http://stackoverflow.com/comment/88830312
comment on: http://stackoverflow.com/q/50915139
score: 4
has text: You shouldn't name variables `input`, it overrides a builtin
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/88975653
has text: You are passing the regex as a string, so the backslash should be doubled, like `\\+` instead of `\+`
score: 1
comment on: http://stackoverflow.com/q/50990333
type: QuestionComment
type: Comment

http://stackoverflow.com/a/50874693
type: Answer
has body: It is set (code) as a field inside the callback: early_stopping_monitor.stopped_epoch will give you the epoch it stopped at after training or 0 if it didn't early stop.
score: 14
upvote count: 14
accepted answer of: http://stackoverflow.com/q/50874596
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50874596

http://stackoverflow.com/comment/88783849
type: Comment
comment on: http://stackoverflow.com/a/50891423
score: 0
type: AnswerComment
has text: I want the output to stay, in this case ['C','A','C'], no matter how many times I run the code. With map, I'll just keep getting random output for each run. I want the dictionary to be generated randomly, but want to use the dictionary to get the same output dataframe for each run.

http://stackoverflow.com/comment/88840048
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50919872
score: 4
has text: **everything** is an object. All instance variables are always objects in Python. Also, you *never use* an instance variable in your second example, you simply pass an instance to the constructor then immediately discard it in `__init__`, and refer to the global name `b` in your method. This is generally a bad practice (the entire point of a class being to avoid global state)

http://stackoverflow.com/q/50897326
upvote count: 1
type: UnansweredQuestion
tagged with: apache-spark
answer count: 0
downvote count: 0
score: 1
has body: I am using the following to add a spark job step to a running emr v5.11.1 cluster on AWS, using python 3.6.5 boto3 and spark 2.2.1: myemr = boto3.client('emr',region_name=os.environ['AWS_DEFAULT_REGION']) response = myemr.add_job_flow_steps( JobFlowId=my_emr_id, Steps=[ { 'Name': key, 'ActionOnFailure': 'CONTINUE', 'HadoopJarStep': { 'Jar': 'command-runner.jar', 'Args': [ 'spark-submit', '--deploy-mode', 'cluster', '--master', 'yarn', '--conf', 'spark.yarn.appMasterEnv.my_password=sensitive_value', '--conf', 'spark.redaction.regex=password', '--class', 'com.myApp', 's3a://myjarurl.jar', '-c', 's3a://s3bucket_myconfig_location', '-w', 'myconfig.json', '-e', 'prod', '-n', 'demo' ] } } ] ) The step is running ok and able to access the yarn environment variable. But the sensitive_value is not redacted from logs or AWS EMR Console, steps tab. I see --conf, spark.yarn.appMasterEnv.my_password=sensitive_value displayed in both. I would like for either the variable spark.yarn.appMasterEnv.my_password to be completely removed from logs and console, or the sensitive_value to be replaced with something like ***. Reading the apache spark doc https://spark.apache.org/docs/2.2.1/configuration.html I thought this would work. Appreciate any suggestions.
has comment: http://stackoverflow.com/comment/108099094
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/90150788
has comment: http://stackoverflow.com/comment/108257836
tagged with: python
tagged with: redaction
has title: Not Working: Redaction of Spark Environment Variable
tagged with: emr

python
tags question: http://stackoverflow.com/q/50901280
tags question: http://stackoverflow.com/q/51002465
tags question: http://stackoverflow.com/q/51008386
tags question: http://stackoverflow.com/q/50983452
tags question: http://stackoverflow.com/q/50951651
tags question: http://stackoverflow.com/q/50934156
tags question: http://stackoverflow.com/q/50957993
tags question: http://stackoverflow.com/q/50868873
tags question: http://stackoverflow.com/q/50962608
tags question: http://stackoverflow.com/q/50880595
tags question: http://stackoverflow.com/q/50858615
tags question: http://stackoverflow.com/q/50975349
tags question: http://stackoverflow.com/q/50949646
tags question: http://stackoverflow.com/q/50888891
tags question: http://stackoverflow.com/q/50856919
tags question: http://stackoverflow.com/q/50987639
tags question: http://stackoverflow.com/q/50929613
tags question: http://stackoverflow.com/q/50932221
tags question: http://stackoverflow.com/q/50952294
tags question: http://stackoverflow.com/q/50858732
tags question: http://stackoverflow.com/q/50962527
tags question: http://stackoverflow.com/q/51010380
tags question: http://stackoverflow.com/q/50933860
tags question: http://stackoverflow.com/q/50865774
tags question: http://stackoverflow.com/q/50939088
tags question: http://stackoverflow.com/q/50965533
tags question: http://stackoverflow.com/q/50971697
tags question: http://stackoverflow.com/q/50939162
tags question: http://stackoverflow.com/q/50954833
tags question: http://stackoverflow.com/q/50983782
tags question: http://stackoverflow.com/q/50981879
tags question: http://stackoverflow.com/q/50937045
tags question: http://stackoverflow.com/q/50863679
tags question: http://stackoverflow.com/q/50892465
tags question: http://stackoverflow.com/q/50893505
tags question: http://stackoverflow.com/q/50962280
tags question: http://stackoverflow.com/q/50893309
tags question: http://stackoverflow.com/q/50983290
tags question: http://stackoverflow.com/q/50882090
tags question: http://stackoverflow.com/q/50856538
tags question: http://stackoverflow.com/q/50957772
tags question: http://stackoverflow.com/q/50890716
tags question: http://stackoverflow.com/q/50909164
tags question: http://stackoverflow.com/q/50937321
tags question: http://stackoverflow.com/q/50918048
tags question: http://stackoverflow.com/q/50915593
tags question: http://stackoverflow.com/q/50899502
tags question: http://stackoverflow.com/q/50961998
tags question: http://stackoverflow.com/q/50901281
tags question: http://stackoverflow.com/q/50930773
tags question: http://stackoverflow.com/q/50910638
tags question: http://stackoverflow.com/q/50863108
tags question: http://stackoverflow.com/q/50997189
tags question: http://stackoverflow.com/q/51009991
tags question: http://stackoverflow.com/q/50873610
tags question: http://stackoverflow.com/q/50901465
tags question: http://stackoverflow.com/q/51004461
tags question: http://stackoverflow.com/q/50941661
tags question: http://stackoverflow.com/q/50981036
tags question: http://stackoverflow.com/q/51009667
tags question: http://stackoverflow.com/q/50886294
tags question: http://stackoverflow.com/q/50911961
tags question: http://stackoverflow.com/q/50993314
tags question: http://stackoverflow.com/q/51007380
tags question: http://stackoverflow.com/q/50948428
tags question: http://stackoverflow.com/q/50936676
tags question: http://stackoverflow.com/q/50979111
tags question: http://stackoverflow.com/q/50974924
tags question: http://stackoverflow.com/q/50918266
tags question: http://stackoverflow.com/q/50949973
tags question: http://stackoverflow.com/q/50991922
tags question: http://stackoverflow.com/q/50870870
tags question: http://stackoverflow.com/q/50965673
tags question: http://stackoverflow.com/q/50929367
tags question: http://stackoverflow.com/q/50976954
tags question: http://stackoverflow.com/q/50919547
tags question: http://stackoverflow.com/q/50974722
tags question: http://stackoverflow.com/q/50917997
tags question: http://stackoverflow.com/q/50909957
tags question: http://stackoverflow.com/q/50887274

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

http://stackoverflow.com/a/50969662
answers question: http://stackoverflow.com/q/50969366
score: 0
type: Answer
has body: print type(clr) will print &lt;type 'list'&gt; since it is a list. if You keep clr = np.uint8([[[0,255,0 ]]]) print type(clr) this will give you result as &lt;type 'numpy.ndarray'&gt; or else clr = [np.uint8([[[0,255,0 ]]])] print type(clr[0]) print type(clr) output will be &lt;type 'numpy.ndarray'&gt; &lt;type 'list'&gt; Hope you got the point.

http://stackoverflow.com/a/50866348
answers question: http://stackoverflow.com/q/50865899
score: 0
type: Answer
has body: The following might work. import pandas as pd import numpy as np dfg_item_info = item_info.groupby(["ccy", "seller"]) def fillna(x): if np.isnan(x["C"]): return (dfg_item_info .get_group((x["ccy"], x["seller"]))["item"] .values[0]) else: return x["item"] qty["item] = qty["item"].apply(fillna, axis=1)

http://stackoverflow.com/q/50887821
tagged with: tf-idf
type: UnansweredQuestion
tagged with: python
tagged with: vectorization
upvote count: 0
has title: How to use GloVe to generate vector matrix?
type: Question
has answer: http://stackoverflow.com/a/50890602
score: -1
has body: I am using HDBSCAN algorithm to create clusters from the documents I have. But to create a vector matrix from the words, I am using tf-idf algorithm and want to use GloVe. I have searched posts but could not understand how to use this algorithm. I also read about Gensim but did not understand how could I use this to implement GloVe. Here is what I am doing: import numpy as np import pandas as pd import nltk import re import os import codecs from sklearn import feature_extraction import mpld3 import csv import string import time import sys import matplotlib.pyplot as plt from sklearn.metrics.pairwise import cosine_similarity from sklearn.externals import joblib from nltk.stem.snowball import SnowballStemmer from sklearn.feature_extraction.text import TfidfVectorizer import hdbscan csvRows = [] nltk.download('stopwords') title = [] synopses = [] filename = "twitter-test-dataset.csv" num_clusters = 10 pkl_file = "doc_cluster.pkl" generate_pkl = False # pre-process data with open(filename, 'r') as csvfile: # creating a csv reader object csvreader = csv.reader(csvfile) # extracting field names through first row fields = csvreader.next() # extracting each data row one by one duplicates = 0 for row in csvreader: # removes the characters specified line = re.sub(r'[.,"!]+', '', row[2], flags=re.MULTILINE) line = re.sub(r'^RT[\s]+', '', line, flags=re.MULTILINE) # removes RT line = re.sub(r'https?:\/\/.*[\r\n]*', '', line, flags=re.MULTILINE) # remove link line = re.sub(r'[:]+', '', line, flags=re.MULTILINE) line = (re.sub( "(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)", " ", line, flags=re.MULTILINE)) line = filter(lambda x: x in string.printable, line) # filter non-ascii characers if line not in synopses: synopses.append(line) title.append(row[2]) else: duplicates += 1 print("Removed " + str(duplicates) + " rows") stopwords = nltk.corpus.stopwords.words('english') stemmer = SnowballStemmer("english") def tokenize_and_stem(text): # first tokenize by sentence, then by word…
answer count: 1
downvote count: 1
favorite count: 0
tagged with: hdbscan

http://stackoverflow.com/q/50882547
has comment: http://stackoverflow.com/comment/88767476
has comment: http://stackoverflow.com/comment/88767521
has body: I am writing a program that scrapes a website and extracts the names and the links from a table. I store each name and respective link in an object and append it to a list of objects by running a for loop. I want to save this list as a csv file, but haven't been able to do so using the filewriter as it converts the whole object to str, which is not what I want. I would be really grateful if someone can guide me with this. Here is my code: from selenium import webdriver from bs4 import BeautifulSoup class Player(): def __init__(self): self.name = "" self.link = "" player_list = [] driver = webdriver.PhantomJS(executable_path = r'C:\Users\sarim\Desktop\Scraper\phantomjs.exe') driver.get('https://dak.gg/ranks/na/solo-fpp/rating') pause = 0 lastHeight = driver.execute_script("return document.body.scrollHeight") while True: driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") time.sleep(pause) newHeight = driver.execute_script("return document.body.scrollHeight") if newHeight == lastHeight: break lastHeight = newHeight html_doc = driver.page_source soup = BeautifulSoup(html_doc, 'lxml') players = soup.find('table', class_ = 'list rating') player_names = players.find_all('td', class_ = 'nick') add_link = "https://dak.gg" for i in player_names[0:3]: newPlay = Player() n = i.find('a') l = add_link + n['href'] newPlay.link = l newPlay.name = n.text.strip() #print newPlay.name #print newPlay.link player_list.append(newPlay) #print players_names[1] driver.quit()
answer count: 1
score: 6
favorite count: 0
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/50882994
tagged with: python
tagged with: file-writing
upvote count: 7
downvote count: 1
type: Question
tagged with: object
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50882994
tagged with: screen-scraping
has title: Storing a list of objects as csv in python

http://stackoverflow.com/a/50901553
has comment: http://stackoverflow.com/comment/88803305
score: 2
upvote count: 2
downvote count: 0
has body: You can use the following nested for loops: for f in *Genes.GeneSet do for i in `seq 1 22` do python make_annot.py --gene-set-file "${f}" --bimfile ../../1000G_EUR_Phase3_plink/1000G.EUR.QC.${i}.bim --annot-file `echo "${f}" | grep -oP '^.*(?=Genes.Geneset$)'`.${i}.annot.gz; done done This will loop on all your CELL_TYPEGenes.GeneSet and your CELL_TYPE.${i}.annot.gz to generate your 31 * 22 = 682 files combinations Where echo "${f}" | grep -oP '^.*(?=Genes.Geneset$)' is used to get the CELL_TYPE part of the filename
type: Answer
answers question: http://stackoverflow.com/q/50901491

http://stackoverflow.com/comment/88866155
has text: Agreed. I ended up getting a solution from the Plotly community for those interested: https://community.plot.ly/t/visualizing-mri-volume-slices-in-offline-mode/11004
comment on: http://stackoverflow.com/a/50927980
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/50929781
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50929367
has comment: http://stackoverflow.com/comment/88860853
has body: This may help as in str2 you are searching specific keyword which is "mn" so we split str1 into simple list of words and then traverse the list to find occurrences of partial mn in items. mylist = ['abc', 'def', 'ghi', 'jkl', 'mno'] str1 = 'does mn have anything to do with it?' str2 = 'I think mn is there' for i in str1.split(" "): for j in mylist: if i in j: print("match found and its for " + i + " which is partially exist in " + j)

http://stackoverflow.com/comment/88845886
comment on: http://stackoverflow.com/q/50923112
has text: I think you misunderstand what Lock does. It doesn't lock access to `i`, it just locks access to the lock itself, until it's released. So the 1,000,000 locks your code creates don't do anything useful, they just waste time.
type: Comment
type: QuestionComment
score: 0

authentication
tags question: http://stackoverflow.com/q/50884337
tags question: http://stackoverflow.com/q/50926614
tag name: authentication
type: Tag
tags question: http://stackoverflow.com/q/50997759
tags question: http://stackoverflow.com/q/50887479
tags question: http://stackoverflow.com/q/50982086
tags question: http://stackoverflow.com/q/50933529
tags question: http://stackoverflow.com/q/50886444

http://stackoverflow.com/comment/88818403
type: AnswerComment
has text: Thank you for the quick reply! so the best way you think would be directly through pandas? I attached a picture but it did not seem to have been posted. My main issue is categorizing the list or dataframe by each subject when on collumn 1 i have the names of the subject for each measurement and on collumn 2 i have the measurments. I know this is a little confusing, ill try and see if I can read that into a dataframe byt doing some more researching, if not ill rephrase my question clearer and repost.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/50909168

http://stackoverflow.com/comment/88726680
type: Comment
has text: This (computer vision with plants) just so happens to be an integral part of the project I have been working on professionally for the past 6 months. If you have any other questions about your project, feel free to DM me in the future!
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50861978

http://stackoverflow.com/comment/88751940
type: AnswerComment
score: 0
type: Comment
has text: `from typing import NamedTuple`
comment on: http://stackoverflow.com/a/50874566

http://stackoverflow.com/q/50919871
answer count: 0
tagged with: python-2.4
type: Question
has comment: http://stackoverflow.com/comment/88873048
has comment: http://stackoverflow.com/comment/88839497
score: 0
has comment: http://stackoverflow.com/comment/88839625
tagged with: wxpython
has title: Wxpython GUI is not same on python2
type: UnansweredQuestion
has body: I'm trying to change the code written in python3 to python2.4. Python3 version code run on window well but in python2.4 and Centos5.11, GUI is not same even it run same code. in window, python3 in centos, python2.4 The gui code is below: class Panel(wx.Panel): global WTIME def __init__(self, parent, site): wx.Panel.__init__(self, parent,wx.ID_ANY, pos=wx.DefaultPosition, size=wx.Size(600,100), style=wx.TAB_TRAVERSAL) self.site = site bSizer = wx.BoxSizer(wx.VERTICAL) self.canvas = PlotCanvas(self, 0) self.canvas.SetYSpec("none") self.canvas.Draw(drawBarGraph(self.site), xAxis=(0,12), yAxis=(0,1)) bSizer.Add(self.canvas, 1, wx.EXPAND) self.SetSizer(bSizer) self.canvas.SetEnableGrid(False) self.Layout() def updateGraph(self, site_log): self.canvas.Draw(drawBarGraph(self.site, site_log), xAxis=(0,WTIME), yAxis=(0,1)) class MainFrame(wx.Frame): def __init__(self): """Constructor""" wx.Frame.__init__(self, None, title="NoName", size=(1250,500)) self.scroll = wx.ScrolledWindow(self, -1, size=(1250,500)) self.scroll.SetScrollbars(1,1,1400,1600) topSizer = wx.BoxSizer(wx.VERTICAL) panelSizer1 = wx.BoxSizer(wx.HORIZONTAL) panelSizer2 = wx.BoxSizer(wx.HORIZONTAL) panelSizer3 = wx.BoxSizer(wx.HORIZONTAL) panelSizer4 = wx.BoxSizer(wx.HORIZONTAL) self.p1 = Panel(self.scroll, "SITE1") self.p2 = Panel(self.scroll, "SITE2") self.p3 = Panel(self.scroll, "SITE3") self.p4 = Panel(self.scroll, "SITE4") self.p5 = Panel(self.scroll, "SITE5") self.p6 = Panel(self.scroll, "SITE6") self.p7 = Panel(self.scroll, "SITE7") self.p8 = Panel(self.scroll, "SITE8") self.panels = [self.p1, self.p2, self.p3, self.p4, self.p5, self.p6, self.p7, self.p8] panelSizer1.Add(self.p1, 0, wx.ALL|wx.EXPAND,5) panelSizer1.Add(self.p2, 0, wx.ALL|wx.EXPAND,5) panelSizer2.Add(self.p3, 0, wx.ALL|wx.EXPAND,5) panelSizer2.Add(self.p4, 0, wx.ALL|wx.EXPAND,5) panelSizer3.Add(self.p5, 0, wx.ALL|wx.EXPAND,5) panelSizer3.Add(self.p6, 0, wx.ALL|wx.EXPAND,5) panelSizer4.Add(self.p7, 0, wx.ALL|wx.EXPAND,5) panelSizer4.Add(sel…
tagged with: python

http://stackoverflow.com/comment/88957118
score: 1
type: QuestionComment
has text: it solves the problem!! thank you!!
comment on: http://stackoverflow.com/q/50978954
type: Comment

http://stackoverflow.com/q/50871201
has comment: http://stackoverflow.com/comment/88744476
answer count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/50871541
tagged with: arrays
has comment: http://stackoverflow.com/comment/88744377
favorite count: 0
score: 0
has comment: http://stackoverflow.com/comment/88744204
has comment: http://stackoverflow.com/comment/88744115
has answer: http://stackoverflow.com/a/50871298
downvote count: 1
tagged with: python
has title: How to search for a set of words in a text file?
has comment: http://stackoverflow.com/comment/88744864
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88744114
tagged with: text
has body: I'm writing a project on extracting a semantic orientation from a review stored in a text file. I have a 400*2 array, each row contains a word and it's weight. I want to check which of these words is in the text file, and calculate the weight of the whole content. My question is - what is the most efficient way to do it? Should I search for each word separately, for example with a for loop? Do I get any benefit from storing the content of the text file in a string object?
type: Question

http://stackoverflow.com/comment/88984715
type: Comment
type: AnswerComment
has text: I tried your solution and it did not work. Are you using the multipart parser because the documentations say you need to in order to process multipart/form-data.
comment on: http://stackoverflow.com/a/50979970
score: 0

http://stackoverflow.com/comment/89010748
has text: The upgrade message is just a warning, 'should consider' is not the same thing as 'must'. There is a PermissionError there, where you can't write to the `C:\\Program Files\\Anaconda3\\Lib\\site-packages` folder. That's not an error upgrading `pip` will solve, I'm afraid.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51008838
score: 0

http://stackoverflow.com/q/50984899
tagged with: flask-sqlalchemy
score: 0
tagged with: python
type: UnansweredQuestion
has title: sqlalchemy wtih python ThreadPool and Flask
has body: I have a database of images that need to be processed. Each image takes around a minute to process. I'm trying to make it multi-threaded. I'm having trouble entering data into the database in a worker thread. For some reason, the data isn't saved. Here is what the code looks like. images = Images.query.all() images_ = [] for image in images: images_.append(image) pool = ThreadPool() pool.map(dostuff, (images_)) pool.close() pool.join() def dostuff(image): # do stuff image.done = True db.session.commit() Any ideas what could be happening? I also tried to pass the session into dostuff(image, session) but that didn't work either. Any help is appreciated!
tagged with: threadpool
tagged with: sqlalchemy
type: Question
has answer: http://stackoverflow.com/a/51994141
answer count: 1
tagged with: flask

http://stackoverflow.com/comment/88806495
comment on: http://stackoverflow.com/q/50903270
type: Comment
type: QuestionComment
has text: I mean i made the changes in the code that you suggested but sill i get the same error
score: 0

http://stackoverflow.com/a/50903990
downvote count: 0
score: 1
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/88833979
has body: The Reader class is not defined in a top-level reader module. Rather, it's defined in reader.reader, since the top level reader is a package. If your current code that's causing the error is: import reader r= reader.Reader('test.gzip') You need to change it to use reader.reader instead of just reader: import reader.reader r = reader.reader.Reader('test.gzip') Or alternatively, you could move the contents of reader/reader.py into reader/__init__.py, since the latter file is where the contents of the reader package are defined. Or you could split the difference, and keep the reader.py file while still making the class available at package level, using something like this in __init__.py (note I've not tested this, there are some weird corner cases with relative imports from __init__.py files): from .reader import Reader
accepted answer of: http://stackoverflow.com/q/50902445
has comment: http://stackoverflow.com/comment/88836848
answers question: http://stackoverflow.com/q/50902445
type: AcceptedAnswer

http://stackoverflow.com/q/50868792
favorite count: 0
has body: I'm attempting to access my personal Apple Music library using the MusicKit API. I'm building a Python web application that uses it. I wasn't sure how I could generate a personalized Apple Music User Token. The process appears to be a tad more convoluted than the process for a Developer Token. I'm also unfamiliar with XCode and Swift - I'd appreciate some hand-holding if the solution requires those. Thanks!
has title: How do I create a personalized Music User Token in Apple Music?
type: UnansweredQuestion
tagged with: python
tagged with: apple-musickit
score: 2
upvote count: 2
type: Question
has answer: http://stackoverflow.com/a/50879393
tagged with: ios
tagged with: apple-music
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/64418342

http://stackoverflow.com/comment/88759960
comment on: http://stackoverflow.com/a/50878705
has text: @juanpa.arrivillaga Saying that Python _never_ passes by _reference_ is misleading because it does _always_ do the same thing. However, you are right, and I have updated my answer to reflect the fact that it passes arguments by object reference. Keeping the answer up because it's definitely not the most far-fetched thing anyone would want to do.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/56878814
answers question: http://stackoverflow.com/q/50951955
score: 6
upvote count: 6
has body: On Mac, you can install it like shown below. This works for me. brew install tesseract
downvote count: 0
type: Answer

django-models
tag name: django-models
tags question: http://stackoverflow.com/q/50984323
tags question: http://stackoverflow.com/q/50877270
tags question: http://stackoverflow.com/q/50870950
tags question: http://stackoverflow.com/q/50980831
tags question: http://stackoverflow.com/q/50917685
tags question: http://stackoverflow.com/q/50871526
tags question: http://stackoverflow.com/q/50938119
tags question: http://stackoverflow.com/q/50922794
tags question: http://stackoverflow.com/q/50916730
tags question: http://stackoverflow.com/q/50982334
tags question: http://stackoverflow.com/q/50982757
tags question: http://stackoverflow.com/q/50991920
tags question: http://stackoverflow.com/q/50955605
tags question: http://stackoverflow.com/q/50993171
tags question: http://stackoverflow.com/q/50915911
tags question: http://stackoverflow.com/q/50874737
tags question: http://stackoverflow.com/q/50913121
tags question: http://stackoverflow.com/q/50970667
tags question: http://stackoverflow.com/q/50915120
tags question: http://stackoverflow.com/q/50991487
type: Tag
tags question: http://stackoverflow.com/q/50948274
tags question: http://stackoverflow.com/q/50895969
tags question: http://stackoverflow.com/q/50925513
tags question: http://stackoverflow.com/q/50930821
tags question: http://stackoverflow.com/q/50969522
tags question: http://stackoverflow.com/q/50923553
tags question: http://stackoverflow.com/q/50872142
tags question: http://stackoverflow.com/q/50866574
tags question: http://stackoverflow.com/q/50859307
tags question: http://stackoverflow.com/q/51010549
tags question: http://stackoverflow.com/q/50895730
tags question: http://stackoverflow.com/q/50953809
tags question: http://stackoverflow.com/q/50889026
tags question: http://stackoverflow.com/q/51009512
tags question: http://stackoverflow.com/q/50875816
tags question: http://stackoverflow.com/q/50955203
tags question: http://stackoverflow.com/q/50950864
tags question: http://stackoverflow.com/q/50908642
tags question: http://stackoverflow.com/q/50972893
tags question: http://stackoverflow.com/q/50982990
tags question: http://stackoverflow.com/q/50951852
tags question: http://stackoverflow.com/q/51008203
tags question: http://stackoverflow.com/q/50880854
tags question: http://stackoverflow.com/q/50969484
tags question: http://stackoverflow.com/q/50858571
tags question: http://stackoverflow.com/q/51005163
tags question: http://stackoverflow.com/q/50936123

http://stackoverflow.com/comment/88750185
score: 1
comment on: http://stackoverflow.com/q/50872574
type: Comment
type: QuestionComment
has text: Try this `file = "hdfs://data/logs/*logs_455DD_33*.csv"`

http://stackoverflow.com/comment/88770672
score: 0
type: Comment
has text: Yes exactly same its now working. i added a `sleep` command before now i renamed it now its working fine... thank you...
comment on: http://stackoverflow.com/a/50880104
type: AnswerComment

http://stackoverflow.com/comment/88847953
type: Comment
comment on: http://stackoverflow.com/a/50911946
type: AnswerComment
has text: Ok, Im trying to split the res to drop duplicates and then concatenate list comprehension of series. If this doesnt work Ill ask a separate qusetion and invite you to answer, thx for your time.
score: 0

http://stackoverflow.com/comment/88939647
comment on: http://stackoverflow.com/q/50970937
has text: Are you using any salt to hash? (you should) Is it the **same** salt on both sides?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50880175
answer count: 1
downvote count: 0
favorite count: 0
linked to: http://stackoverflow.com/q/1009712
tagged with: beautifulsoup
type: UnansweredQuestion
tagged with: web-scraping
has body: I am trying to extract data from website and have following code which is extracting all URLs from Main category and its sub category links. I am now stuck in saving the extracted output with line separator (to move each URL in separate line) in a file -Medical.tsv Need help on this. Code is given below: from bs4 import BeautifulSoup import requests import time import random def write_to_file(file,mode, data, newline=None, with_tab=None): #** with open(file, mode, encoding='utf-8') as l: if with_tab == True: data = ''.join(data) if newline == True: data = data+'\n' l.write(data) def get_soup(url): return BeautifulSoup(requests.get(url).content, "lxml") url = 'http://www.medicalexpo.com/' soup = get_soup(url) raw_categories = soup.select('div.univers-main li.category-group-item a') category_links = {} for cat in (raw_categories): t0 = time.time() response_delay = time.time() - t0 # It wait 10x longer than it took them to respond using delay. time.sleep(10*response_delay) # This way if the site gets overwhelmed and starts to slow down, the code will automatically back off. time.sleep(random.randint(2,5)) # This will provide random time intervals of 2 and 3 secs acting as human crawl instead of bot. soup = get_soup(cat['href']) links = soup.select('#category-group li a') category_links[cat.text] = [link['href'] for link in links] print(category_links)
tagged with: python
tagged with: python-requests
has answer: http://stackoverflow.com/a/50880291
score: 1
type: Question
upvote count: 1
has title: Saving output URLs with next line in file

datetimeoffset
type: Tag
tags question: http://stackoverflow.com/q/50948852
tag name: datetimeoffset

http://stackoverflow.com/comment/88845491
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50922946
has text: Using `pandas` is a bit of a ten ton hammer imo :)

http://stackoverflow.com/a/50948462
type: Answer
has body: It seems to me you may use reObj = re.compile(""" \[D\]\. \s* # [D]. and 0+ whitespaces (?: # An optional alternation group (?P&lt;PLACE&gt;[^,:]*) # Group "PLACE": 0+ chars other than , and : (?: # An optional sequence of : \s* (?P&lt;HOLDER&gt;[^,:]*) # :, 0+ whitespaces, Group "HOLDER" (0+ non-colons and non-commas) )? (?: # An optional sequence of ,\s* (?P&lt;YEAR&gt;[12]\d{3}) # , + 0+ whitespaces, Group "YEAR" (1 or 2 and then three digits )? )? $ # end of string """, flags=re.X) See the regex and Python demos: import re reObj = re.compile( r"\[D\]\.\s*(?:(?P&lt;PLACE&gt;[^,:]*)(?::\s*(?P&lt;HOLDER&gt;[^,:]*))?(?:,\s*(?P&lt;YEAR&gt;[12]\d{3}))?)?$", re.VERBOSE ) txt = '''Smith. The paper name. The subtitle of paper[D]. US: MIT, 2011 Smith. The paper name. The subtitle of paper[D]. US, 2011 Smith. The paper name. The subtitle of paper[D]. US: MIT'''.split('\n') for i in txt: print('------------------------\nTESTING {}'.format(i)) m = reObj.search(i) if m: if not m.group('PLACE'): print('missing place') else: print(m.group('PLACE')) if not m.group('YEAR'): print('missing year') else: print(m.group('YEAR')) Output: ------------------------ TESTING Smith. The paper name. The subtitle of paper[D]. US: MIT, 2011 US 2011 ------------------------ TESTING Smith. The paper name. The subtitle of paper[D]. US, 2011 US 2011 ------------------------ TESTING Smith. The paper name. The subtitle of paper[D]. US: MIT US missing year
has comment: http://stackoverflow.com/comment/88963542
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/50946163
has comment: http://stackoverflow.com/comment/88962597
answers question: http://stackoverflow.com/q/50946163
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88962856

http://stackoverflow.com/a/52724994
has body: Try pptk (point processing toolkit). The package has a 3-d point cloud viewer that directly takes a 3-column numpy array as input, and is able to interactively visualize 10-100 million points. (It reduces the number of points that needs rendering in each frame by using an octree to cull points outside the view frustum and to approximate groups of far away points as single points) To install, &gt;&gt; pip install pptk To visualize 100 randomly generated points in Python, &gt;&gt; import pptk &gt;&gt; import numpy as np &gt;&gt; P = np.random.rand(100,3) &gt;&gt; v = pptk.viewer(P) screenshot of pptk viewer visualizing 100 random points The documentation website also has a tutorial specifically on visualizing point clouds loaded from .ply files.
has comment: http://stackoverflow.com/comment/104563958
type: Answer
has comment: http://stackoverflow.com/comment/118063879
answers question: http://stackoverflow.com/q/50965673
has comment: http://stackoverflow.com/comment/103597825
has comment: http://stackoverflow.com/comment/106994945
has comment: http://stackoverflow.com/comment/92397585
downvote count: 1
has comment: http://stackoverflow.com/comment/92496698
score: 14
has comment: http://stackoverflow.com/comment/96613271
upvote count: 15
has comment: http://stackoverflow.com/comment/115145833
has comment: http://stackoverflow.com/comment/106930910

http://stackoverflow.com/a/50949570
downvote count: 0
score: 1
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/50949318
accepted answer of: http://stackoverflow.com/q/50949318
has body: I think the first step would be to get your hands on or to generate some labelled training data. You should look into at feature extraction; for example, if you notice that for a certain item, the second line is usually the price, you could represent that as a parameter. Or say if a number is followed by a unit like ml/l/oz, it's likely to be the volume. What you want to know is how confident you are that a specific line/string is say the price. However, I think TensorFlow would be more suited for the OCR portion of the problem, which you have already solved. What you are asking is more towards text parsing, which could be better solved with an NLP approach.
type: AcceptedAnswer

http://stackoverflow.com/comment/88922004
type: Comment
type: QuestionComment
has text: Updated my question; I see the file content when I print list_words
comment on: http://stackoverflow.com/q/50962318
score: 0

http://stackoverflow.com/comment/88728201
comment on: http://stackoverflow.com/q/50862801
score: 0
type: Comment
has text: I just tried it, all the given strings are printed back to me, including one '', but I can give further inputs and it won't stop... eg. 1. 1. 1. '1. 1. 1.' 2. 2. 2. '2. 2. 2.' ''
type: QuestionComment

pyqt
type: Tag
tags question: http://stackoverflow.com/q/50982003
tags question: http://stackoverflow.com/q/50955501
tags question: http://stackoverflow.com/q/50967870
tags question: http://stackoverflow.com/q/50914252
tags question: http://stackoverflow.com/q/50929090
tags question: http://stackoverflow.com/q/50880660
tags question: http://stackoverflow.com/q/50868830
tags question: http://stackoverflow.com/q/50960316
tags question: http://stackoverflow.com/q/50977603
tags question: http://stackoverflow.com/q/50923163
tags question: http://stackoverflow.com/q/50955182
tags question: http://stackoverflow.com/q/50929322
tags question: http://stackoverflow.com/q/50887951
tags question: http://stackoverflow.com/q/50914555
tags question: http://stackoverflow.com/q/51000507
tags question: http://stackoverflow.com/q/50864170
tags question: http://stackoverflow.com/q/50966786
tags question: http://stackoverflow.com/q/50915351
tags question: http://stackoverflow.com/q/50926888
tags question: http://stackoverflow.com/q/50915464
tags question: http://stackoverflow.com/q/50890645
tags question: http://stackoverflow.com/q/50864375
tags question: http://stackoverflow.com/q/50905170
tags question: http://stackoverflow.com/q/50980192
tags question: http://stackoverflow.com/q/50956886
tags question: http://stackoverflow.com/q/50953477
tags question: http://stackoverflow.com/q/50985090
tags question: http://stackoverflow.com/q/50941424
tags question: http://stackoverflow.com/q/50982375
tags question: http://stackoverflow.com/q/50880850
tags question: http://stackoverflow.com/q/50885667
tags question: http://stackoverflow.com/q/50951872
tags question: http://stackoverflow.com/q/50907375
tags question: http://stackoverflow.com/q/50939373
tags question: http://stackoverflow.com/q/50981097
tags question: http://stackoverflow.com/q/50894347
tags question: http://stackoverflow.com/q/50892264
tags question: http://stackoverflow.com/q/50861450
tag name: pyqt
tags question: http://stackoverflow.com/q/50858666
tags question: http://stackoverflow.com/q/50915949
tags question: http://stackoverflow.com/q/50930792
tags question: http://stackoverflow.com/q/50870845
tags question: http://stackoverflow.com/q/50917165

http://stackoverflow.com/comment/90636209
score: 0
type: AnswerComment
has text: just try to print the status and check if states are changing or not. If not check the asterisk server if properly installed or not. If server configuration is ok, it should trigger the flags correctly.
type: Comment
comment on: http://stackoverflow.com/a/50909695

http://stackoverflow.com/a/50971248
has comment: http://stackoverflow.com/comment/88959662
has body: img1 = cv2.imread('Tarun.jpg',0) As you know, imread reads in the specified image. With just the filename, as here, python tries to read the image from the current working directory. If the file does not exist, no error is reported and img1 will have a value of None. That this line: cv2.imshow('Hey its me Tarun yellogi',img1) returns an error of: error: C:\projects\opencv-python\opencv\modules\highgui\src\window.cpp:331: error: (-215) size.width&gt;0 &amp;&amp; size.height&gt;0 in function cv::imshow means that the image specified in the imshow command (i.e. img1) has a width and/or a height of 0. What the error message is saying is that the image in function imshow must have a size where the width is greater than zero and the height is greater than zero. You can check the image size with img1.shape. In this case you will probably get an error message AttributeError: 'NoneType' object has no attribute 'shape'. You can further check if img1 is None with img1 == None. If you get a response of True then you will know that img1 does not contain image data. TL;DR The file 'Tarun.jpg' was not found thus img1 == None.
type: Answer
score: 3
answers question: http://stackoverflow.com/q/50938738
downvote count: 1
upvote count: 4

docker
tags question: http://stackoverflow.com/q/50971175
type: Tag
tags question: http://stackoverflow.com/q/50926347
tags question: http://stackoverflow.com/q/50918102
tags question: http://stackoverflow.com/q/50862085
tags question: http://stackoverflow.com/q/50938370
tags question: http://stackoverflow.com/q/50977361
tags question: http://stackoverflow.com/q/50919752
tags question: http://stackoverflow.com/q/50974960
tags question: http://stackoverflow.com/q/50878337
tags question: http://stackoverflow.com/q/50884396
tags question: http://stackoverflow.com/q/50923582
tags question: http://stackoverflow.com/q/50920705
tag name: docker
tags question: http://stackoverflow.com/q/51006382
tags question: http://stackoverflow.com/q/50906214
tags question: http://stackoverflow.com/q/50917570
tags question: http://stackoverflow.com/q/50876784
tags question: http://stackoverflow.com/q/50865974
tags question: http://stackoverflow.com/q/50956539
tags question: http://stackoverflow.com/q/50878533
tags question: http://stackoverflow.com/q/50950588
tags question: http://stackoverflow.com/q/50993271
tags question: http://stackoverflow.com/q/50995707
tags question: http://stackoverflow.com/q/50957848
tags question: http://stackoverflow.com/q/50935649
tags question: http://stackoverflow.com/q/50953930
tags question: http://stackoverflow.com/q/50955274
tags question: http://stackoverflow.com/q/50966018

http://stackoverflow.com/q/50863162
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/50863371
tagged with: psutil
accepted answer: http://stackoverflow.com/a/50863371
linked to: http://stackoverflow.com/q/50866386
has comment: http://stackoverflow.com/comment/88732145
type: Question
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/88731468
favorite count: 0
has comment: http://stackoverflow.com/comment/88731105
tagged with: ssh
tagged with: python
has title: subprocess and psutil : how to get a list out of subprocess.check_output?
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88731771
tagged with: subprocess
has body: I am willing to determine the current CPU usage of a bunch of Linux computers, all available via SSH connexion. As for now I have managed something via the psutil and subprocess modules, but it could be much more straightforward if I could get a list out of subprocess.check_output. So I defined a cpu_script.py : import psutil print(psutil.cpu_percent(interval=1,percpu=True)) to be called in my main script, which is in the same folder, with: import subprocess import os import numpy as np import psutil usr = "AA" computer = "BB" cpu_script = os.path.join(os.getcwd(),"cpu_script.py") test = subprocess.check_output("ssh -X " + usr + "@" + computer + "python3 -u - &lt; " + cpu_script,shell=True).strip() As cpu_percent's outputs are typically in a list, I would expect my "test" variable to be a list, but what I really get is a byte: input(test) &gt;&gt; b'[4.0, 5.0, 7.0, 10.9, 18.4, 1.0, 4.0, 3.0]' input(type(test)) &gt;&gt; &lt;class 'bytes'&gt; Here I have managed to bend everything to finally get an array (with decode + replace + np.fromstring), but it is far from satisfying: tmp = test.decode("utf-8") input(tmp) &gt;&gt; [4.0, 5.0, 7.0, 10.9, 18.4, 1.0, 4.0, 3.0] input(type(tmp)) &gt;&gt; &lt;class 'str'&gt; tmp = (tmp.replace('[','')).replace(']','') result = np.fromstring(tmp, sep=',') input(result) &gt;&gt; [ 4. 5. 7. 10.9 18.4 1. 4. 3. ] input(type(result)) &gt;&gt; &lt;class 'numpy.ndarray'&gt; Could'nt I have straightaway a subprocess.check_output variable that is a list or an array ? What am I missing ? Also if there is a way to avoid defining a cpu_script, hence to pass directly the python command in the subprocess, I would be interested ! I have failed at all my attempts to do so for now, the tricky part here being that there is both a ssh connexion and a python3 console command followed by python commands. Thanks for your help!
type: AnsweredQuestion

http://stackoverflow.com/a/50994787
upvote count: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/50992705
answers question: http://stackoverflow.com/q/50992705
score: 2
type: AcceptedAnswer
downvote count: 0
has body: On top of python 2.7 installed on the "python" command, I also had python 2.6 installed on the "python2" command. Uninstalling python 2.6 solved the issue, Google Cloud install went through without issue on the next try.

http://stackoverflow.com/q/50859944
tagged with: http-post
downvote count: 0
score: 1
favorite count: 0
has body: I have the below code which i've written after looking over many over modules and questions on stack, but i keep getting back a 500 reponse error when trying to submit an order? the text of the resposne is always something like "Internal sever error" followed by a 13? digit number that is always different import requests import json my_aid = xxxxxxxx loan_id = yyyyyyyyy url = 'htpps://api.lendingclub.com/api/investors/v1/accounts/xxxxxxxxx/orders' header = {'Authorization':*my_AUTH*} payload = { 'aid':my_aid, 'orders':[{ 'loanId':loan_id, 'requestedAmount':25.0, }] } resp = requests.post(url,headers=header,data=json.dumps(payload)) any thoughts?
type: Question
tagged with: python
has title: LendingClub Rest API Submit Order reponse 500 Internal Server Error
has answer: http://stackoverflow.com/a/50863283
upvote count: 1
tagged with: request
answer count: 1
tagged with: lending-club-api
type: UnansweredQuestion
tagged with: post

http://stackoverflow.com/a/50970790
score: 1
has comment: http://stackoverflow.com/comment/88938512
has comment: http://stackoverflow.com/comment/88945058
has comment: http://stackoverflow.com/comment/88938741
has comment: http://stackoverflow.com/comment/88938881
has comment: http://stackoverflow.com/comment/88945983
answers question: http://stackoverflow.com/q/50969805
upvote count: 1
has body: The first thing to notice is that you are using %s with patients_data[pd]. I assume patients_data is a list of the names of the patients, which means you are constructing a different output path for each patient - you are asking numpy to save each of your processed images to a new location. Secondly, .npy is probably not the file type you want to use for your purposes, as it does not handle appending data. You probably want to pick a different file type, and then np.save() to the same file path each time. Edit: Regarding file type, a pdf may be your best option, where you can make each of your images a separate page.
type: Answer
downvote count: 0

http://stackoverflow.com/q/50945618
answer count: 2
accepted answer: http://stackoverflow.com/a/50945750
possible better answer: http://stackoverflow.com/a/50945737
has answer: http://stackoverflow.com/a/50945737
favorite count: 0
tagged with: while-loop
has answer: http://stackoverflow.com/a/50945750
tagged with: python
tagged with: dictionary
downvote count: 4
type: AnsweredQuestion
upvote count: 0
tagged with: list
has body: liste = [] while True: key = input("key: ") val = input("val: ") words = ('"{}":"{}"'.format(key,val)) liste.append(words) if len(liste)&gt;=16: #I have 16 words per page print(liste) Here is my code. It is working but when I print the list, it is like: liste = ['"key1","val1"','"key2","val2"','"key3","val3"'] As you can see, there are prime marks (') at the beginning and end of every item. So if I copy and paste those keys and values to my dictionary it won't work. How can I delete these prime marks from my list?
has title: I created a program, I input keys and values to add to a dictionary but it doesn't work properly
score: -4
type: Question
tagged with: format
has comment: http://stackoverflow.com/comment/88888646
has comment: http://stackoverflow.com/comment/88888690
has comment: http://stackoverflow.com/comment/88888615

http://stackoverflow.com/comment/88953836
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50978994
has text: You should just use a single thread ... in the above each `Timer` is a separate thread, and will only run its target *once*
score: 0

http://stackoverflow.com/comment/88955712
score: 1
comment on: http://stackoverflow.com/q/50979323
type: QuestionComment
type: Comment
has text: @OlivierMelançon On further reflection, when comparing `{x: 0} == {y: 0}` (where x and y are distinct self-containing lists), is TOOWTDI to ensure you get the same exception as `{0: x} == {0: y}`? Or whatever would happen if `x` were a self-containing tuple created by the C API? True (for the same reason as hypersets in anti-foundation set theory)? I was trying to get False to work, but that actually seems like the least defensible option, and I’m not sure anymore why that was my first instinct.

http://stackoverflow.com/comment/88942161
type: QuestionComment
has text: @Ben.T there is not a block ID in the original data, but it can easily be added.
comment on: http://stackoverflow.com/q/50970476
score: 0
type: Comment

http://stackoverflow.com/q/50935910
tagged with: list
has answer: http://stackoverflow.com/a/50936100
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50936063
tagged with: counter
type: Question
score: 0
answer count: 3
has body: I'n being warned that this question has been frequently downvoted, but I haven't seen a solution for my particular problem. I have a dictionary that looks like this: d = {'a': [['I', 'said', 'that'], ['said', 'I']], 'b':[['she', 'is'], ['he', 'was']]} I would like for the output to be a dictionary with the original keys and then a dictionary containing a value that indicates the count for each of the words (e.g., {'a':{'I':2, 'said':2, 'that':1} and so on with b. If the values were in a list instead of a sublist, I could get what I wanted just by using Counter: d2 = {'a': ['I','said','that', 'I'],'b': ['she','was','here']} from collections import Counter counts = {k: Counter(v) for k, v in d2.items()} However, I'm getting TypeError: unhashable type: 'list' because the lists containing the values I want to count are sublists and the list that contains them isn't hashable. I also know that if I just had sublists, I could get what I want with something like: lst = [['I', 'said', 'that'], ['said', 'I']] Counter(word for sublist in lst for word in sublist) But I just can't figure out how to combine these ideas to solve my problem (and I guess it lies in combining these two). I did try this for key, values in d.items(): flat_list = [item for sublist in values for item in sublist] new_dict = {key: flat_list} counts = {k: Counter(v) for k, v in new_dict.items()} But that only gives me the counts for the second list (because the flat_list itself only returns the value for the second key.
possible better answer: http://stackoverflow.com/a/50936094
has title: Count values with items in a dictionary with sublists
has answer: http://stackoverflow.com/a/50936094
has comment: http://stackoverflow.com/comment/88870651
tagged with: python
has answer: http://stackoverflow.com/a/50936063
tagged with: dictionary
has comment: http://stackoverflow.com/comment/88870747

http://stackoverflow.com/comment/89014016
type: QuestionComment
type: Comment
has text: please include those models in the question?
score: 1
comment on: http://stackoverflow.com/q/51010549

http://stackoverflow.com/comment/89134385
type: QuestionComment
comment on: http://stackoverflow.com/q/50954795
score: 0
type: Comment
has text: @MosheSlavin It's a Django app

http://stackoverflow.com/q/50902319
answer count: 0
type: UnansweredQuestion
has title: custom object detection model breaks because of ParseFromString and StringIntLabelMap (python v3.5 w/ tensorflow v1.8)
has comment: http://stackoverflow.com/comment/88806334
type: Question
has body: This seems to be a problem that is unique to me because I have found 0 results on the web for it. First Error: Second Error: The command that I'm trying to run from my object_detection folder is this: python train.py --logtostderr --train_dir=training/ --pipeline_config_path=training/ssd_mobilenet_v1_pets.config Here is my train.py (this should be the default since I have made no modifications to it): https://hastebin.com/gizaqutuje.py EDIT: I am starting to think this problem arises from my protobuf installation. I tried uninstalling and reinstalling different versions of protobuf using pip3, but that did not change the output at all. I don't really know if there is anymore information that I should give that is relevant to this problem, but if I am leaving something out please let me know!
tagged with: python
has comment: http://stackoverflow.com/comment/88805439
score: 0
tagged with: tensorflow

http://stackoverflow.com/comment/88908816
type: QuestionComment
comment on: http://stackoverflow.com/q/50955189
score: 0
type: Comment
has text: **steve**, a number is factor of itself, so it will be the largest factor. As I understand, here largest factor actually means second largest factor and its just less than or equal to half of number. In case of `10`, `5` is largest factor. it is just half. Now you can decrease the number of iterations of for loop. You code is ok, but it is taking time to respond. Use `print()` to see, it works.

http://stackoverflow.com/comment/88940113
type: Comment
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/50971697
has text: guess you need to import *MediaFileUpload*

http://stackoverflow.com/comment/88993346
score: 0
has text: You can't do it because after template renders, django has no access to change anything. You can use javascript instead and handle that functionality with it.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50999577

http://stackoverflow.com/q/50897254
has comment: http://stackoverflow.com/comment/88798536
type: Question
has comment: http://stackoverflow.com/comment/88799081
tagged with: python
has answer: http://stackoverflow.com/a/50899881
score: 0
answer count: 2
has body: So I have been trying to play around abit with monitor - For those who doesn't know what monitoring is - basically what it means is that you are checking something etc element, url or whatever in a certain time and check again if it has been changed. This is what I have done and... url = 'mrcnoir' while True: try: password_page = requests.get('https://{}.com'.format(url), timeout=5) password_page.raise_for_status() except requests.exceptions.RequestException as err: print('Error checking password page! - https://{}.com'.format(url) + ' - ' + str(err)) continue else: # *************---If password up---************** if ('password' in password_page.url): # Password page is up print('Password page is up! - ' + 'https://{}.com'.format(url)) if not ('password' in password_page.url): # No password page -&gt; password page # *************---Send---************** print("SENDING...1") time.sleep(random.randint(6, 12)) # *************---If password down---************** else: # Password page is down print('Password page is down! - ' + 'https://{}.com'.format(url)) if ('password' in password_page.url): # Password page -&gt; no password page # *************---Send---************** print("SENDING...2") #&lt;---- If it comes in here - it will be stuck forever and just keep posting this print... time.sleep(random.randint(6, 12)) # *************---Retry between 6-12 random.---************** finally: time.sleep(random.randint(6, 12)) The issue im having is at the bottom where it prints "SENDING...2" - What happened is that it just continues to print out the SENDING...2 all the time which means it been stuck in the loop - Basically what I want to do is that whenever it comes to the second Else part it should print it out once and then continue to "monitor" and check until there is new changes. Meaning it will be needing to wait until it appears/password in the url. How could I in that case make it happen?
has comment: http://stackoverflow.com/comment/88797881
possible better answer: http://stackoverflow.com/a/50899541
accepted answer: http://stackoverflow.com/a/50899881
has title: How can I get away from a loop?
tagged with: loops
has answer: http://stackoverflow.com/a/50899541
type: AnsweredQuestion

http://stackoverflow.com/comment/88811858
has text: Can i ask you a quick question related to this? i want to compile some LaTeX code which includes phrases like: \documentclass[a4paper]{jpconf} \usepackage{graphicx} \usepackage{titling} how do i avoid the .format method to excluded these? {jpconf}
type: Comment
score: 0
comment on: http://stackoverflow.com/a/50905852
type: AnswerComment

http://stackoverflow.com/comment/88963055
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50982315
score: 0
has text: I suggest changing the title of your question to "Get hypernym of a word..." or "Get common hypernym of two words...", depending on what your intentions are. Word types are nouns, verbs, adjectives and so on, and people might not find what they are looking for here.

numpy
tags question: http://stackoverflow.com/q/50880360
tags question: http://stackoverflow.com/q/50881875
tags question: http://stackoverflow.com/q/50984032
tags question: http://stackoverflow.com/q/50943043
tags question: http://stackoverflow.com/q/50901525
tags question: http://stackoverflow.com/q/50856752
tags question: http://stackoverflow.com/q/50879469
tags question: http://stackoverflow.com/q/50928028
tags question: http://stackoverflow.com/q/50860869
tags question: http://stackoverflow.com/q/50955782
tags question: http://stackoverflow.com/q/50859183
tags question: http://stackoverflow.com/q/50959570
tags question: http://stackoverflow.com/q/50911695
tags question: http://stackoverflow.com/q/50916422
tags question: http://stackoverflow.com/q/50896980
tags question: http://stackoverflow.com/q/50944475
tags question: http://stackoverflow.com/q/51002335
tags question: http://stackoverflow.com/q/51002815
tags question: http://stackoverflow.com/q/50907049
tags question: http://stackoverflow.com/q/50865463
tags question: http://stackoverflow.com/q/50877370
tags question: http://stackoverflow.com/q/50880399
tags question: http://stackoverflow.com/q/50955960
tags question: http://stackoverflow.com/q/50890791
tags question: http://stackoverflow.com/q/50897552
tags question: http://stackoverflow.com/q/51002465
tags question: http://stackoverflow.com/q/50975349
tags question: http://stackoverflow.com/q/50983782
tags question: http://stackoverflow.com/q/50907220
tags question: http://stackoverflow.com/q/50974924
tags question: http://stackoverflow.com/q/50978860
tags question: http://stackoverflow.com/q/50949089
tags question: http://stackoverflow.com/q/50958158
tags question: http://stackoverflow.com/q/50920346
tags question: http://stackoverflow.com/q/50961779
tags question: http://stackoverflow.com/q/50894096
tags question: http://stackoverflow.com/q/50944405
tags question: http://stackoverflow.com/q/50910334
tags question: http://stackoverflow.com/q/50904510
tags question: http://stackoverflow.com/q/50895035
tags question: http://stackoverflow.com/q/50896193
tags question: http://stackoverflow.com/q/50952453
tags question: http://stackoverflow.com/q/50916845
tags question: http://stackoverflow.com/q/50875234
tags question: http://stackoverflow.com/q/50988766
tags question: http://stackoverflow.com/q/50931068
tags question: http://stackoverflow.com/q/51006714
tags question: http://stackoverflow.com/q/50975833
tags question: http://stackoverflow.com/q/50921241
tags question: http://stackoverflow.com/q/50918497
tags question: http://stackoverflow.com/q/50971213
tags question: http://stackoverflow.com/q/50975156
tags question: http://stackoverflow.com/q/50878858
tags question: http://stackoverflow.com/q/50969804
tags question: http://stackoverflow.com/q/50980067
tags question: http://stackoverflow.com/q/50951700
tags question: http://stackoverflow.com/q/51003207
tags question: http://stackoverflow.com/q/50929439
tags question: http://stackoverflow.com/q/50902633
tags question: http://stackoverflow.com/q/50991679
tags question: http://stackoverflow.com/q/50875021
tags question: http://stackoverflow.com/q/50981193
tags question: http://stackoverflow.com/q/50919666
tags question: http://stackoverflow.com/q/50976373
tags question: http://stackoverflow.com/q/50914335
tags question: http://stackoverflow.com/q/50963189
tags question: http://stackoverflow.com/q/50980810
tags question: http://stackoverflow.com/q/50957704
tags question: http://stackoverflow.com/q/50913499
tags question: http://stackoverflow.com/q/50950676
tags question: http://stackoverflow.com/q/50876425
tags question: http://stackoverflow.com/q/51010662
tags question: http://stackoverflow.com/q/51000584
tags question: http://stackoverflow.com/q/50984042
tags question: http://stackoverflow.com/q/50947816
tags question: http://stackoverflow.com/q/50969167
tags question: http://stackoverflow.com/q/50941693
tags question: http://stackoverflow.com/q/50925382
tags question: http://stackoverflow.com/q/50972987
tags question: http://stackoverflow.com/q/50949692

http://stackoverflow.com/q/50986355
type: Question
score: -1
upvote count: 0
has comment: http://stackoverflow.com/comment/88967384
has comment: http://stackoverflow.com/comment/88967383
answer count: 1
favorite count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/50986356
has body: For some reason a string is double printed. How could it be like that?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50986356
downvote count: 1
has title: Python double printed string

http://stackoverflow.com/a/50907831
upvote count: 2
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/50907531
score: 2
has comment: http://stackoverflow.com/comment/88815605
answers question: http://stackoverflow.com/q/50907531
downvote count: 0
has body: One solutions: writer = csv.writer("testfile.csv", dialect = 'excel') for k, v in getNProducts.iteritems(): writer.writerow(list((k,)) + list(v))

http://stackoverflow.com/q/50970060
type: Question
has comment: http://stackoverflow.com/comment/88936498
has comment: http://stackoverflow.com/comment/88936545
has title: How can I reach nested attributes inside an object
has comment: http://stackoverflow.com/comment/88936933
score: 2
downvote count: 0
has body: I am using tensorflow object detector code but this is not exclusively a tensorflow question. I have made a function to save the most useful parameters to a text file. I am using the code: configs = config_util.get_configs_from_pipeline_file(FLAGS.pipeline_config_path) to get the actual config object. config itself is dict but the values it contains are all tensorflow specific objects. model_config = configs['model'] type(model_config) object_detection.protos.model_pb2.DetectionModel train_config = configs['train_config'] type(train_config) object_detection.protos.train_pb2.TrainConfig Each of these object contains other tensorflow class objects which I can access through getattr function like: type(getattr(train_config.optimizer, 'rms_prop_optimizer')) object_detection.protos.optimizer_pb2.RMSPropOptimizer Since I can see the various parameters in the actual text config file I can use a chain of these getattr to get to the actual value I am interested in. The problem is that it gets really long (and ugly I would say) and it does not feel the right way to do it. For example to get the actual learning rate from this sample config file I would have to use: getattr(getattr(getattr(getattr(train_config.optimizer, 'momentum_optimizer'), 'learning_rate'), 'manual_step_learning_rate'), 'initial_learning_rate') 0.0003000000142492354 ok there are some rounding errors here but that's not the point here. I would like to mention that using the higher level item in object does not seem to work for these objects. I was wondering if there was any way to get that value is a prettier way? A way less error prone and anyway applicable even without the knowing the actual text configuration file. Strictly speaking this is not a tensorflow question since the getattr approach could be applied to any object having attributes but if a tensorflow solution exist I am open to it.
favorite count: 0
answer count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
tagged with: tensorflow

dictionary
tags question: http://stackoverflow.com/q/50868109
tags question: http://stackoverflow.com/q/50907531
tags question: http://stackoverflow.com/q/50878091
tags question: http://stackoverflow.com/q/50884274
tags question: http://stackoverflow.com/q/50969419
tags question: http://stackoverflow.com/q/50939068
tags question: http://stackoverflow.com/q/50929265
tags question: http://stackoverflow.com/q/50982326
tags question: http://stackoverflow.com/q/50937106
tags question: http://stackoverflow.com/q/50943979
tags question: http://stackoverflow.com/q/50980245
tags question: http://stackoverflow.com/q/50861252
tags question: http://stackoverflow.com/q/50929768
tags question: http://stackoverflow.com/q/50989404
tags question: http://stackoverflow.com/q/50888651
tags question: http://stackoverflow.com/q/50924141
tags question: http://stackoverflow.com/q/50960914
tags question: http://stackoverflow.com/q/50937231
tags question: http://stackoverflow.com/q/50950563
tags question: http://stackoverflow.com/q/51003884
tags question: http://stackoverflow.com/q/50918419
tags question: http://stackoverflow.com/q/50901296
tags question: http://stackoverflow.com/q/50872498
tags question: http://stackoverflow.com/q/50874707
tags question: http://stackoverflow.com/q/50870912
tags question: http://stackoverflow.com/q/51002210
tags question: http://stackoverflow.com/q/50950220
tags question: http://stackoverflow.com/q/50970824
tags question: http://stackoverflow.com/q/50935910
tags question: http://stackoverflow.com/q/50877322
tags question: http://stackoverflow.com/q/50882225
tags question: http://stackoverflow.com/q/50995690
tags question: http://stackoverflow.com/q/50933158
tags question: http://stackoverflow.com/q/50955568
tags question: http://stackoverflow.com/q/50913322
tags question: http://stackoverflow.com/q/50901166
tags question: http://stackoverflow.com/q/50956459
tags question: http://stackoverflow.com/q/50871095
tags question: http://stackoverflow.com/q/50971429
tag name: dictionary
tags question: http://stackoverflow.com/q/50886718
tags question: http://stackoverflow.com/q/50954147
tags question: http://stackoverflow.com/q/50967543
tags question: http://stackoverflow.com/q/50988299
tags question: http://stackoverflow.com/q/50864169
tags question: http://stackoverflow.com/q/50885545
tags question: http://stackoverflow.com/q/50994746
tags question: http://stackoverflow.com/q/50945618
tags question: http://stackoverflow.com/q/50865770
tags question: http://stackoverflow.com/q/50938883
tags question: http://stackoverflow.com/q/50992241
tags question: http://stackoverflow.com/q/50914127
tags question: http://stackoverflow.com/q/50949476
tags question: http://stackoverflow.com/q/50960123
tags question: http://stackoverflow.com/q/50920234
tags question: http://stackoverflow.com/q/50862660
tags question: http://stackoverflow.com/q/50970946
tags question: http://stackoverflow.com/q/50984524
tags question: http://stackoverflow.com/q/50914381
tags question: http://stackoverflow.com/q/50868589
tags question: http://stackoverflow.com/q/50878915
tags question: http://stackoverflow.com/q/50966390
tags question: http://stackoverflow.com/q/50899952
tags question: http://stackoverflow.com/q/50901787
tags question: http://stackoverflow.com/q/50925340
tags question: http://stackoverflow.com/q/50965308
tags question: http://stackoverflow.com/q/50967065
tags question: http://stackoverflow.com/q/51004860
tags question: http://stackoverflow.com/q/50865164
tags question: http://stackoverflow.com/q/50964064
tags question: http://stackoverflow.com/q/50966466
tags question: http://stackoverflow.com/q/50883192
tags question: http://stackoverflow.com/q/50932755
tags question: http://stackoverflow.com/q/50925488
tags question: http://stackoverflow.com/q/51001914
tags question: http://stackoverflow.com/q/51010593
tags question: http://stackoverflow.com/q/51000097
tags question: http://stackoverflow.com/q/51004506
tags question: http://stackoverflow.com/q/50869367
tags question: http://stackoverflow.com/q/50856138

http://stackoverflow.com/q/50986420
favorite count: 0
accepted answer: http://stackoverflow.com/a/50986541
has title: Cannot override exisitng dataframe values while replacing values in columns (strings)
upvote count: 1
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50986541
score: 1
type: Question
tagged with: dataframe
has body: I have a dataframe in pandas with customers IDs and their gender. However, while cleaning the dataset I noticed that some IDs have two genders assigned, in most cases it is Female or Male and Unknown. The df looks like this: index ID gender 0 23 M 1 23 U 2 55 F 3 55 U My aim is to locate IDs that have two genders assigned and replace the U gender with the non-U gender. To do this, I am using a for loop over a list, in which I have all customer IDs that have inconsistent genders. For example, for ID = 23 the code inside the loop would look like this: if all((customers.loc[customers['ID'] == 23]['gender'].str.contains('M')) | (customers.loc[customers['ID'] == 23]['gender'].str.contains('U'))): customers.loc[customers['ID'] == 23]['gender'] = customers.loc[customers['ID'] == 23]['gender'].replace('U', 'M') My problems: Not sure if the for loop and if statements are optimal to perform my task While using my method I am not able to override the existing dataframe. I tried using replace(inplace = True), I tried assigning the new genders as above using .loc(), but also with chained indexing. In all cases I am receiving a warning (while using .loc or chained indexing): A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: http://pandas.pydata.org/pandas- docs/stable/indexing.html#indexing-view-versus-copy (while using replace(inplace = True) C:\Users\***: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame and the original dataframe is intact. I looked at the StackOverflow extensively, but I still cannot solve my problem.
tagged with: pandas
answer count: 1
downvote count: 0
tagged with: string

http://stackoverflow.com/a/50875034
has comment: http://stackoverflow.com/comment/88752335
downvote count: 0
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50874618
has comment: http://stackoverflow.com/comment/88752133
has body: If you want to reproduce a more Gaussian-like distribution you're talking about weigthing of single points (class score in a row). So I would suggest to use Guassian distributed weights to amplify the score. Here an example: import numpy as np import pandas as pd #Preparation of the data nclasses = 10 nsamples = 5 df_c = [] for nc in range( nsamples ): a = np.random.rand(nclasses) a = [n/np.sum(a) for n in a] df_c.append( a ) df = pd.DataFrame(df_c) # Now let's weight for nr in range( df[0].count() ): #iterate over rows a = df.iloc[nr] #capture the nth row #generate Gaussian weights gw = np.random.normal( np.mean(a), np.std(a), len(a) ) #sort gw and a in order to assign one to the other gw = np.sort(gw) b_ind = np.argsort(a) #indexes to sort a b = a[b_ind] #sorted version of a # now weight the row aw_r = a*b # you can reduce the entity adding anotherfactor, like 0.8 for instance # back from sort aw = [ aw_r[n] for n in b_ind ] #update the dataframe df.iloc[nr] = aw # there you go! Hope it will be helpful Update__ If you want to adjust the mean of every row to a same value, for instance 0.5, you just have to subtract the difference between the row mean and the target mean (0.5 in this case). a=np.array([1,2,3,47,2,6]) print( a.mean() ) # 10.1666 target_mean = 0.5 a_adj = a-(np.mean(a) - target_mean) print( np.mean( a_adj ) ) # 0.5 It means that in the main example above, before substituting aw in df.iloc[nr] you should do aw = aw-(np.mean(aw) - 0.5)
answers question: http://stackoverflow.com/q/50874618
type: Answer
has comment: http://stackoverflow.com/comment/88751958
score: 1

http://stackoverflow.com/a/50931254
downvote count: 0
has comment: http://stackoverflow.com/comment/88861451
answers question: http://stackoverflow.com/q/50931098
type: Answer
has body: The format function seems perfect for this. Try it like this: tprice = 0 tup = [['apple', '100', '2'], ['blackberry', '100', '23']] myformat = "{:&lt;10}{:&lt;25}{:&lt;5}{}" f = open(filename, 'w') g = open('recpt.txt', 'r') lines = g.readlines() for line in lines: base = line.split() tup.append(base) print(myformat.format('S.no', 'Product', 'Unit', 'Price')) for i in range(len(tup)): if len(tup[i][0]) &lt;= 7: print(myformat.format(str([i + 1]), tup[i][0], tup[i][2], tup[i][1])) else: print(myformat.format(str([i + 1]), tup[i][0], tup[i][2], tup[i][1])) price = int(tup[i][1]) tprice += price print(tprice) Output: S.no Product Unit Price [1] apple 2 100 [2] blackberry 23 100
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/88861651
accepted answer of: http://stackoverflow.com/q/50931098
type: AcceptedAnswer

http://stackoverflow.com/comment/88911800
comment on: http://stackoverflow.com/q/50956542
score: 1
has text: @user2357112 if you and hpaulj can't give a definitive answer on this then I assume this question will remain in limbo. In any case, you've both given me assurance that I'm not going mad that this result is not intuitive, thanks.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50974645
possible better answer: http://stackoverflow.com/a/50974730
has body: I have one solution for particular problem as [[0.34 0.26 0.76 ] [0.79 0.82 0.37 ] [0.93 0.87 0.94]] I have another solution for same problem as [[0.21 0.73 0.69 ] [0.35 0.24 0.53] [0.01 0.42 0.50]] Now I have to merge their ith position together so the resultant array would be like [[0.34 0.21] [0.26 0.73] [0.76 0.69] [0.79 0.35] .......... ..........
has answer: http://stackoverflow.com/a/50974796
has answer: http://stackoverflow.com/a/50974730
type: Question
tagged with: numpy
tagged with: numpy-ndarray
has answer: http://stackoverflow.com/a/50974698
has title: How to merge ith values of two different array in one array python
score: 4
has answer: http://stackoverflow.com/a/50974891
upvote count: 4
has answer: http://stackoverflow.com/a/50977172
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/50974698
tagged with: multidimensional-array
answer count: 5
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/88993245
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50999628
has text: We don't _need_ to ensure that prices must occur twice. The question says prices *can* appear twice. Prices are allowed to appear twice. Not a necessary condition.
type: AnswerComment

http://stackoverflow.com/comment/88714352
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50855749
score: 0
has text: Can someone please elaborate a bit? Checking the "original" answers only confused me.

http://stackoverflow.com/q/50968217
answer count: 1
tagged with: matplotlib
type: UnansweredQuestion
has body: I have code below which is not grouping my matplot lib chart properly. fig = plt.figure() # Create matplotlib figure ax = fig.add_subplot(111) # Create matplotlib axes ind = np.arange(5) width = 0.20 avg_bar1 = (10,20,30,60,14) avg_bar2 = (10,50,30,60,35) avg_bar3 = (10,90,30,60,12) avg_bar4 = (10,70,30,60,23) avg_bar5 = (10,50,30,40,80) rects1 = plt.bar(ind, avg_bar1, label='bar1') rects2 = plt.bar(ind+width, avg_bar2, label='bar2') rects3 = plt.bar(ind+width, avg_bar3, label='bar3') rects4 = plt.bar(ind+width, avg_bar4, label='bar4') rects5 = plt.bar(ind+width, avg_bar5, label='bar5') plt.xticks(ind+0.20, ('Q1 2017', 'Q2 2017', 'Q3 2017', 'Q4 2017', 'Q5 2017')) img_path = str(str(user)+str(req_id)+str(slide_id)+'.png') plt.savefig(img_path, bbox_inches="tight", pad_inches=0) return img_path I don't know why this bar charts are grouping by quarters given in xticks.
type: Question
has answer: http://stackoverflow.com/a/50968377
tagged with: python
has title: Matplot lib : bar charts are not grouping properly
score: 0

http://stackoverflow.com/q/50974293
tagged with: http://stackoverflow.com/tag/csv
answer count: 1
has answer: http://stackoverflow.com/a/50976366
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has body: I'm having trouble implementing a function. First here's the snippet: # LOAD ROWS for row in eans: gtin_row = row[0] if(gtin_row[0].isdigit()): print('True') gtin = row[0].split(";") gtin = gtin[0] # DIGIT IS FOUND IN row[0] so START at the next row next(eans,None) # IF ITEM IS FOUND on Found_list if gtin in found_list: # STARTING FROM row[0] I mentioned earlier until it finds another row that starts with a digit, delete every row if(row[0].isdigit): break else: print('Non Digit = Iterate') output = open(csv_file, 'wb') writer = csv.writer(output) writer.writerow(row) output.close() next(eans,None) continue I was loading a list, from a csv I've commented on how the code was supposed to work, somehow next() wasn't working. I'm having trouble starting on next(eans,None) because it doesn't point row eans to the next row. Let's say I have rows like this: 3423423 jalsjfslv fbdbdf bdfndf 32532532 I intended to start at jalsjfslv delete it and its following rows until it points to 32532532 where if(row[0].isdigit): is supposed to work and stops the loop so it can go with the next gtin My code doesn't work with .next and next(list, None) any idea on how to solve this problem? Really stuck I think i'm missing something. Thank you!
has title: How Do I Command CSV to Delete thr Rows On Starting from This Row and To That Row
type: Question
score: 0

http://stackoverflow.com/a/66739012
downvote count: 0
has body: I don't know whether you already resolved this problem or not, but, from what I have seen so far from your code and (also borrowing from Evgeny's code) your requirements, the only reason you have the different levels of horizontal bars because you have defined the scalar y of the barh of matplotlib (matplotlib.pyplot.barh(y, width, height=0.8, left=None, *, align='center', **kwargs) as a range. So, each successive stacked bar is being listed on a separate level. So, I took the liberty of downloading your dataset and playing around with the code a little bit. I created a dataframe from the google dataset and assigned each of the Dynasty (Dynasty_col column) and Age (Age_col column) with a matplotlib CSS color (this is not necessary, but, I find this easier to manage for visualisation): Then for the purpose of replicating your Xia Dynasty representation, I just created a subset: Following that I kept mostly to what your/Evgeny's code already shows with a few minor changes: event = data_set_xia['EnglishName'] begin = data_set_xia['Start'] end = data_set_xia['Finish'] length = data_set_xia['Length'] Here I added a level for naming with a vertical line (you can lengthen or shorten the array [-2, 2, -1, 1] to get different levels of labelling): levels = np.tile([-2, 2, -1, 1], int(np.ceil(len(begin)/4)))[:len(begin)] import matplotlib.pyplot as plt plt.style.use('ggplot') plt.figure(figsize=(12,6)) Here I basically add all of the dynasties on the same y scalar (listed as 0), the rest of the line has been modified to correspond to the color of the bars and give an edgecolour. plt.barh(0, (end-begin), color=data_set_xia.loc[:,"Dynasty_col"], height =0.3 ,left=begin, edgecolor = "black") plt.tick_params(axis='both', which='major', labelsize=15) plt.tick_params(axis='both', which='minor', labelsize=20) plt.title('Xia Dynasty', fontsize = '25') plt.xlabel('Year', fontsize = '20') # plt.yticks(range(len(begin)), "") ax = plt.gca() ax.axes.yaxis.set_visible(False) plt.xlim(-2250…
type: Answer
answers question: http://stackoverflow.com/q/50883054
score: 17
upvote count: 17

http://stackoverflow.com/comment/88830742
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50914146
type: QuestionComment
has text: So you didn't actually do the thing you said. You are worried about what happens when you import your module multiple times, but you only import it once.

http://stackoverflow.com/comment/88941299
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50972135
has text: Is `C:Path` supposed to be `C:/Path`?
score: 0

http://stackoverflow.com/q/51000166
tagged with: matplotlib
has title: Pandas: unable to save multiple plots using for loop
has answer: http://stackoverflow.com/a/51001691
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51001634
score: 0
has body: I am trying to save multiple plots created by pandas.dataframe.plot in gif format. I am using a for loop to iterate over the plots. The problem is that the plots that are saved after executing after executing the loop are not correct. Here is the code for i in range(len(plot_cols)): grouped = cust_data[plot_cols[i]].groupby(cust_data['Cluster_ID']) mean_trans = grouped.mean() plot = mean_trans.plot(kind = 'bar', figsize = [10, 7]) plot.set_ylabel(plot_cols[i]) fig = plot.get_figure() fig.savefig("C:\\Users\\utkarsh.a.ranjan\\Documents\\pyqt_data\\view_bar_graphs\\cluster_" + str(i)) When I remove the for loop and substitute individual values of i, I get the correct plots. my desired plots are these the plots I am getting instead are these
tagged with: pandas
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/34990179
tagged with: python
has comment: http://stackoverflow.com/comment/88996878
has comment: http://stackoverflow.com/comment/88996899
duplicate of: http://stackoverflow.com/q/34990179

http://stackoverflow.com/comment/88766927
score: 1
comment on: http://stackoverflow.com/q/50882225
has text: "But switch/case statements in Python are geared towards specific cases " *Python does not have switch/case statements*. They aren't geared towards *any* cases. Just use the if-elif-else statements
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/106073125
has text: In case it's too subtle, this answer clarifies that the question was asked about `sklearn.metrics.confusion_matrix()`, not `tensorflow.math.confusion_matrix()`, which might be expected given the tag `keras`
comment on: http://stackoverflow.com/a/50921588
type: AnswerComment
score: 35
type: Comment

http://stackoverflow.com/comment/88720962
type: AnswerComment
type: Comment
has text: @AntoineLB: that's explained in the [*How coverage works* section](https://coverage.readthedocs.io/en/latest/howitworks.html) of the project documentation.
comment on: http://stackoverflow.com/a/50858728
score: 0

http://stackoverflow.com/comment/88826367
comment on: http://stackoverflow.com/a/50913008
score: 0
type: AnswerComment
type: Comment
has text: While that works, the assignment doesn't want us to use any Python functions. So sorted() isn't an option. That's why I was hesitating with the statistics functions as well.

http://stackoverflow.com/a/50994132
accepted answer of: http://stackoverflow.com/q/50954795
answers question: http://stackoverflow.com/q/50954795
has body: It's report that the element not found error after you supplying the login , so I think the login failed and the page redirected to somewhere. You can use screenshot option to take a screenshot of the page and then see which page the driver load. driver.save_screenshot("path to save screen.jpeg") Also you can save the raw html code and inspect the same page. Webdriver Screenshot Using Selenium in Python to save a webpage on Firefox
score: 4
upvote count: 4
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/q/50993497
upvote count: 3
has answer: http://stackoverflow.com/a/54117358
tagged with: python
has answer: http://stackoverflow.com/a/56468772
downvote count: 0
has title: Can't access activate, deactivate, or conda inside a conda environment
type: UnansweredQuestion
score: 3
tagged with: anaconda
tagged with: conda
type: Question
answer count: 2
has body: So if I load a conda environment and want to use conda to install a package (or whatever else), I have to specify conda.exe. What I expect to work: (randomenv) λ conda --version The system cannot find the path specified. What actually works: (randomenv) λ conda.exe --version conda 4.5.4 Further complicating things, the following: (randomenv) λ where conda C:\Users\[USERNAME]\AppData\Local\conda\conda\envs\randomenv\Scripts\conda C:\Users\[USERNAME]\AppData\Local\conda\conda\envs\randomenv\Scripts\conda.bat C:\ProgramData\Anaconda3\Scripts\conda.exe Is the first entry supposed to be C:\Users\[USERNAME]\AppData\Local\conda\conda\envs\randomenv\Scripts\conda.exe and the environment got setup wrong or something? Edit: We're now in to usage breaking issues. I can't use deactivate, because deactivate doesn't have a .exe extension. Per usual, where deactivate turns up: C:\Users\[USERNAME]\AppData\Local\conda\conda\envs\randomenv\Scripts\deactivate C:\Users\[USERNAME]\AppData\Local\conda\conda\envs\randomenv\Scripts\deactivate.bat C:\ProgramData\Anaconda3\Scripts\deactivate C:\ProgramData\Anaconda3\Scripts\deactivate.bat Even more hilariously frustrating: (randomenv) λ C:\Users\[USERNAME]\AppData\Local\conda\conda\endevs\randomenv\Scripts\deactivate The system cannot find the path specified. and then it gets even better: (randomenv) λ cd C:\Users\[USERNAME]\AppData\Local\conda\conda\envs\randomenv\Scripts\ C:\Users\[USERNAME]\AppData\Local\conda\conda\envs\randomenv\Scripts (randomenv) λ ls 2to3.exe* conda* easy_install.exe* epylint-script.py iptest3.exe* ipython-script.py pip-script.py pygmentize-script.py pyreverse.bat symilar.exe* 2to3-script.py conda.bat easy_install-script.py idle.exe* ipython.exe* isort.exe* pydoc.exe* pylint.bat pyreverse.exe* symilar-script.py activate* deactivate* epylint.bat idle-script.py ipython3.exe* isort-script.py pydoc-script.py pylint.exe* pyreverse-script.py wheel.exe* activate.bat deactivate.bat epylint.exe* iptest.exe* ipython3-script.py…
favorite count: 0

http://stackoverflow.com/comment/89020941
comment on: http://stackoverflow.com/q/50995861
has text: I'm looking to calculate the np.var at each respective shell. I would set it up to calculate the variance where the radius of the circle = 1, then the variance of the next circle with radius = 2 and so on and so forth. In this way, I would calculate the np.var over multiple different axes. (each axes represented by newly the generated circle shell)
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/q/50955335
answer count: 2
upvote count: 1
possible better answer: http://stackoverflow.com/a/50955505
downvote count: 0
has comment: http://stackoverflow.com/comment/88908963
has comment: http://stackoverflow.com/comment/88908772
favorite count: 0
has comment: http://stackoverflow.com/comment/88909039
has answer: http://stackoverflow.com/a/50955505
tagged with: python
has title: Python __ror__ without initializing class
accepted answer: http://stackoverflow.com/a/50956016
score: 1
has body: I am using the ipython shell a lot, and decided to make some tidies wrapper function more easy to type. Goal is to be able to type AnObject | dump, instead of dump(AnObject). This is only inside an ipython shell, and in dev. To make it easier to type. I have come up with this so far: class _dump: def __ror__(_, obj): print(obj) dump = _dump() d = {'test': 123} d | dump which outputs {'test': 123} A tiny thing annoys me.. Is there any way to do this without initializing the class after the definition? And as a bonus, is it possible to accept both the | dump style, as well as, as a function (| dump(opt=True))
has answer: http://stackoverflow.com/a/50956016
type: Question
has comment: http://stackoverflow.com/comment/88908723
type: AnsweredQuestion

http://stackoverflow.com/q/50995861
score: 1
has title: Iterating radially through a numpy array and caculating the variance by radial shells in Python
type: Question
tagged with: numpy
has body: I'm looking to calculate the numpy.var(array), however, I want a set of variance values instead of the variance of the entire array. The idea is to generate a bunch of evenly spaced circular shells from my numpy array and find the variance of each shell. #For instance- a simple example: import numpy as np arr = np.arange(9).reshape(3,3) ### Insert some method to find all of the values at each respective radius RESULT arr_radius_0 = [4] arr_radius_1 = [0,1,2,5,8,7,6,3] var_r0 = np.var(arr_radius_0) var_r1 = np.var(arr_radius_1) After getting all the variances for each respective shell, I want to append them all to a new array. The goal is to be able to calculate the radial variance for large data sets. I've been sweating over this for quite some time! Any help at all is super appreciated!
has comment: http://stackoverflow.com/comment/88986313
upvote count: 1
favorite count: 0
answer count: 0
has comment: http://stackoverflow.com/comment/89020941
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89001124
downvote count: 0

http://stackoverflow.com/q/51005760
has answer: http://stackoverflow.com/a/51005766
tagged with: series
possible better answer: http://stackoverflow.com/a/51005764
has answer: http://stackoverflow.com/a/51005764
has body: I have the below pandas column. I need to convert cells containing the word 'anaphylaxis' to 1 and the cells not containing the word to 0. Till now I have tried but there is something missing df['Name']= df['Name'].replace(r"^(.(?=anaphylaxis))*?$", 1,regex=True) df['Name']= df['Name'].replace(r"^(.(?&lt;!anaphylaxis))*?$", 0, regex=True) ID Name 84 Drug-induced anaphylaxis 1041 Acute anaphylaxis 1194 Anaphylactic reaction 1483 Anaphylactic reaction, due to adverse effect o... 2226 Anaphylaxis, initial encounter 2428 Anaphylaxis 2831 Anaphylactic shock 4900 Other anaphylactic reaction
tagged with: python
tagged with: regex
has title: Convert regex values in pandas to 0 or 1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51005766
upvote count: 1
type: Question
answer count: 2
tagged with: pandas
downvote count: 0
score: 1
favorite count: 0

http://stackoverflow.com/q/50857551
favorite count: 0
has comment: http://stackoverflow.com/comment/88717982
has answer: http://stackoverflow.com/a/50868573
accepted answer: http://stackoverflow.com/a/50868573
has comment: http://stackoverflow.com/comment/88718090
tagged with: python
has body: How can I filter the physicalserver if its id is in the given param? class PhysicalServerListAPIView(ListAPIView): serializer_class = PhysicalServerListSerializer permission_classes = [IsSuperAdminOrObjEqualsSelf] pagination_class = CommonPagination def get_queryset(self): query_params = self.request.query_params qs = PhysicalServer.objects.filter(user=self.request.user) id_list = get_param_from_query_params(query_params, 'id_list') if id_list: qs = qs.filter(Q(id__in=id_list)) # I want to filter if the physicalserver id is in the `id_list` return qs the code of the method: def get_param_from_query_params(query_params, param): """ :param query_params: :param param: :return: """ param_temp = None try: mutable = query_params._mutable query_params._mutable = True param_list = query_params.pop(param) param_temp = param_list[0] if (isinstance(param_list, list) and len(param_list) &gt; 0) else '' query_params._mutable = mutable except Exception as e: pass return param_temp How can I filter the physicalserver if its id is in the given param? EDIT-1 My id_list in the url form is: id_list[]=24&amp;id_list[]=25&amp;id_list[]=27
has comment: http://stackoverflow.com/comment/88717842
has title: How can I filter the physicalserver if its id is in the given param?
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/88717793
tagged with: django
type: Question
has comment: http://stackoverflow.com/comment/88717567
has comment: http://stackoverflow.com/comment/88717909
score: 1
has comment: http://stackoverflow.com/comment/88717720
upvote count: 1
answer count: 1

paramiko
tags question: http://stackoverflow.com/q/50877171
tag name: paramiko
tags question: http://stackoverflow.com/q/50952508
tags question: http://stackoverflow.com/q/50861080
tags question: http://stackoverflow.com/q/50962485
tags question: http://stackoverflow.com/q/50927844
type: Tag
tags question: http://stackoverflow.com/q/50989698
tags question: http://stackoverflow.com/q/50888082
tags question: http://stackoverflow.com/q/50977380

http://stackoverflow.com/q/50982269
tagged with: lightgbm
has answer: http://stackoverflow.com/a/50984328
has comment: http://stackoverflow.com/comment/88959879
tagged with: python
favorite count: 0
upvote count: 8
accepted answer: http://stackoverflow.com/a/50984328
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/10062954
has body: I was running lightgbm with categorical features: X_train, X_test, y_train, y_test = train_test_split(train_X, train_y, test_size=0.3) train_data = lgb.Dataset(X_train, label=y_train, feature_name=X_train.columns, categorical_feature=cat_features) test_data = lgb.Dataset(X_test, label=y_train, reference=train_data) param = {'num_trees': 4000, 'objective':'binary', 'metric': 'auc'} bst = lgb.train(param, train_data, valid_sets=[test_data], early_stopping_rounds=100) Turns out the Error: if self.handle is not None and feature_name is not None and feature_name != 'auto': ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() I checked the other similar errors on stackoverflow mostly related to numpy, and I then checked documentation and tried to replace my categorical_feature with index like [0, 2, 5, ...](my original was column names of categorical features), still the same error. I also tried replacing label with the column index, still error. Anyone could help? Thanks in advance.
has answer: http://stackoverflow.com/a/51015475
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/113012556
score: 8
downvote count: 0
possible better answer: http://stackoverflow.com/a/51015475
has title: LightGBM: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

http://stackoverflow.com/comment/88977223
has text: Yes, I would prefer to not have to go through that extra step. And while reducing the number of columns certainly increases speed, it still runs quite slowly. For the very simple example I posted, which has only two columns, the loop still takes over 10 minutes for 10,000 rows. There must be some major inefficiency with my process but I don't know what it is.
comment on: http://stackoverflow.com/q/50988340
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88752044
type: Comment
has text: Thanks for your reply. I tried to do so, but the only output I get out of it is: dual : Direction=Suffix.IMPORT, Datatype=Suffix.FLOAT Key : Value Backend Qt5Agg is interactive backend. Turning interactive mode on. So nothing that would help me I think. Also I have already gotten an output by using model.dual.get([cobject[index]), but somehow all the variables are containing a value of none. Which is just very strange since I can see in the results that some are inequality contraints are active.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50866363

http://stackoverflow.com/q/50867657
has answer: http://stackoverflow.com/a/50867673
favorite count: 0
type: Question
upvote count: 2
tagged with: python-multithreading
tagged with: multithreading
tagged with: python
answer count: 1
linked to: http://stackoverflow.com/q/34361035
has body: I am creating multiple threads in my python program with thread name. Is there any way I can identify a specific task from /proc//task/*. I can see /proc/17094/task/17095/comm but that prints my program name only not the thread name class myThread (threading.Thread): def __init__(self, threadID, name, counter): threading.Thread.__init__(self, name=name) self.threadID = threadID self.name = name self.counter = counter def run(self): print "Starting " + self.name # Get lock to synchronize threads print_time(self.name, self.counter, 9) # Free lock to release next thread def print_time(threadName, delay, counter): while counter: time.sleep(delay+9) print "%s: %s" % (threadName, time.ctime(time.time())) threadLock.acquire() counter -= 1 threadLock.release() threadLock = threading.Lock() threads = [] # Create new threads thread1 = myThread(1, "Thread-1", 1) thread2 = myThread(2, "Thread-2", 2) # Start new Threads thread1.start() thread2.start() # Add threads to thread list threads.append(thread1) threads.append(thread2) print "Started both threads" # Wait for all threads to complete for t in threads: t.join() print "Exiting Main Thread" Here I want to see the thread based on name - Thread-1 - I can see the tasks under /proc/ ~ # ps -ef | grep thread1 root 17787 4859 0 00:24 pts/0 00:00:00 /bin/python ./thread1.py root 17800 4938 0 00:24 pts/1 00:00:00 grep thread1 ~ # ls -l /proc/17787/task/ total 0 dr-xr-xr-x 7 root root 0 Jun 15 00:24 17787 dr-xr-xr-x 7 root root 0 Jun 15 00:24 17788 dr-xr-xr-x 7 root root 0 Jun 15 00:24 17789 But there I couldn't see Thread-1 in any files under these directories.
has title: How to identify thread from /proc using thread name?
downvote count: 0
type: UnansweredQuestion
score: 2
tagged with: python-2.x

http://stackoverflow.com/q/50944808
tagged with: python
has title: Pass messages between pool processes in Python multiprocessing
score: 2
has body: I am new to python multiprocessing. I am writing a redis pubsub module in which a publisher reads data from a database table and publishes the data on a channel. At subscribers side I intend to create a number of worker processes which can listen to the channel by subscribing to it, get the item from channel and perform some operation on it. I want to stop all pool processes when any process gets a END string from channel. For this I am using multiprocessing.Manager().Queue() to communicate among pool processes. My subscriber module is below: import redis import time import traceback import json import multiprocessing as mp import contextlib NO_OF_PROCESS = 4 def newProcess(queue): r = redis.StrictRedis() p = r.pubsub() p.subscribe('subChannel') while True: print ('Waiting...') if (queue.get() == 'END'): break # Do some work from message message = p.get_message() print (message) if message: data = message['data'] # If 'END' received than stop all pool processes by setting a message in shared queue if data == b'END': queue.put('END') break else: data = json.loads(data) print (data) time.sleep(1) class Worker: def __init__(self, NO_OF_PROCESS): self.NO_OF_PROCESS = NO_OF_PROCESS self.queue = mp.Manager().Queue() self.pool = mp.Pool(processes = NO_OF_PROCESS) def doWork(self): [self.pool.apply(newProcess, args=(self.queue)) for i in range(self.NO_OF_PROCESS)] def parallelExec(): worker = Worker(NO_OF_PROCESS) worker.doWork() parallelExec() The problem here is I am getting following error when I try to execute: TypeError: newProcess() argument after * must be an iterable, not AutoProxy[Queue]. Please help, also if there is any other approach than I would like to hear.
tagged with: python-multiprocessing
tagged with: multiprocessing
type: Question
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/50944966
favorite count: 0
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/comment/88922646
score: 0
type: Comment
type: QuestionComment
has text: Didn't rename the file, made a copy of plpython3.dll and named it plpython33.dll. Can you guide me please how to check matching pyhton version.? I went through the release notes of PG 9.4.1 but couldn't find anything related https://www.postgresql.org/docs/9.4/static/release-9-4-1.html
comment on: http://stackoverflow.com/q/50962412

http://stackoverflow.com/comment/88847001
comment on: http://stackoverflow.com/a/50923817
score: 0
type: AnswerComment
has text: @AzatIbrakov: Tell that to the OP.
type: Comment

http://stackoverflow.com/comment/88774895
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50886332
type: AnswerComment
has text: oh ok...I did not use `enumerate` because i thought that was....unnecessary for this task. Guess i was wrong. Thanks anyway :). I learn a lot coding in stackoverflow :).

http://stackoverflow.com/q/50944106
tagged with: python-3.x
tagged with: python-tesseract
possible better answer: http://stackoverflow.com/a/50950424
tagged with: web-scraping
has body: I've written a script in python in combination with pytesseract to extract a word out of an image. There is only a single word TOOLS available in that image and that is what I'm after. Currently my below script is giving me wrong output which is WIS. What Can I do to get the text? Link to that image This is my script: import requests, io, pytesseract from PIL import Image response = requests.get('http://facweb.cs.depaul.edu/sgrais/images/Type/Tools.jpg') img = Image.open(io.BytesIO(response.content)) img = img.resize([100,100], Image.ANTIALIAS) img = img.convert('L') img = img.point(lambda x: 0 if x &lt; 170 else 255) imagetext = pytesseract.image_to_string(img) print(imagetext) # img.show() This is the status of the modified image when I run the above script: The output I'm having: WIS Expected output: TOOLS
type: Question
has answer: http://stackoverflow.com/a/51002047
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88898434
tagged with: python-imaging-library
has title: Unable to extract a word out of an image
has answer: http://stackoverflow.com/a/50950424
answer count: 2
score: 4
favorite count: 0
upvote count: 5
downvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/51002047

http://stackoverflow.com/comment/131162875
has text: I found that `sys.executable` works only on .exe files but `sys.argv[0]` works when I run the script like this `python script.py` and when I build the script to exe and run it using cmd. This is how I reference things now: `os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])), 'Resources')`
comment on: http://stackoverflow.com/a/53511380
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/51594531
has body: The below code prints the first repeated character in a string. I used the functionality of the list to solve this problem. def findChar(inputString): list = [] for c in inputString: if c in list: return c else: list.append(c) return 'None' print (findChar('gotgogle')) Working fine as well. It gives the result as 'g'.
score: 0
upvote count: 1
downvote count: 1
answers question: http://stackoverflow.com/q/50976511
type: Answer

http://stackoverflow.com/q/50993773
has answer: http://stackoverflow.com/a/50993890
type: Question
has body: I'm trying to get the 3rd string between the 3rd and 4th occurrence of the / character using regex the list of strings is something like this: ... /restaurants/garnish/گارنیش/ /restaurants/burger1358/برگر-۱۳۵۸/ /restaurants/delion-saadat/صبحانه--و-میان-وعده-دلیون-شعبه-سعادت-آباد/ /restaurants/kamran/کامران--اسکای-فال-سابق-/ ... the desired output for the list above is something like this: ... گارنیش برگر-۱۳۵۸ صبحانه--و-میان-وعده-دلیون-شعبه-سعادت-آباد کامران--اسکای-فال-سابق- ... as the desired part of the string is not ASCII (English) and there is no pattern (names being different), I cannot figure out the proper regex syntax.
has answer: http://stackoverflow.com/a/50993896
answer count: 3
has comment: http://stackoverflow.com/comment/88982081
has comment: http://stackoverflow.com/comment/88982336
tagged with: python
tagged with: regex
accepted answer: http://stackoverflow.com/a/50993896
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/50994253
possible better answer: http://stackoverflow.com/a/50993890
has title: Regex: nth occurrence of a string

http://stackoverflow.com/q/50887460
has answer: http://stackoverflow.com/a/50887707
tagged with: regex
favorite count: 0
has comment: http://stackoverflow.com/comment/88776280
upvote count: 2
has comment: http://stackoverflow.com/comment/88776277
accepted answer: http://stackoverflow.com/a/50887694
tagged with: python
type: AnsweredQuestion
score: 2
tagged with: list
type: Question
linked to: http://stackoverflow.com/q/1080411
possible better answer: http://stackoverflow.com/a/50887477
has comment: http://stackoverflow.com/comment/88776798
has comment: http://stackoverflow.com/comment/88776342
downvote count: 0
has answer: http://stackoverflow.com/a/50887477
has body: I'm fetching webpages with the use of curl and storing it in a variable in python. var = '&lt;body&gt;&lt;img src=\"https://cdn.neow.in/news/images/uploaded/2018/06/Gaming sloop, preview group, hardware _mediump.jpg\" style=\"display: none;\"/&gt;&lt;div class=\"wrapper\"&gt;' I just want the links from the string for example: "https://cdn.neow.in/news/images/uploaded/2018/06/Gaming sloop, preview group, hardware _mediump.jpg" I Tried matching with regular expressions by defining the start of regular expression as "(https|http) and end as ": x = re.findall(r'"(https|http)*"$', var) print(x) But I'm not getting the output. Please help me with this, thanks in advance. &gt;&gt;&gt;[]
has title: How to get url from a string in python
has answer: http://stackoverflow.com/a/50887694
has comment: http://stackoverflow.com/comment/88776812
linked to: http://stackoverflow.com/q/1732348
answer count: 3

http://stackoverflow.com/comment/88863242
type: QuestionComment
has text: "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%d,%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,%s' at line 7")
type: Comment
comment on: http://stackoverflow.com/q/50932144
score: 0

http://stackoverflow.com/comment/88792537
score: 0
type: Comment
type: QuestionComment
has text: Yes, they are using a different data structure than mine. While I'm only using certain columns (1,2,3...136), they are using all of them, and each row is on a separate array, they are using all data.
comment on: http://stackoverflow.com/q/50896193

http://stackoverflow.com/comment/88808551
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50904156
score: 0
has text: Why don't you use `xml.etree.ElementTree` to parse the xml files?

http://stackoverflow.com/a/51100510
has body: Small workaround is to define it like this: import pandas as pd pd.core.common.is_list_like = pd.api.types.is_list_like import pandas_datareader
answers question: http://stackoverflow.com/q/50863799
type: Answer
score: 0

http://stackoverflow.com/q/50990122
has comment: http://stackoverflow.com/comment/88975262
downvote count: 0
has body: I have a data frame of 370000 rows x 340 columns, in this DataFrame I have mixed numeric and non-numeric values between columns. I'd like to merge rows, basing on user_id, that certain numeric values are summed, and non-numeric values are preserved. Given table: user_id points gender age 11111 10000 male 18 2222 4200 female 33 11111 30000 male 18 2222 10 female 33 11111 20000 male 18 I'd expect this result: user_id points gender age 11111 60000 male 18 2222 4210 female 33 While summing rows, I need to sum approx. 300 values out of 340, but I'm new to pandas struggling to find the right way to do this, would appreciate any tips.
favorite count: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/50990330
has comment: http://stackoverflow.com/comment/88975025
has comment: http://stackoverflow.com/comment/88974897
type: UnansweredQuestion
upvote count: 1
tagged with: python
score: 1
has answer: http://stackoverflow.com/a/50990334
type: Question
has title: Sum certain values between rows
answer count: 2

http://stackoverflow.com/a/50948440
has comment: http://stackoverflow.com/comment/88897755
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50937044
answers question: http://stackoverflow.com/q/50937044
score: 1
upvote count: 1
type: AcceptedAnswer
has body: You have a bunch of errors in your code. In first place, you should use () to invoke a function and not just its name, so you would need to change the radio button like this: Then you will need to modify the function code to get all the values of the checked ckeckboxes; function CheckBoxes(clicked) { // array of checkboxes to check var checked = [15, 16, 17, 18, 19, 22, 23, 26, 28, 29, 30, 31, 33, 34, 35, 36, 39, 40, 47, 48, 50, 52, 59, 60]; // if the radio button is checked if($(clicked).is(':checked')) { // for each checked checkbox $('input[name*="report_id"]').each(function() { // set as checked if the value is defined in the array // Convert $(this).val() to Numnber() to compare against a number $(this).prop('checked', checked.indexOf(Number($(this).val())) >= 0); }); } } As a side note, if you are going to submit a form with multiple checkboxes with the same name, you should use the array name definition []. In your case it will be (note the use of the square brackets in the name definition): Check my working snippet: function CheckBoxes(clicked) { // Array of checked values var checked = [1, 2, 5]; // if the radio button is checked if($(clicked).is(':checked')) { // for each checked checkbox $('input[name*="report_id"]').each(function() { // set as checked if the value is defined in the array // Convert $(this).val() to Numnber() to compare against a number $(this).prop('checked', checked.indexOf(Number($(this).val())) >= 0); }); } } Value 1 Value 2 Value 3 Value 4 Value 5 Hope it helps.
type: Answer

http://stackoverflow.com/q/50924670
answer count: 0
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/47804753
has comment: http://stackoverflow.com/comment/88850436
has comment: http://stackoverflow.com/comment/88939121
has title: Need a Python script for Slack to deactivate a user
has comment: http://stackoverflow.com/comment/88850380
has comment: http://stackoverflow.com/comment/88850619
tagged with: slack
type: Question
score: 0
has body: import os from slackclient import slackclient SLACK_TOKEN = os.eviron.get ('SLACK_TOKEN') slack_client = SlackClient (SLACK_TOKEN) username=raw_input("Please Type the user you would like to deactivate: ") print "User: " users.admin.setInactive &lt;--- Not sure how to implement this
has comment: http://stackoverflow.com/comment/88858420
tagged with: python
linked to: http://stackoverflow.com/q/47804753

http://stackoverflow.com/q/50948599
score: 3
answer count: 0
downvote count: 0
tagged with: keras
favorite count: 0
has body: I am extending the WGAN-GP to be conditional from code base found here: https://github.com/eriklindernoren/Keras-GAN/blob/master/wgan_gp/wgan_gp.py When I train the model, it doesn't seem to be conditioned on the labels. This is how I build my model. # The generator takes noise and the target label (states) as input # and generates the corresponding samples of that label noise = Input(shape=(self.latent_size, ), name="noise") label = Input(shape=(self.label_size, ), name="labels") real_samples = Input(shape=(self.input_size,), name="real") self.discriminator = self.build_discriminator() self.generator = self.build_generator([noise, label]) # First we train the discriminator self.generator.trainable = False fake_samples = self.generator([noise, label]) fake = self.discriminator([fake_samples, label]) valid = self.discriminator([real_samples, label]) interpolated = Lambda(self.random_weighted_average)([real_samples, fake_samples]) valid_interp = self.discriminator([interpolated, label]) self.d_model = Model([real_samples, noise, label], [valid, fake, valid_interp], name="discriminator") # Time to train the generator self.discriminator.trainable = False self.generator.trainable = True noise_gen = Input(shape=(self.latent_size,), name="noise_gen") fake_samples = self.generator([noise_gen, label]) valid = self.discriminator([fake_samples, label]) self.g_model = Model([noise_gen, label], valid, name="generator") self.g_model.compile(loss=self.wasserstein_loss, optimizer=optimizer) Plotting the model results in: I don't know how to interpret the merged arrows on the right. The label should be concatenated IN the discriminator. I have a feeling this line messes something up: self.d_model = Model([real_samples, noise, label], [valid, fake, valid_interp], name="discriminator") Since I'm just passing the label and I don't know how Keras routes that input to the other outputs..
type: Question
tagged with: python
tagged with: generative-adversarial-network
upvote count: 3
has title: Implementation of conditional WGAN-GP in Keras
type: UnansweredQuestion

http://stackoverflow.com/q/50951592
has comment: http://stackoverflow.com/comment/88906840
duplicate of: http://stackoverflow.com/q/23843234
type: Question
score: 0
has comment: http://stackoverflow.com/comment/88906724
answer count: 1
linked to: http://stackoverflow.com/q/23843234
type: UnansweredQuestion
tagged with: garbage-collection
tagged with: python
has title: Instantiation of a Python class without assignment - why is the resulting object not garbage collected?
has answer: http://stackoverflow.com/a/50954495
has body: Here's my problem. I fire up a fresh python console and I type in the following: import gc meeseeks_instance = False class Meeseeks(object): def __init__(self): gc.collect() print('Look at me!') def __del__(self): print('Mission accomplished!') globals()['meeseks_instance'] = False def __new__(cls): gc.collect() if globals()['meeseeks_instance']: raise Exception('Theres already a Meeseeks!') globals()['meeseeks_instance'] = True return super().__new__(cls) Now, if I type: &gt;&gt;&gt; mymeeseeks = Meeseeks() Look at me! &gt;&gt;&gt; del mymeeseeks Mission accomplished! Fantastic. Now: &gt;&gt;&gt; Meeseeks() Look at me! &lt;Meeseeks object at 0x043DE290&gt; The object was not assigned, so it's not reachable and it should be garbag collected; anyways, it seems that garbage collection was not yet run. But, if I force it, the object is correctly collected: &gt;&gt;&gt; gc.collect() Mission accomplished! 0 And here starts the trouble. If I try to instantiate two Meeseeks, the explicit garbage collection in __new__ does not fire and the Exception is raised: &gt;&gt;&gt; Meeseeks() Look at me! &lt;Meeseeks object at 0x043B0990&gt; &gt;&gt;&gt; Meeseeks() Traceback (most recent call last): File "&lt;input&gt;", line 1, in &lt;module&gt; File "&lt;input&gt;", line 18, in __new__ Exception: Theres already a Meeseeks! Why does this happen? How can I make so that trying to instantiate a new Meeseeks forces garbage collection of the previous, unreachable Meeseeks?

http://stackoverflow.com/q/50905462
score: 1
possible better answer: http://stackoverflow.com/a/50905536
has answer: http://stackoverflow.com/a/50905593
has comment: http://stackoverflow.com/comment/88811879
has comment: http://stackoverflow.com/comment/88810699
has title: Printing prime number in python
has comment: http://stackoverflow.com/comment/88810879
favorite count: 0
tagged with: logic
has body: I am trying to print prime numbers in python in the range 3-50. Here is the code: for i in range(3,51): flag=0 for j in range(3,i): if(i%j==0): flag=1 if(flag==0): print(i) The code is running correctly except THAT IT IS ALSO PRINTING 4. Please tell if there is anything wrong with the logic of the code (ignore the efficiency issues).
answer count: 9
has comment: http://stackoverflow.com/comment/88811123
has answer: http://stackoverflow.com/a/50909728
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50906097
has answer: http://stackoverflow.com/a/65103007
upvote count: 2
has comment: http://stackoverflow.com/comment/88810769
has answer: http://stackoverflow.com/a/68152619
tagged with: loops
has answer: http://stackoverflow.com/a/50905536
has comment: http://stackoverflow.com/comment/88810849
downvote count: 1
has answer: http://stackoverflow.com/a/58927867
type: Question
accepted answer: http://stackoverflow.com/a/50909728
has answer: http://stackoverflow.com/a/50905640
has answer: http://stackoverflow.com/a/50906580

http://stackoverflow.com/q/50957993
linked to: http://stackoverflow.com/q/43055206
type: AnsweredQuestion
has title: Fill all values in a group with the first non-null value in that group
has comment: http://stackoverflow.com/comment/88914198
has comment: http://stackoverflow.com/comment/88913535
has answer: http://stackoverflow.com/a/50958247
upvote count: 1
has comment: http://stackoverflow.com/comment/88914211
type: Question
has body: The following is the pandas dataframe I have: cluster Value 1 A 1 NaN 1 NaN 1 NaN 1 NaN 2 NaN 2 NaN 2 B 2 NaN 3 NaN 3 NaN 3 C 3 NaN 4 NaN 4 S 4 NaN 5 NaN 5 A 5 NaN 5 NaN If we look into the data, cluster 1 has Value 'A' for one row and remain all are NA values. I want to fill 'A' value for all the rows of cluster 1. Similarly for all the clusters. Based on one of the values of the cluster, I want to fill the remaining rows of the cluster. The output should be like, cluster Value 1 A 1 A 1 A 1 A 1 A 2 B 2 B 2 B 2 B 3 C 3 C 3 C 3 C 4 S 4 S 4 S 5 A 5 A 5 A 5 A I am new to python and not sure how to proceed with this. Can anybody help with this ?
tagged with: dataframe
possible better answer: http://stackoverflow.com/a/50958514
has comment: http://stackoverflow.com/comment/88913524
answer count: 2
has answer: http://stackoverflow.com/a/50958514
accepted answer: http://stackoverflow.com/a/50958247
downvote count: 0
score: 1
favorite count: 0
tagged with: pandas
tagged with: python
tagged with: nan

http://stackoverflow.com/comment/88938678
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50970824
has text: Sorting can be secondary first i need the data in the list of key value pairs inside the list

http://stackoverflow.com/a/51002795
answers question: http://stackoverflow.com/q/50943417
downvote count: 0
has comment: http://stackoverflow.com/comment/89031722
type: Answer
score: 6
upvote count: 6
has body: From my understanding of the source code what you want is not possible. I won't dig and try to explain every single relevant lines of code, but basically, here is what happend: Your Lexer class is pygments.lexers.c_cpp.CLexer, which inherits from pygments.lexer.RegexLexer. pygments.lex(lexer, code) function do nothing more than calling get_tokens method on lexer and handle errors. lexer.get_tokens basically parse source code in unicode string and call self.get_tokens_unprocessed get_tokens_unprocessed is defined by each Lexer in your case the relevant method is pygments.lexers.c_cpp.CFamilyLexer.get_tokens_unprocessed. CFamilyLexer.get_tokens_unprocessed basically get tokens from RegexLexer.get_tokens_unprocessed and reprocess some of them. Finally, RegexLexer.get_tokens_unprocessed loop on defined token types (something like (("function", ('pattern-to-find-c-function',)), ("class", ('function-to-find-c-class',)))) and for each type (function, class, comment...) find all matches within the source text, then process the next type. This behavior make what you want impossible because it loops on token types, not on text. To make more obvious my point, I added 2 lines of code in the lib, file: pygments/lexer.py, line: 628 for rexmatch, action, new_state in statetokens: print('looking for {}'.format(action)) m = rexmatch(text, pos) print('found: {}'.format(m)) And ran it with this code: import pygments import pygments.lexers lexer = pygments.lexers.get_lexer_for_filename("foo.h") sample=""" class foo{}; """ print(list(lexer.get_tokens(sample))) Output: [...] looking for Token.Keyword.Reserved found: None looking for Token.Name.Builtin found: None looking for &lt;function bygroups.&lt;locals&gt;.callback at 0x7fb1f29b52f0&gt; found: None looking for Token.Name found: &lt;_sre.SRE_Match object; span=(6, 9), match='foo'&gt; [...] As you can see, the token types are what the code iterate on. Taking that and (as Tarun Lalwani said in comments) the fact that a single new chara…
has comment: http://stackoverflow.com/comment/89115794
has comment: http://stackoverflow.com/comment/89028291
has comment: http://stackoverflow.com/comment/89029939

http://stackoverflow.com/comment/88959445
score: 0
type: Comment
type: QuestionComment
has text: @Imma I updated my question.
comment on: http://stackoverflow.com/q/50966243

http://stackoverflow.com/comment/88966893
type: QuestionComment
comment on: http://stackoverflow.com/q/50986068
has text: @jezrael, look at this.
score: 0
type: Comment

http://stackoverflow.com/comment/88739951
comment on: http://stackoverflow.com/a/50868611
has text: Sorry but nothing changed
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/50912583
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/88827911
tagged with: python
has comment: http://stackoverflow.com/comment/88827890
answer count: 0
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88825334
type: Question
has body: I am running windows commands like ipconfig and trying to capture them in an html page. I am running into an issue where the formatting is not what I would want. I have a function that writes my html. def writeHTML(toWrite): output.write("&lt;p&gt;") if toWrite.find(" ") == 1: toWrite.replace(" ", "&amp;nbsp") output.write(toWrite) print(toWrite) output.write("&lt;/p&gt;") I have tried to "find" \t and the blank spaces but the fomatting does not work. Preferred Output: Current Output: How can I maintain the formatting?
has comment: http://stackoverflow.com/comment/88827240
has title: Python: Saving formatting when creating an html output
has comment: http://stackoverflow.com/comment/88832757

http://stackoverflow.com/a/50954179
type: Answer
answers question: http://stackoverflow.com/q/50917165
upvote count: 1
score: 1
has body: If you want to disable rotation you just have to setup the interactor style for 2D images. In this case, vtkInteractorStyleImage will do it. Here is an example: vtkSmartPointer&lt;vtkInteractorStyleImage&gt; style = vtkSmartPointer&lt;vtkInteractorStyleImage&gt;::New(); renderWindowInteractor-&gt;SetInteractorStyle(style); Take this example (https://www.vtk.org/Wiki/VTK/Examples/Cxx/Filtering/ConstrainedDelaunay2D) and add the above lines below the following line: renderWindowInteractor-&gt;SetRenderWindow(renderWindow); Hope it helps!
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50917165

http://stackoverflow.com/q/50855155
tagged with: python
has title: Distinct Row Values as Column with group by on another field
tagged with: dynamic-pivot
upvote count: 0
has comment: http://stackoverflow.com/comment/88713222
has answer: http://stackoverflow.com/a/50855661
tagged with: pivot
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88713347
tagged with: mysql
type: Question
has answer: http://stackoverflow.com/a/50855264
answer count: 2
tagged with: sql
has body: I've loans data and I want to group by month of date and get amount via distinct product My data looks like this disbursementdate | amount | product | cluster 2017-01-01 | 1000 | HL | West 2018-02-01 | 1000 | PL | East So After querying, I'd ideally want the result to look like this Month | HL | PL January 2018 | 1000 | 0 February 2018 | 100 | 1000 Please note that there could be more products and there's no way of knowing how many unique ... so sum case when wouldnt work I'm struggling with query
favorite count: 0
has comment: http://stackoverflow.com/comment/88713058
downvote count: 3
score: -3

http://stackoverflow.com/q/50888069
tagged with: python-2.7
score: 0
type: UnansweredQuestion
has body: &gt;&gt;&gt; t=(1,2,3) &gt;&gt;&gt; t+t (1, 2, 3, 1, 2, 3) &gt;&gt;&gt; t*2 (1, 2, 3, 1, 2, 3) &gt;&gt;&gt; t+t==t*2 True &gt;&gt;&gt; t+t is t*2 False &gt;&gt;&gt; id(t+t) 49172744L &gt;&gt;&gt; id(t*2) 49172744L but they also have same id (t+t),(t*2). Why are they not equal
has comment: http://stackoverflow.com/comment/88777722
tagged with: python
linked to: http://stackoverflow.com/q/1504717
has comment: http://stackoverflow.com/comment/88777499
linked to: http://stackoverflow.com/q/13650293
answer count: 0
duplicate of: http://stackoverflow.com/q/1504717
has title: tuple of value and identity are same but identity testing (is) get false in python
type: Question
has comment: http://stackoverflow.com/comment/88777503

http://stackoverflow.com/comment/88861497
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50931196
has text: Is this the same situation? [reclassing an instance](https://stackoverflow.com/questions/990758/reclassing-an-instance-in-python)

http://stackoverflow.com/q/50896837
has comment: http://stackoverflow.com/comment/88793465
score: 1
has body: Is there any algorithm to get number of repeating overlap substrings in an string? This question is similar to Splitting a Python list into a list of overlapping chunks, but in my case changed elements are first and last elements of each substring! for example when: string = "HelloWorld" k = 4 then: subString = ["Hell","ello","lloW","loWo","oWor","Worl","orld"] i tried this: i = 0 while len(string[i+4:])&gt;=4: i+=1 print i
has comment: http://stackoverflow.com/comment/88793388
has answer: http://stackoverflow.com/a/50896923
type: Question
has comment: http://stackoverflow.com/comment/88794700
upvote count: 2
has comment: http://stackoverflow.com/comment/88794006
has comment: http://stackoverflow.com/comment/88793561
tagged with: algorithm
has comment: http://stackoverflow.com/comment/88794124
duplicate of: http://stackoverflow.com/q/36586897
tagged with: dynamic-programming
answer count: 1
downvote count: 1
tagged with: string
tagged with: sequence
favorite count: 0
has comment: http://stackoverflow.com/comment/88793394
has comment: http://stackoverflow.com/comment/88794228
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/36586897
has title: what is the best algorithm to get repetition of k length substring in a string in the shortest possible time?
has comment: http://stackoverflow.com/comment/88794810
has comment: http://stackoverflow.com/comment/88793416
has comment: http://stackoverflow.com/comment/88793459

http://stackoverflow.com/q/50976177
tagged with: matplotlib
upvote count: 4
type: AnsweredQuestion
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/50977040
type: Question
tagged with: python
score: 4
answer count: 1
accepted answer: http://stackoverflow.com/a/50977040
tagged with: colormap
has body: Some of the standard matplotlib cmaps, such as viridis or jet show dark colors in small values. While this is what I need, I like them to show nothing, i.e. white background if the value is exactly zero. For non zero values the usual colors of that color map are fine. Is it possible to do this?
has title: matplotlib modified color map with white as zero

http://stackoverflow.com/comment/88899395
type: Comment
comment on: http://stackoverflow.com/a/50936886
score: 0
type: AnswerComment
has text: plt.legend(filenames). https://matplotlib.org/api/_as_gen/matplotlib.pyplot.legend.html

http://stackoverflow.com/q/50905170
tagged with: matplotlib
tagged with: pyqt5
has title: How to show matplotlib.pyplot in qt widget?
type: Question
answer count: 2
tagged with: pyqt
has answer: http://stackoverflow.com/a/50909905
favorite count: 0
tagged with: python-3.x
upvote count: 2
has body: I want to show the pyplot image in widget (QWidget) that I put in a gui designed in QtDesigner: When I push the Çiz button I want to show the image that I can create in python with that code: points = np.array([(1, 1), (2, 4), (3, 1), (9, 3)]) x = points[:,0] y = points[:,1] # calculate polynomial z = np.polyfit(x, y, 2) f = np.poly1d(z) x_fit = np.linspace(min(x), max(x), 10000) y_fit = [f(_x) for _x in x_fit] plt.plot(x, y) plt.plot(x_fit, y_fit) plt.show() EDIT I made some changes according to the answer but I have new problems. After I promote it: I rearrange my code below: # calculate polynomial and r self.x_fit = np.linspace(min(self.itemX), max(self.itemY), 10000) self.y_fit = [f(_x) for _x in self.x_fit] self._dlg.plotwidget.plot(self.itemX, self.itemY) self._dlg.plotwidget.plot(self.x_fit, self.y_fit) self.itemX is x values in a list. self.itemY is y values in a list. self._dlg is the MainWindow that you see. When I try to open that window I get this error message:
type: UnansweredQuestion
tagged with: python
downvote count: 1
has answer: http://stackoverflow.com/a/50905461
score: 1

http://stackoverflow.com/q/51009389
has title: Selecting paragraph by name and not by location with Python Docx
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51009451
tagged with: python
downvote count: 0
score: 1
type: Question
upvote count: 1
answer count: 1
has body: I am using docx to edit paragraphs, you understand I can use: document.paragraphs[15] = "Hello world" Is there a way to select the paragraph using its name? Something like: document.paragraphs[docx.text.paragraph.Paragraph object at 0x112dbbe48] = "Hello world"
favorite count: 0
tagged with: http://stackoverflow.com/tag/docx

http://stackoverflow.com/a/50868195
accepted answer of: http://stackoverflow.com/q/50868137
answers question: http://stackoverflow.com/q/50868137
upvote count: 1
type: AcceptedAnswer
type: Answer
has body: You can create a div below the box that receives the input for the credential/credentials that where in valid: In the HTML: {{message_username}} {{message_password}} Log In Then, in the app (utilizing placeholder lookup functions for username and password): @app.route('/login', methods = ['GET', 'POST']) def login(): if flask.request.method == 'POST': username = flask.request.form['username'] password = flask.request.form['password'] u_flag, p_flag = is_valid_username(username), is_valid_password(password) if not u_flag or not p_flag: return flask.render_template('login.html', message_username = '' if u_flag else 'Invalid Username', message_password = '' if p_flag else 'Invalid Password' return flask.render_template('login.html', message_username = '', message_password = '')
downvote count: 0
score: 1

http://stackoverflow.com/comment/88926211
type: QuestionComment
has text: @Aran-Fey I did understand that `is` and `==` were different but I wasn't quite clear on all the details. I did not understand enough of the mechanics of python to consider that a python object might be cached or reused. I've accepted an answer that helped me understand the difference more clearly.
comment on: http://stackoverflow.com/q/50964352
score: 0
type: Comment

http://stackoverflow.com/q/50950220
has answer: http://stackoverflow.com/a/50950304
accepted answer: http://stackoverflow.com/a/50950304
has comment: http://stackoverflow.com/comment/88898177
type: Question
has comment: http://stackoverflow.com/comment/88898118
score: 0
has title: Python dictionary to C++ map
answer count: 1
has comment: http://stackoverflow.com/comment/88898090
tagged with: python
tagged with: dictionary
tagged with: c++
type: AnsweredQuestion
has body: I am very new to C++ and am trying to translate a dictionary into a C++ format. I can't quite seem to find the answer I am looking for from the previous questions submitted on here. I have code as follows: #include &lt;iostream&gt; #include &lt;map&gt; using namespace std; typedef std::map&lt;string, int&gt; BasePairMap; int main() { BasePairMap m; m['power'] = 0; m['select'] = 1; m['backup'] = 2; ... ... ... m['rewind'] = 71; m['boxoffice'] = 240; m['sky'] = 241; return 0; } But I keep getting character overflow errors. How can I map string/int pairs together in C++? Thanks

http://stackoverflow.com/comment/88846292
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50880013
has text: Thx a lot for your thorough answers Lucas !
type: AnswerComment

http://stackoverflow.com/q/50999989
has title: I want loop to open youtube url on google chrome after every 60 second and refresh it then close
has comment: http://stackoverflow.com/comment/88998592
tagged with: selenium-webdriver
answer count: 1
downvote count: 1
has body: I have tried this code but its not working properly, its open the google chrome one time but not youtube url and after one time open its getting show error anybody could help me make some changes on my code : from selenium import webdriver as wd chromedir = 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe' driver = wd.Chrome(chromedir) website = input("http:\youtu.be/RsWCo_xGXxY") driver.open(website) def until_func(driver): driver.refresh() orderElem = WebDriverWait(driver, timeout=60, poll_frequency=10).until(until_func)
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51000038
score: 1
favorite count: 0
type: Question
upvote count: 2
tagged with: python

http://stackoverflow.com/a/50893661
has comment: http://stackoverflow.com/comment/88787591
type: Answer
score: 1
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/50893309
has comment: http://stackoverflow.com/comment/88787836
has body: set_password is a method so I'd suggest to do the following: Replace: user.set_password = self.cleaned_data["password"] with user.set_password(self.cleaned_data["password"])

http://stackoverflow.com/q/51001489
tagged with: python
has title: Download text data from HTML link in Python
has comment: http://stackoverflow.com/comment/88996968
tagged with: https
linked to: http://stackoverflow.com/q/23254013
has comment: http://stackoverflow.com/comment/88997050
type: Question
has comment: http://stackoverflow.com/comment/88997004
score: 0
tagged with: pandas
has body: Hi I want to download delimited text which is hosted on a HTML Link. (The link is accessible on a Private network only, so can't share here). In R, following function solves the purpose (all other functions gave "Unauthorized access" or "401" error) url = 'https://dw-results.ansms.com/dw-platform/servlet/results? job_id=13802737&amp;encoding=UTF8&amp;mimeType=plain' download.file(url, "~/insights_dashboard/testing_file.tsv") a = read.csv("~/insights_dashboard/testing_file.tsv",header = T,stringsAsFactors = F,sep='\t') I want to do the same thing in Python, for which I used: (A)urllib and requests.get() import urllib.request url_get = requests.get(url, verify=False) urllib.request.urlretrieve(url_get, 'C:\\Users\\cssaxena\\Desktop\\24.tsv') (B)requests.get() and read.html url='https://dw-results.ansms.com/dw-platform/servlet/results? job_id=13802737&amp;encoding=UTF8&amp;mimeType=plain' s = requests.get(url, verify=False) a = pd.read_html(io.StringIO(s.decode('utf-8'))) (C) Using wget: import wget url = 'https://dw-results.ansms.com/dw-platform/servlet/results? job_id=13802737&amp;encoding=UTF8&amp;mimeType=plain' wget.download(url,--auth-no-challenge, 'C:\\Users\\cssaxena\\Desktop\\24.tsv') OR wget --server-response -owget.log "https://dw-results.ansms.com/dw-platform/servlet/results? job_id=13802737&amp;encoding=UTF8&amp;mimeType=plain" NOTE: The URL doesn't asks for any credentials and it is accessible by browser and able to download using R with download.file. I am looking for a solution in Python
answer count: 1
tagged with: url
has comment: http://stackoverflow.com/comment/88996909
has answer: http://stackoverflow.com/a/52042725
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88997823
has comment: http://stackoverflow.com/comment/88997517

http://stackoverflow.com/q/51005957
tagged with: win32gui
has comment: http://stackoverflow.com/comment/89005578
type: Question
score: -2
has title: C++ Getting the Name of a Process via ProcessID
has answer: http://stackoverflow.com/a/51007385
downvote count: 3
upvote count: 1
has comment: http://stackoverflow.com/comment/89005498
answer count: 1
favorite count: 0
has body: For example from the PID 10948 I would like to get the process name of firefox.exe I've tried using GetModuleFileNameEx, GetModuleFileName, GetProcessImageFileName, and GetModuleBaseName and all of them result in a garbage string of characters such as: ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠ 7Σ My code: DWORD* thread = new DWORD; TCHAR szName[_MAX_FNAME]; HANDLE processhandle = OpenProcess(PROCESS_QUERY_INFORMATION, false, GetWindowThreadProcessId(GetForegroundWindow(), thread)); GetProcessImageFileName(processhandle, szName, _MAX_FNAME); strrchr(szName, '\\'); Originally I tried doing this using python using the win32gui library using the process's handle, which worked, but it would not be able to find command prompt handles. I don't care which language I use to solve this problem of identifying the current program being in use as long as I am able to find the name of all programs that I can possibly use.
has comment: http://stackoverflow.com/comment/89005605
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89005598
tagged with: process
tagged with: python
tagged with: c++
tagged with: winapi

http://stackoverflow.com/q/51002355
has comment: http://stackoverflow.com/comment/88998490
has answer: http://stackoverflow.com/a/51002483
downvote count: 0
tagged with: string
has title: Speeding up a function that outputs products with repeats in Python
favorite count: 0
has comment: http://stackoverflow.com/comment/88998722
tagged with: python
has answer: http://stackoverflow.com/a/51002422
score: 2
type: AnsweredQuestion
has body: I've written a function which returns a list of all possible 'products' of a string with repeats (for a spell check program): def productRepeats(string): comboList = [] for item in [p for p in product(string, repeat = len(list(string)))]: if item not in comboList: comboList.append("".join(item)) return list(set(comboList)) Therefore, when print(productRepeats("PIP")) is inputted, he output is (I don't care what the order is): ['PII', 'IIP', 'PPI', 'IPI', 'IPP', 'PPP', 'PIP', 'III'] However, if I try anything greater than 5 digits (PIIIIP), it takes about 30 seconds to output, even though there are only 64 ways Is there any way I could speed this up, as getting the list for the string 'GERAWUHGP', for instance, takes well over half an hour?
accepted answer: http://stackoverflow.com/a/51002483
upvote count: 2
possible better answer: http://stackoverflow.com/a/51002422
type: Question
tagged with: python-itertools
has comment: http://stackoverflow.com/comment/88998587
answer count: 2

http://stackoverflow.com/q/50965278
tagged with: php
type: AnsweredQuestion
has title: How to call a php script in server from python
has answer: http://stackoverflow.com/a/50965381
has comment: http://stackoverflow.com/comment/88926992
type: Question
possible better answer: http://stackoverflow.com/a/50972436
has comment: http://stackoverflow.com/comment/88926877
answer count: 2
has comment: http://stackoverflow.com/comment/88926939
has answer: http://stackoverflow.com/a/50972436
downvote count: 0
has body: I am trying to run the php script which is in my server from the python project which is in my local machine. I have tried following till now Python Side: # -*- coding: utf-8 -*- import subprocess import json import sys import os def php(script_path): p = subprocess.Popen(['php', script_path], stdout=subprocess.PIPE) result = p.communicate()[0] return result image_dimensions_json = str(php("http://XXX.XXX.XX.XX/logistic_admin/test1.php")) dic = json.loads(image_dimensions_json) print str(dic["0"]) + "|" + str(dic["1"]) php side: test1.php &lt;?php echo(json_encode(getimagesize($argv[1]))); ?&gt; But I am facing following error: Traceback (most recent call last): File "D:\folder\test.py", line 20, in &lt;module&gt; image_dimensions_json = str(php("http://XXX.XXX.XX.XX/logistic_admin/test1.php")) File "D:\folder\test.py", line 16, in php p = subprocess.Popen(['php', script_path], stdout=subprocess.PIPE) File "C:\Python27\Lib\subprocess.py", line 711, in __init__ errread, errwrite) File "C:\Python27\Lib\subprocess.py", line 948, in _execute_child startupinfo) WindowsError: [Error 2] The system cannot find the file specified
has comment: http://stackoverflow.com/comment/88926915
tagged with: python-2.7
accepted answer: http://stackoverflow.com/a/50965381
tagged with: python
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88927024
tagged with: subprocess
upvote count: 1

http://stackoverflow.com/a/50907010
answers question: http://stackoverflow.com/q/50906756
upvote count: 2
has body: Slightly long-winded answer utilizing itertools.groupby. For greater than ~1000 rows, use @MaxU's solution - it's faster. from itertools import groupby, chain from operator import itemgetter chainer = chain.from_iterable def sumfunc(x): return (sum(map(itemgetter(1), x)), len(x)) grouper = groupby(zip(df['Name'], df['In.Cl']), key=itemgetter(0)) summer = [sumfunc(list(j)) for _, j in grouper] df['Name'] += pd.Series(list(chainer(repeat(j, j) for i, j in summer))).astype(str) df['col2'] = list(chainer(repeat(i, j) for i, j in summer)) print(df) In.Cl Name col2 0 2 A1 2 1 1 B2 6 2 5 B2 6 3 2 A2 6 4 4 A2 6 5 2 B1 2 6 3 C3 12 7 1 C3 12 8 8 C3 12 9 5 B1 5 10 7 C1 7
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/q/50915127
has comment: http://stackoverflow.com/comment/88832298
has answer: http://stackoverflow.com/a/50915500
accepted answer: http://stackoverflow.com/a/50915500
type: Question
has answer: http://stackoverflow.com/a/50915612
has body: For homework I am trying to strip a set of characters inputted from the user from a sentence inputted by a user. This is the code that I have come up with so far using Python 2.7: sentence = raw_input("Please write a sentence. ") remove = raw_input("Please input characters to remove from sentence. ") remove = remove.strip(" ") # in case user added spaces sentence = sentence.strip(remove) print sentence
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/88830350
has comment: http://stackoverflow.com/comment/88830602
has comment: http://stackoverflow.com/comment/88871675
has comment: http://stackoverflow.com/comment/88830543
has title: How to remove characters in one strong from another string
has comment: http://stackoverflow.com/comment/88830363
tagged with: python
possible better answer: http://stackoverflow.com/a/50915290
linked to: http://stackoverflow.com/q/3939361
answer count: 4
has answer: http://stackoverflow.com/a/50915290
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88830321
has answer: http://stackoverflow.com/a/50915297

http://stackoverflow.com/a/50923467
type: Answer
has comment: http://stackoverflow.com/comment/88849582
score: 0
has body: When you islice(inReader, ...) you consume all the data in inReader without saving it anywhere. You need to store the data in a variable, and only then find the max. import csv from itertools import islice headerLines = 15 # you can put both context managers in a single "with" with open("input.csv", "r") as inf, open('output', 'w') as outf: inReader = csv.reader(inf, delimiter='\t') outWriter = csv.writer(outf, delimiter="\t") inLines = list(inReader) Xmax = max(float(row[1]) for row in islice(inLines, headerLines, None)) for i,row in enumerate(inLines): # refactor to avoid code duplication if i &gt;= headerLines: row[1] = str(float(row[1])*(-1)+Xmax) row[5] = str(float(row[5])-180) outWriter.writerow(row)
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88848198
accepted answer of: http://stackoverflow.com/q/50923028
answers question: http://stackoverflow.com/q/50923028

http://stackoverflow.com/q/50896928
has answer: http://stackoverflow.com/a/50925601
tagged with: android-studio
has body: I want to send a mp3 file using POST request from android studio to a flask server. I have read an mp3 file from device and stored in input stream object. The flask server identifies the request to be a POST request and creates the mp3 file. But when I play the mp3 file it does not work. So the connection part does not have any problem. I would like to know how to send this inputstream object in my POST request and get it successfully play the mp3 file on the server (Raspberry Pi). The part to get the mp3 file and store in inputstream: if(!DocumentsContract.isDocumentUri(this, data.getData())) throw new RuntimeException("Not a documentsContract document"); try { InputStream is = getContentResolver().openInputStream(data.getData()); new Main4Activity.httpAsyncTask417().execute(); } catch (FileNotFoundException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } The part of sending the POST request: public class httpAsyncTask417 extends AsyncTask&lt;String, Void, Void&gt; { @Override protected Void doInBackground(String... strings) { try { String url="http://172.17.57.132/post_songs"; URL obj=new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); //add reuqest header con.setRequestMethod("POST"); String urlParameters = "content="; // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); Log.v("HTTPDelete_Check3", "Get returned: " + responseCode); BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); //print result }catch(java.io.IOException ex) { } return null; } @Override protected void onPostExecute(Void v) { } }
score: 1
tagged with: java
upvote count: 1
type: Question
tagged with: flask
has title: How to send an InputStream using POST request
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/88875684
type: QuestionComment
type: Comment
has text: next to the .py is the image?
comment on: http://stackoverflow.com/q/50938738
score: 0

http://stackoverflow.com/comment/88835841
comment on: http://stackoverflow.com/q/50917432
score: 0
has text: It prints the following....('s', '7')
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88891426
has text: Are you looking for `sys.argv`? It contains the list of the command line arguments.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50944302

http://stackoverflow.com/q/50879053
has answer: http://stackoverflow.com/a/50886760
upvote count: 2
has title: Check if node is an operation or a tensor in Tensorflow Graph
tagged with: python
has answer: http://stackoverflow.com/a/50879201
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50886760
tagged with: tensorflow
type: Question
linked to: http://stackoverflow.com/q/42168977
score: 2
has body: Using names = [n.name for n in graph.as_graph_def().node] I can get all the node names in the graph. For instance, say this prints: ['model/classifier/dense/kernel/Initializer/random_uniform/shape', 'model/classifier/dense/kernel/Initializer/random_uniform/min', 'model/classifier/dense/kernel/Initializer/random_uniform/max', 'model/classifier/dense/kernel/Initializer/random_uniform/RandomUniform', 'model/classifier/dense/kernel/Initializer/random_uniform/sub', 'model/classifier/dense/kernel/Initializer/random_uniform/mul', 'model/classifier/dense/kernel/Initializer/random_uniform', 'model/classifier/dense/kernel', 'model/classifier/dense/kernel/Assign', 'model/classifier/dense/kernel/read', 'model/classifier/dense/bias/Initializer/zeros/shape_as_tensor', 'model/classifier/dense/bias/Initializer/zeros/Const', 'model/classifier/dense/bias/Initializer/zeros', 'model/classifier/dense/bias', 'model/classifier/dense/bias/Assign', 'model/classifier/dense/bias/read', 'model/classifier/dense/MatMul', 'model/classifier/dense/BiasAdd'] How can I select only the operations or only the tensors? I'm aware of the following workarounds, which will work in specific situations but are not general enough and would not scale to a large graph: string manipulations from the above names for instance to get model/classifier/dense/kernel: tensor = [graph.get_tensor_by_name(n + ":0") for n in names if 'classifier' in n and 'kernel' in name and not n.split('kernel')[-1] ][0] As you can imagine this may be very error prone and is very tensor specific try/except I could get the tensors which are outputs of these operation with: tensors = [] for name in names: try: tensors.append(graph.get_tensor_by_name(name + ":0")) except KeyError: pass But again this is but a workaround and does not solve the selection problem: what if I just want the kernel Tensor?
downvote count: 0
possible better answer: http://stackoverflow.com/a/50883176
has answer: http://stackoverflow.com/a/50883176
answer count: 3
favorite count: 0

http://stackoverflow.com/a/50953524
has comment: http://stackoverflow.com/comment/88904814
answers question: http://stackoverflow.com/q/50953470
has body: my_data="BEAR" for i in range(len(my_data)): print(my_data[:len(my_data)-i]) #trick is here Output: BEAR BEA BE B
accepted answer of: http://stackoverflow.com/q/50953470
upvote count: 1
type: AcceptedAnswer
downvote count: 1
score: 0
has comment: http://stackoverflow.com/comment/88904782
type: Answer

http://stackoverflow.com/a/51004323
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51004201
has body: expr executes expressions: expr x"$TMFR" : x"[^0-9]*\([0-9]*\)" matches the string x followed by the value of $TMFR against the regulare expression x[^0-9]*([0-9]*), printing out the part between the parentheses (which are escaped to prevent them from being interpreted by bash instead). expr 0$num \* $factor multiplies the number $num by $factor, defaulting to 0. So it basically finds the first numeric value in the string $TMFR and multiplies that number by the factor already calculated. If you always have a number followed by a duration string, I'd just use a regular expression to extract both in one go, and use a dictionary to map the duration string to a factor: import re durations = { 'mo': 2592000, 'w': 604800, 'd': 86400, 'h': 3600, 'm': 60, 's': 1 } # match on digits followed directly by one of the duration strings, ignoring case # the duration strings are sorted by descending length to ensure shorter # sub-patterns are considered after the longer options (compare 'mo' and m') pattern = re.compile(r'(\d+)({})\b'.format( '|'.join(sorted(durations, key=len, reverse=True))), flags=re.IGNORECASE) def duration_from_string(s): return sum( int(m.group(1)) * durations[m.group(2)] for m in pattern.finditer(s)) I've assumed you need to support compound durations that are space separated, so 1mo 2w 3d is 4060800 seconds (1 month, 2 weeks and 3 days): &gt;&gt;&gt; duration_from_string('foo bar spam 1mo 2w 3d') 4060800 If the format should work without spaces too, drop the \b anchor from the regex pattern.
upvote count: 1
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/51004201

http://stackoverflow.com/a/50989437
has comment: http://stackoverflow.com/comment/88974202
type: Answer
score: 3
downvote count: 0
has body: The date and time "created_at" is given via the API is UTC. See the reference at Tweet Object. Attribute:createad_at, type:String, description: UTC time when this Tweet was created When you are logged into the official web site, tweets date are converted to the time zone you have set into your profile settings.
upvote count: 3
accepted answer of: http://stackoverflow.com/q/50988451
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50988451
has comment: http://stackoverflow.com/comment/88973582

http://stackoverflow.com/q/50904709
has comment: http://stackoverflow.com/comment/88810974
upvote count: 1
tagged with: scrapy
type: Question
has body: ########### This article is posted before I found it using scrapy + splash is not best way because I checked rendered pages (http://localhost:8050/render.html?url=xxx) has no data I want. That's why I try another way to make use of selenium or something. Thank you!! 【What I Want to Know: How do I should modify code of yield SplashRequest(url, callback=self.parse, args = {"wait": 5}, endpoint = "render.html")】 I don't have no idea that I should change code in order to pass URLs from A's method to B's in case of using scrapy + splash. In my opinion, the corrected places are, yield SplashRequest(url, callback=self.parse, args = {"wait": 5}, endpoint = "render.html") of start_requests method(#1). There are 3 reasons. 1st reason is, logging.info(#2) before of "yield SplashRequest(url, callback=self.parse, args = {"wait": 5}, endpoint = "render.html")" gave me correct feedback. 2nd reason is, I set up scrapy + splash, reading Scrapy+Splash's README of as reference. Scrapy+Splash for JavaScript integration https://github.com/scrapy-plugins/scrapy-splash 3rd reason is, logging method(#3) gave me NO information. Here is my code. # -*- coding: utf-8 -*- import scrapy from scrapy_splash import SplashRequest from bnb_sentiment.items import BnbItem from scrapy_splash import SplashRequest import re import logging logging.basicConfig(level=logging.INFO) # __name__ is name of a method logger = logging.getLogger(__name__) class BnbPriceTestSpider(scrapy.Spider): name = 'bnb_price_test' start_urls = [ # Tokyo--Japan 'https://www.airbnb.com/s/Tokyo--Japan/homes?refinement_paths%5B%5D=%2Fhomes&amp;allow_override%5B%5D=&amp;checkin=2018-07-07&amp;checkout=2018-07-08&amp;locale=en&amp;min_beds=0&amp;price_max=20000&amp;price_min=10000&amp;query=Tokyo%2C%20Japan&amp;place_id=ChIJ51cu8IcbXWARiRtXIothAS4&amp;s_tag=Mz88jJs1', ] def start_requests(self): for url in self.start_urls: logger.info(url) #2 yield SplashRequest(url, callback=self.parse, args = {"wait": 5}, endpoint = "render.html") …
downvote count: 0
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88852036
tagged with: scrapy-splash
tagged with: python
has comment: http://stackoverflow.com/comment/88810320
has title: How do I pass URLs from A's method to B's by changing code of yield SplashRequest?? (Scrapy + Splash with Python & Dcoker)
answer count: 0
score: 1

telegram
tags question: http://stackoverflow.com/q/50877819
tags question: http://stackoverflow.com/q/50886560
tag name: telegram
type: Tag
tags question: http://stackoverflow.com/q/50977420
tags question: http://stackoverflow.com/q/50866239
tags question: http://stackoverflow.com/q/50885784
tags question: http://stackoverflow.com/q/50960420
tags question: http://stackoverflow.com/q/50968163

http://stackoverflow.com/q/50888820
answer count: 0
type: UnansweredQuestion
type: Question
has title: Let Python detect if a site is active on the PC
upvote count: 2
linked to: http://stackoverflow.com/q/15906308
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/88778880
tagged with: notifications
tagged with: python
has comment: http://stackoverflow.com/comment/88779793
score: 2
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88779035
has body: Okay so I am making a script that gives you a notification in windows 10 IF you access a certain site. So an example: You go to the site like: twitter.com, then the Python script will detect that and it will run the other script (notification script). This is the notification script: import time from win10toast import ToastNotifier toaster = ToastNotifier() toaster.show_toast("Distracting", "You are now going on a disstracting site.", icon_path=None, duration=5, threaded=True)

http://stackoverflow.com/q/50935514
type: AnsweredQuestion
has body: I use Python Flask and Postgres to insert one apple into the database: cursor.execute(""" LOCK TABLE apples IN SHARE ROW EXCLUSIVE MODE; INSERT INTO apples(apple) SELECT %s WHERE NOT EXISTS ( SELECT * FROM apples WHERE apple = %s ); """, apple)) But I get the following error: TypeError: not all arguments converted during string formatting Where is the mistake? EDIT: With (apple, ) I get the following error: IndexError: tuple index out of range (also with [apple]). Thanks
tagged with: flask-sqlalchemy
accepted answer: http://stackoverflow.com/a/50935565
tagged with: postgresql
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/88883180
score: 0
has comment: http://stackoverflow.com/comment/88869640
answer count: 1
has answer: http://stackoverflow.com/a/50935565
linked to: http://stackoverflow.com/q/16856647
has title: Postgresql and Python - TypeError: not all arguments converted during string formatting
tagged with: flask
duplicate of: http://stackoverflow.com/q/16856647

python-3.x
tags question: http://stackoverflow.com/q/50885241
tags question: http://stackoverflow.com/q/50925906
tags question: http://stackoverflow.com/q/50919800
tags question: http://stackoverflow.com/q/50900340
tags question: http://stackoverflow.com/q/50969917
tags question: http://stackoverflow.com/q/50955336
tags question: http://stackoverflow.com/q/50999263
tags question: http://stackoverflow.com/q/50871254
tags question: http://stackoverflow.com/q/50894676
tags question: http://stackoverflow.com/q/50975701
tags question: http://stackoverflow.com/q/50997532
tags question: http://stackoverflow.com/q/50957382
tags question: http://stackoverflow.com/q/50955355
tags question: http://stackoverflow.com/q/50873875
tags question: http://stackoverflow.com/q/50869718
tags question: http://stackoverflow.com/q/50948727
tags question: http://stackoverflow.com/q/50941472
tags question: http://stackoverflow.com/q/50894096
tags question: http://stackoverflow.com/q/50888617
tags question: http://stackoverflow.com/q/50978660
tags question: http://stackoverflow.com/q/50885312
tags question: http://stackoverflow.com/q/50951335
tags question: http://stackoverflow.com/q/50875028
tags question: http://stackoverflow.com/q/50867251
tags question: http://stackoverflow.com/q/50968065
tags question: http://stackoverflow.com/q/50951274
tags question: http://stackoverflow.com/q/50925390
tags question: http://stackoverflow.com/q/50891316
tags question: http://stackoverflow.com/q/50883081
tags question: http://stackoverflow.com/q/50991142
tags question: http://stackoverflow.com/q/50970824
tags question: http://stackoverflow.com/q/50996913
tags question: http://stackoverflow.com/q/50965902
tags question: http://stackoverflow.com/q/50995692
tags question: http://stackoverflow.com/q/50915341
tags question: http://stackoverflow.com/q/50875037
tags question: http://stackoverflow.com/q/50896344
tags question: http://stackoverflow.com/q/50923500
tags question: http://stackoverflow.com/q/50919285
tags question: http://stackoverflow.com/q/50874618
tags question: http://stackoverflow.com/q/50892535
tags question: http://stackoverflow.com/q/50920242
tags question: http://stackoverflow.com/q/50892996
tags question: http://stackoverflow.com/q/50935328
tags question: http://stackoverflow.com/q/50886506
tags question: http://stackoverflow.com/q/50874514
tags question: http://stackoverflow.com/q/50901241
tags question: http://stackoverflow.com/q/50977380
tags question: http://stackoverflow.com/q/51006161
tags question: http://stackoverflow.com/q/50878091
tags question: http://stackoverflow.com/q/51010315
tags question: http://stackoverflow.com/q/51008798
tags question: http://stackoverflow.com/q/50900249
tags question: http://stackoverflow.com/q/50872410
tags question: http://stackoverflow.com/q/51002703
tags question: http://stackoverflow.com/q/50863799
tags question: http://stackoverflow.com/q/50932470
tags question: http://stackoverflow.com/q/50985232
tags question: http://stackoverflow.com/q/50934201
tags question: http://stackoverflow.com/q/50877184
tags question: http://stackoverflow.com/q/50866336
tags question: http://stackoverflow.com/q/50971871
tags question: http://stackoverflow.com/q/50977756
tags question: http://stackoverflow.com/q/50986472
tags question: http://stackoverflow.com/q/50862238
tags question: http://stackoverflow.com/q/51010322
tags question: http://stackoverflow.com/q/50944627
tags question: http://stackoverflow.com/q/50946713
tags question: http://stackoverflow.com/q/50962716
tags question: http://stackoverflow.com/q/50863093
tags question: http://stackoverflow.com/q/50933000
tags question: http://stackoverflow.com/q/50915226
tags question: http://stackoverflow.com/q/50951790
tags question: http://stackoverflow.com/q/50891021
tags question: http://stackoverflow.com/q/50868834
tags question: http://stackoverflow.com/q/50930527
tags question: http://stackoverflow.com/q/50996134
tags question: http://stackoverflow.com/q/50924723
tags question: http://stackoverflow.com/q/50938738
tags question: http://stackoverflow.com/q/50956810

http://stackoverflow.com/q/50928663
tagged with: python
has title: Python Cocos2d can't find resource image after resizing it
type: Question
linked to: http://stackoverflow.com/q/6541494
has body: I'm trying to resize an image in Python and then load a cocos2d sprite with the resized image. However, trying to initialize a cocos2d sprite results in an error that the resource can't be found. Example code to reproduce the problem: from pathlib import Path import cocos from PIL import Image im = Image.open("in.jpg") im.thumbnail((600, 900)) im.save("out.jpg", "JPEG") im.close() file = Path("out.jpg") if file.is_file(): print("File exists") sprite = cocos.sprite.Sprite("out.jpg") This results in the error pyglet.resource.ResourceNotFoundException: Resource "out.jpg" was not found on the path. Ensure that the filename has the correct captialisation. However, the output is: File exists Running it a second time doesn't give errors, since out.jpg has been created in the previous run. Deleting out.jpg and running it again produces the error. Adding an im.close() didn't solve the problem. The OS is Windows 10 with Python version 3.6.4.
has answer: http://stackoverflow.com/a/51086301
score: 0
answer count: 1
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89158082
tagged with: cocos2d-python
type: UnansweredQuestion

http://stackoverflow.com/q/50892346
linked to: http://stackoverflow.com/q/12079607
has body: I have installed pandas with apt-get package manager via code sudo apt-get install python3-pandas Because pip install pandas hungs long time. I need to use pandas inside a virtual environment. How can i use a apt-get installed Python package inside virtual environment?
has title: Using Apt-Get Python Packages Inside Virtual Environment
type: UnansweredQuestion
tagged with: virtualenv
has comment: http://stackoverflow.com/comment/88785443
tagged with: linux
tagged with: pandas
answer count: 1
tagged with: python
linked to: http://stackoverflow.com/q/11441546
tagged with: python-3.x
type: Question
score: 0
has answer: http://stackoverflow.com/a/50892767
has comment: http://stackoverflow.com/comment/88785953
has comment: http://stackoverflow.com/comment/88792697

http://stackoverflow.com/comment/88878354
has text: You are a life saver. thank you very much. I ran your code and just two changes to make it work => row, col = int(cellname[1:]) - 1 , ord(cellname[0].upper()) - ord('A') .
score: 0
comment on: http://stackoverflow.com/q/50917315
type: Comment
type: QuestionComment

object-detection
tags question: http://stackoverflow.com/q/50862129
tag name: object-detection
tags question: http://stackoverflow.com/q/50882259
tags question: http://stackoverflow.com/q/50977740
tags question: http://stackoverflow.com/q/50996511
tags question: http://stackoverflow.com/q/50955720
type: Tag
tags question: http://stackoverflow.com/q/50923920
tags question: http://stackoverflow.com/q/50861066

http://stackoverflow.com/comment/88903453
type: QuestionComment
comment on: http://stackoverflow.com/q/50925618
score: 0
type: Comment
has text: Notice that in both questions `ipython`, not `python`, prompt is used: "Note: Importing it via `from IPython import get_ipython` in ordinary shell `python` will *not* work as you really need `ipython` running."

http://stackoverflow.com/comment/88807075
comment on: http://stackoverflow.com/q/50903622
type: Comment
type: QuestionComment
score: 3
has text: Good example no how to ask a question. Upvoted!

http://stackoverflow.com/comment/88933331
comment on: http://stackoverflow.com/a/50963637
score: 0
type: AnswerComment
type: Comment
has text: I got around the pickling issue by writing a function like this `def help_func(in_val): in_val[1].process_datapoint(in_val[2], in_val[0])`. However, when I run this on my data, I would expect that there are only as many instances as `groupid`, however for some reason it seems to make more instances. Do you have any pointers here?

http://stackoverflow.com/q/50929883
accepted answer: http://stackoverflow.com/a/50931296
has answer: http://stackoverflow.com/a/50930742
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/50930742
has body: I am confused. I've setup Jenkins. I've setup a Master and a Slave node. I have a Jenkinsbuild file in my git repo, which is executed by the pipeline job. And in the Jenkinsbuild file I have lines like this: sh "docker build -t cd-demo ." Where is this executed? Does this happen on the master or on the slave? If I write a Python script, and I want to call it as a shell script, do I need to put the Python script on the master or on the slave? Even more important: if I want to push a built Docker image to ECS, which machine needs to have AWS credentials, the master or the slave?
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50931296
tagged with: jenkins
type: Question
has title: When I use a Jenkinsbuild file in Jenkins to run a shell script, does it execute on master or slave?

http://stackoverflow.com/comment/88950846
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50976749
has text: @ykaner I have tried till 20000 steps and batch_sizes of 32, 64 and 128 also with no luck.
score: 0

http://stackoverflow.com/a/50886912
has comment: http://stackoverflow.com/comment/88775307
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50886683
type: Answer
has body: Golden rule when it comes to HTTP requests (API or not and whatever the expected response's content type) is that things can go wrong in many ways and at any time and that they WILL go wrong one day or another in the most unexpected way, so if you hope to have a decenty robust client program, you have to be prepared to handle just any possible outcome. Most often, this actually means wrapping requests calls in try/except handlers plus testing the response's status code, content-type and effective content (instead of blindly assuming you got what you asked for), and depending on the exception / unexpected response value decide whether it's worth retrying the request a couple times (with increasing delays between the retries) before giving up (some error conditions can be temporary) or just give up immediatly. In all cases, you also want to make sure you let the user know what went wrong, with as much informations as possible (request, response if you got one, exception and full traceback else) when you decide to give up.
upvote count: 3
score: 3
accepted answer of: http://stackoverflow.com/q/50886683

http://stackoverflow.com/comment/88819095
type: QuestionComment
has text: What was the last line the process "hang" after? You could try to add print statements after each individual line, then try to reproduce the problem. (Since reproducing the problem may take hours, please don't expect us to.)
comment on: http://stackoverflow.com/q/50909361
score: 0
type: Comment

http://stackoverflow.com/q/50973015
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/50975688
has comment: http://stackoverflow.com/comment/88943678
favorite count: 0
has comment: http://stackoverflow.com/comment/88951176
tagged with: tkinter
linked to: http://stackoverflow.com/q/189725
has comment: http://stackoverflow.com/comment/88943422
tagged with: python
has comment: http://stackoverflow.com/comment/88946552
has body: The problem is that I made a short algorithm that finds it's way through a maze and marks all squares that it has visited in blue. The core program works fine but the problem is that the GUI only displays the maze with it's visited squares after the whole process is done. This would not normally be a problem but I need to be able to visibly see the algorithm traverse the maze as it goes. The problem is that when I call the UpdateMaze function every iteration of the searching algorithm, it doesn't appear to take affect until the whole traversal is finished. Wall images are just a black square GIF Space images are just a white square GIF Edge images are just a Red square GIF Finish is a Green square GIF Visited is a blue square GIF import tkinter as tk from tkinter import * import time class MazeGUI(): def __init__(self): self.maze =[ [4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4], [4, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 1, 4], [4, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 4], [4, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 4], [4, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 1, 4], [4, 0, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 4], [4, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 4], [4, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 4], [4, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 4], [4, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0, 4], [4, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 4], [4, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 4], [4, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 4], [4, 0, 1, 2, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 4], [4, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 4], [4, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 4], [4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4] ] self.wall = tk.PhotoImage(file = "MazePiece_Wall.gif") self.space = tk.PhotoImage(file = "MazePiece_Space.gif") self.edge = tk.PhotoImage(file = "MazePiece_Outer.gif") self.visited = tk.PhotoImage(file = "MazePiece_Visited.gif") self.finish = tk.PhotoIm…
has comment: http://stackoverflow.com/comment/88945088
type: AnsweredQuestion
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/88943423
type: Question
accepted answer: http://stackoverflow.com/a/50975688
has title: How to update tkinter GUI every move?

http://stackoverflow.com/a/50881461
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50881441
type: Answer
has body: You can rename your sql table and then delete the model and then rename back.
score: 0
accepted answer of: http://stackoverflow.com/q/50881441

http://stackoverflow.com/a/50972468
type: Answer
has comment: http://stackoverflow.com/comment/88986632
score: 2
has comment: http://stackoverflow.com/comment/88988067
has comment: http://stackoverflow.com/comment/88988100
downvote count: 0
answers question: http://stackoverflow.com/q/50916340
has comment: http://stackoverflow.com/comment/88945306
has body: It's hard to know without looking at all the code and knowing the class hierarchy, but at the moment I'd hazard a guess that your code is slow in the OGM bit because every relationship is created in its own transaction. So you're doing a huge number of transactions for a larger graph which is going to slow things down. I'd suggest for an initial import where you're creating every class/object, rather than just adding a new one or editing the relationships for one class, that you use your class inspectors to simply create a graph representation of the data, and then use Cypher to construct it in a lot fewer transactions in Neo4J. Using some basic topological graph theory you could then optimise it by reducing the number of lookups you need to do, too. You can create a NetworkX MultiDiGraph in your python code to model the structure of your classes. From there on in there are a few different strategies to put the data into Neo4J - I also just found this but have no idea about whether it works or how efficient it is. The most efficient way to query to import your graph will depend on the topology of the graph, and whether it is cyclical or not. Some options are below. 1. Create the Graph in Two Sets of Queries Run one query for every node label to create every node, and then another to create every edge between every combination of node labels (the efficiency of this will depend on how many different node labels you're using). 2. Starting from the topologically highest or lowest point in the graph, create the graph as a series of paths If you have lots of different edge labels and node labels, this might involve writing a lot of cypher logic combining UNWIND and FOREACH (CASE r.label = 'SomeLabel' THEN [1] ELSE [] | CREATE (n:SomeLabel {node_unique_id: x})-&gt;, but if the graph is very hierarchical you could also use python to keep track of which nodes have all their lower nodes and relationships created already and then use that knowledge to limit the size of paths t…
upvote count: 2

http://stackoverflow.com/comment/88999001
comment on: http://stackoverflow.com/a/51002141
type: AnswerComment
score: 0
type: Comment
has text: @Fidel_Willis Are you still receiving `wrong permissions` error? Note, however, that `'/anaconda2/lib/python2.7/site-packages/selenium/webdriver/chrome/chromedriver.exe'` does not look like the full path. Instead, locate the executable, and drag-and-drop the file into your command-line/terminal to get the full path. Then, copy the result in your terminal and pass it to the class.

http://stackoverflow.com/comment/88839180
comment on: http://stackoverflow.com/a/50918931
score: 0
type: AnswerComment
type: Comment
has text: @YuchenHuang No problem! Glad to help! Happy coding and learning!

http://stackoverflow.com/comment/88891713
comment on: http://stackoverflow.com/q/50882504
has text: `rm -rf <PREFIX>/lib/python*/*-packages/imageio*` usually works
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/50909741
type: Answer
downvote count: 0
has body: Use df.loc: df.loc[df["date"] == "2005-12-22", "AIR_TEMP"]
score: 3
answers question: http://stackoverflow.com/q/50909666
upvote count: 3

http://stackoverflow.com/a/50960243
answers question: http://stackoverflow.com/q/50960165
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/88956477
has body: You should not be using optparse for new projects. According to the docs: Deprecated since version 2.7: The optparse module is deprecated and will not be developed further; development will continue with the argparse module. The functionality you are looking for is built into argparse: import argparse parser = argparse.ArgumentParser('Test program') parser.add_argument('-a', action='store_true') parser.add_argument('-v', action='store_true') parser.add_argument('-f', nargs='+') args = parser.parse_args() print(args) This yields: $ python parser.py -av -f f1.txt f2.txt f3.txt Namespace(a=True, f=['f1.txt', 'f2.txt', 'f3.txt'], v=True)
has comment: http://stackoverflow.com/comment/88959393
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/50960165
type: AcceptedAnswer

http://stackoverflow.com/q/50994140
linked to: http://stackoverflow.com/q/44213781
has comment: http://stackoverflow.com/comment/88984074
has title: Problems while plotting label vs datetime in a pandas column?
tagged with: seaborn
tagged with: python
duplicate of: http://stackoverflow.com/q/44213781
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50998639
has body: I have the following pandas dataframe, which consist of datetime timestamps and user ids: id datetime 130 2018-05-17 19:46:18 133 2018-05-17 20:59:57 131 2018-05-17 21:54:01 142 2018-05-17 22:49:07 114 2018-05-17 23:02:34 136 2018-05-18 06:06:48 324 2018-05-18 12:21:38 180 2018-05-18 12:49:33 120 2018-05-18 14:03:58 120 2018-05-18 15:28:36 How can I plot on the y axis the id and on the x axis day or minutes? I tried to: plt.plot(df3['datatime'], df3['id'], '|') plt.xticks(rotation='vertical') However, I have two problems, my dataframe is quite large and I have multiple ids, the second problem is that I wasn't able to arrange each label on the y axis and plot it against its datime value in the x axis. Any idea of how to do something like this: The whole objective of this plot is to visualize the logins per time of that specific user.
has comment: http://stackoverflow.com/comment/88984368
type: Question
tagged with: matplotlib
accepted answer: http://stackoverflow.com/a/50998639
score: 0
tagged with: pandas
answer count: 1
tagged with: python-3.x

http://stackoverflow.com/a/50969973
downvote count: 0
has body: You have a couple of options. Option 1: Server side process Each django app can register code to call when it is starting up via the AppConfig's ready. If you'd like to start some backend polling/computing thread and module, this is where you would do it. Keep in mind that this gets complicated very quickly considering (a) it's multi-process programming and (b) the many ways to handle WSGI requests (single threaded, gevent, multi-process, multi-threaded) and if you're in a distributed environment. Does consistency between hosts, process, thread, etc matter? Option 2: Tasks As another answer indicated, this is where async workers shine. Things like celery were designed for this and integrate nicely. In my opinion, this is the correct way to engineer the problem. I know this answer is kind of regurgitating the one from Chetan, but I hope it adds a little more clarity.
answers question: http://stackoverflow.com/q/50917614
type: AcceptedAnswer
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50917614
score: 1

http://stackoverflow.com/q/50868980
downvote count: 0
accepted answer: http://stackoverflow.com/a/50869782
tagged with: bulkinsert
has comment: http://stackoverflow.com/comment/88742185
tagged with: python
favorite count: 0
tagged with: django
has answer: http://stackoverflow.com/a/50869782
type: AnsweredQuestion
score: 3
upvote count: 3
type: Question
has title: Get key of IntegrityError in django bulk_create
has body: I am trying to do a Model.objects.bulk_create(bulk_objects) in django, I am expecting IntegrityError's at times but I would like get the objects details that has caused the exception. try: # bulk_objects contains ~70k items Auction.objects.bulk_create(bulk_objects) except IntegrityError as e: print(str(e.__cause__)) msg = str(e.__cause__) match = re.search('(?!\()\d+(?=\))', msg) print(match.group(0)) # prints 123865 in this case this throws the exception insert or update on table "auction_table" violates foreign key constraint"my_constraint" DETAIL: Key (item_id)=(123865) is not present in table "item_table". This is fine and I expect this, I am wanting to get the item_id that has caused the exception, in this case the item_id of 123865. Is there a way of doing this without doing some regex on the string or iterating over the bulk_objects? Was just hoping to get it directly from the error, otherwise I will continue with the regex approach
answer count: 1

http://stackoverflow.com/comment/88740074
has text: I didn't get you.
score: 0
comment on: http://stackoverflow.com/q/50869177
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50934049
type: Answer
has comment: http://stackoverflow.com/comment/88879778
answers question: http://stackoverflow.com/q/50933912
has body: You can use re: import re def highlight(text, keywords, _class='highlight'): return re.sub('|'.join(keywords), lambda x:f"{x.group()}", text) s = """ Alfa Romeo Mercedes Volkswagen """ print(highlight(s, ['Alfa Romeo', 'Mercedes', 'Volkswagen'])) Output: Alfa Romeo Mercedes Volkswagen
score: 0

http://stackoverflow.com/q/50993436
has comment: http://stackoverflow.com/comment/88981804
has body: I've been trying to import pandas into my python file but every time i run it i get the following error: Traceback (most recent call last): File "C:\Python36\lib\site-packages\pandas\compat\__init__.py", line 49, in &lt;module&gt; import __builtin__ as builtins ModuleNotFoundError: No module named '__builtin__' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "email.py", line 1, in &lt;module&gt; import pandas as pd File "C:\Python36\lib\site-packages\pandas\__init__.py", line 23, in &lt;module&gt; from pandas.compat.numpy import * File "C:\Python36\lib\site-packages\pandas\compat\__init__.py", line 62, in &lt;module&gt; import http.client as httplib File "C:\Python36\lib\http\client.py", line 71, in &lt;module&gt; import email.parser File "C:\Users\xx\Desktop\Projects\email_sender\email.py", line 3, in &lt;module&gt; df = pd.read_excel("emails.xlsx", 'Sheet1', index_col=None, na_values=['NA']) AttributeError: module 'pandas' has no attribute 'read_excel' this is what the import code block looks like in the the /pandas/__init__.py file: try: import __builtin__ as builtins # not writeable when instantiated with string, doesn't handle unicode well from cStringIO import StringIO as cStringIO # always writeable from StringIO import StringIO BytesIO = StringIO import cPickle import httplib except ImportError: import builtins from io import StringIO, BytesIO cStringIO = StringIO import pickle as cPickle import http.client as httplib I found out that __builtin__ was renamed to builtins in python3, after fixing that line and trying to import I get the error from the StringIO import as well, since that was deleted from python3 and uses a different syntax to call that module. My system only has python3 installed. I have upgraded all pandas dependencies as well and they can be imported as normal. I've also uninstalled pandas and reinstalled again but the same thing happens. Pandas version is 0.23.1 Python version is 3.…
score: 0
tagged with: importerror
tagged with: pandas
has comment: http://stackoverflow.com/comment/88981513
tagged with: python
has comment: http://stackoverflow.com/comment/88981646
duplicate of: http://stackoverflow.com/q/36250353
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88981671
has comment: http://stackoverflow.com/comment/88981559
has comment: http://stackoverflow.com/comment/88981579
type: Question
has title: Importing pandas seems to be using deprecated python modules
has comment: http://stackoverflow.com/comment/88981586
has comment: http://stackoverflow.com/comment/88981705

dataset
tags question: http://stackoverflow.com/q/50992080
tags question: http://stackoverflow.com/q/50868589
type: Tag
tags question: http://stackoverflow.com/q/50986886
tag name: dataset

http://stackoverflow.com/q/50861802
has title: Pandas Max Min between index range
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/50862242
tagged with: dataframe
tagged with: pandas
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50862242
tagged with: python
score: 2
type: AnsweredQuestion
has body: I have the following time series pandas dataframe index | Date | Time | open | high | low | close | volume 293 2018-06-14 14:55 1832.15 1833.40 1831.90 1833.35 37947 294 2018-06-14 15:00 1833.40 1834.95 1833.30 1834.90 106271 295 2018-06-14 15:05 1834.95 1835.05 1834.40 1834.85 102107 296 2018-06-14 15:10 1834.80 1834.85 1832.95 1833.80 95931 297 2018-06-14 15:15 1833.75 1834.85 1833.05 1834.85 124639 298 2018-06-14 15:20 1834.85 1834.85 1831.55 1832.50 121206 I need to fetch index and row data where Date='d1' and Time='t1' eg. fetch the row values where data=2018-06-14 and time=15:05 I need to find max(high) between t1 and t2 where date='d1' (t2>t1) e.g find max(high) between Time 15:00 and 15:15 where date = '2018-06-14'
upvote count: 3

http://stackoverflow.com/comment/88837503
score: 1
comment on: http://stackoverflow.com/a/50918470
type: AnswerComment
type: Comment
has text: I’ve reported the import bug

http://stackoverflow.com/q/50882266
has answer: http://stackoverflow.com/a/50882370
has comment: http://stackoverflow.com/comment/117004649
type: Question
has answer: http://stackoverflow.com/a/52953129
has answer: http://stackoverflow.com/a/65133953
downvote count: 0
linked to: http://stackoverflow.com/q/66744219
favorite count: 0
has body: Using the Ubuntu bash terminal on Windows 10 (installation instructions here), I installed Anaconda and have been using Jupyter notebooks without a problem. Unfortunately, Jupyter is unable to locate a runnable browser from within the subsystem, so I have to copy and paste the link it outputs in the terminal - but that is workable. The main issue comes when I try to open multiple notebooks. Normally, Jupyter would detect that a port (8888 by default) is already being used and make a new one, but it seems to fail to detect this so that when I use the link it generates, I end up looking at the first notebook I opened instead of the new one. Any idea what the issue might be? And, if not, how I can manually get around this?
tagged with: python
has comment: http://stackoverflow.com/comment/88766803
has comment: http://stackoverflow.com/comment/88795118
answer count: 4
tagged with: windows-subsystem-for-linux
tagged with: jupyter-notebook
possible better answer: http://stackoverflow.com/a/52953129
upvote count: 21
has answer: http://stackoverflow.com/a/54074590
accepted answer: http://stackoverflow.com/a/50882370
has comment: http://stackoverflow.com/comment/88768541
type: AnsweredQuestion
score: 21
has title: Using Jupyter with Windows Subsystem for Linux

http://stackoverflow.com/q/50955501
has comment: http://stackoverflow.com/comment/88913452
has title: PyQT/Pyside Opengl widget overlay
favorite count: 0
has comment: http://stackoverflow.com/comment/88912611
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88913285
tagged with: python
has answer: http://stackoverflow.com/a/50956056
tagged with: opengl
score: 1
tagged with: pyside2
upvote count: 1
type: Question
tagged with: pyside
has answer: http://stackoverflow.com/a/75112657
has body: Do PyQT or Pyside support OpenGL button/general widget overlays (I'm looking for something similar to this screenshot of FlashPrint ? I'm having trouble even googling this as I don't know what to call it. Is overlay the correct term here? Also, if neither PyQT or Pyside support this are there any Python based GUI's that allow for this?
has answer: http://stackoverflow.com/a/63477470
linked to: http://stackoverflow.com/q/19199863
answer count: 3
tagged with: pyqt
has comment: http://stackoverflow.com/comment/88913306
has comment: http://stackoverflow.com/comment/88913472
downvote count: 0

http://stackoverflow.com/comment/88803448
type: Comment
score: 2
type: AnswerComment
has text: I think you have solved more than you were asked to: you actually gave a meaningful formulation of "chess sorting" for the OP. Kudos!
comment on: http://stackoverflow.com/a/50901565

http://stackoverflow.com/a/50952248
accepted answer of: http://stackoverflow.com/q/50951803
type: Answer
has body: You can process the nested structure with a stack: Start with the outermost list, reversed, as the stack, together with an empty tuple for each, to track the organisation path. In while stack: loop, take the top element from the stack. Do what you need to do with that organisation, like recording the name. Produce a row from the organisation path with the current organisation name added. Add all the elements in the Children key to the stack, together with the organisation path of the parent organisation. Loop until the stack is done. The reversals are needed because taking elements from a stack gives them in reverse order. You still want to use a stack for this job (as opposed to a queue) because we want to output the information depth-first. This would look like this: def flatten_orgs(orgs): stack = [(o, ()) for o in reversed(orgs)] # organisation plus path while stack: org, path = stack.pop() # top element path += (org['Name'],) # update path, adding the current name yield path # give this path to the caller # add all children to the stack, with the current path stack += ((o, path) for o in reversed(org['Children'])) You can then loop over the above function to get all the paths: &gt;&gt;&gt; for path in flatten_orgs(orgs_json): ... print(*path, sep='\t') ... Org1 Org1 Org2 Org1 Org3 Org1 Org3 Org4 Org1 Org5 Org1 Org5 Org6 Org1 Org5 Org6 Org7
score: 0
answers question: http://stackoverflow.com/q/50951803
type: AcceptedAnswer

http://stackoverflow.com/a/65191743
type: Answer
score: 1
upvote count: 1
has body: I had a similar error, and in my case, it was because of cross-packages imports, which for me worked differently locally vs on the cloud. For example, I had a structure similar to the one below: src: package1: - file_a.py - ClassA package2: - file_b.py - ClassB ...and I had to import Class_A into Class_B. Locally the imports in classB were looking something like this: from src.package1.file_a import ClassA in my case after deployment to the cloud, it did not see anymore the 'src', as there the root package had no name. the workaround was to wrap ClassB imports into try - except. In the except block I used same imports statements without 'src.' part, like this: try: # works locally from src.package1.file_a import ClassA except: # works on the cloud from package1.file_a import ClassA
downvote count: 0
answers question: http://stackoverflow.com/q/50975869

http://stackoverflow.com/q/50995692
tagged with: django-1.11
tagged with: python
has body: I have a person model. Each person has it's children. Children may have children as well. I want to get all children (recursively) in one query. How can I do that? class Person(models.Model): name = models.CharField(max_length=40) parent = models.ForeignKey('self', null=True, blank=True, related_name='children') def __str__(self): return self.name def add_person(request): if(request.method == 'POST'): name = request.POST['name'] parent_id = request.POST.get('parent_id') person = Person(name=name, parent_id=parent_id) person.save() return redirect('/persons') else: return render(request, 'add_person.html')
type: Question
has title: How to get all object children in one query?
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/50995983
tagged with: python-3.x
type: UnansweredQuestion
tagged with: django

http://stackoverflow.com/a/50882370
type: Answer
has body: Assign different port number manually when you start the notebook. For example: jupyter notebook --port=8889
answers question: http://stackoverflow.com/q/50882266
accepted answer of: http://stackoverflow.com/q/50882266
has comment: http://stackoverflow.com/comment/88768455
upvote count: 12
score: 12
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/88884309
comment on: http://stackoverflow.com/a/50872819
has text: How to write the expression using re?
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51008008
has comment: http://stackoverflow.com/comment/99754925
has comment: http://stackoverflow.com/comment/89013202
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/99630935
tagged with: python
has body: I'd like to find out the exact extents of the data inside a matplotlib Axes object; i.e., their highest and lowest x-values, and highest and lowest y-values. (My specific application only needs me to be able to determine the highest x-value with an error of less than 0.5, but I'm curious about the general case.) You're supposed to use Axes.get_xlim() and .get_ylim() to get the extent of an Axes object, but due to the margins, these limits will be slightly outside the data limits. For example: import matplotlib.pyplot as plt plt.plot(range(100), range(100)) ax = plt.gca() print(ax.get_xlim()) # prints (-4.95, 103.95) The margins are given by Axes.margins() as a fraction of the axes, so what if we subtract those? We end up underestimating the limits a little: xlim, xmargin = ax.get_xlim(), ax.margins()[0] width = xlim[1] - xlim[0] lower_xlim = xlim[0] + width*xmargin # 0.495, should be 0 upper_xlim = xlim[1] - width*xmargin # 98.505, should be 99 With trial and error, we find that if we multiply the correcting term by 10/11, we finally hit our mark: lower_xlim = xlim[0] + width*xmargin*10/11 # 0. upper_xlim = xlim[1] - width*xmargin*10/11 # 99. Upon closer inspection with different data ranges and margin sizes, it turns out that the actual factor is: lower_xlim = xlim[0] + width*5/110 # 0. upper_xlim = xlim[1] - width*5/110 # 99. Very bizarre, but it works very well. Except... what if we're using Axes.imshow() instead of Axes.plot()? The plot doesn't have margins in that case (if Axes.use_sticky_edges() is True, which is the default), but the result of Axes.margins() is the same either way. Also, this might be messed up by the addition of non-data Artists such as text boxes outside of the current bounds. (Maybe. I've never tried it.) I know that a foolproof way to find the data limits would be to iterate through all of the data in the Axes object and compute their maxima and minima. This can be done by finding out the Axes object's artists with Axes.get_children(), an…
has answer: http://stackoverflow.com/a/62880868
score: 2
tagged with: axes
upvote count: 2
type: UnansweredQuestion
tagged with: plot
type: Question
has title: Get true limit of plot area of an Axes in matplotlib?
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/89010125

recursion
type: Tag
tags question: http://stackoverflow.com/q/50885001
tags question: http://stackoverflow.com/q/50860869
tag name: recursion
tags question: http://stackoverflow.com/q/50994906
tags question: http://stackoverflow.com/q/50960451
tags question: http://stackoverflow.com/q/51003564
tags question: http://stackoverflow.com/q/50972304
tags question: http://stackoverflow.com/q/50957744
tags question: http://stackoverflow.com/q/50877322
tags question: http://stackoverflow.com/q/50938911
tags question: http://stackoverflow.com/q/50960719
tags question: http://stackoverflow.com/q/50939393
tags question: http://stackoverflow.com/q/51004860
tags question: http://stackoverflow.com/q/50950575
tags question: http://stackoverflow.com/q/50868094
tags question: http://stackoverflow.com/q/50918943
tags question: http://stackoverflow.com/q/50880054

http://stackoverflow.com/comment/88820175
score: 0
type: AnswerComment
has text: That worked, but still I have doubts asked in above comment. Also can you please have a look at [this](https://stackoverflow.com/questions/50858234/which-key-and-certificate-from-keystore-and-truststore-is-used-when-there-are-ma) question?
type: Comment
comment on: http://stackoverflow.com/a/50861563

http://stackoverflow.com/a/50903345
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/50903185
downvote count: 0
has body: The regex here seems to be able to get whatever between the 2nd and 3rd slash. The link has all the explanations for all the syntax that I used. ^(?:[^\/]*\/){2}([^\/]*)\/.*$ Basically, I used the negated set to match everything except the delimiter (/) and capture everything between the second and third delimiter hope it helps :)
type: Answer

http://stackoverflow.com/a/50928114
accepted answer of: http://stackoverflow.com/q/50927753
type: AcceptedAnswer
downvote count: 0
has body: Here's one way. You extract the year from your date series. Then filter for years where strat sum is greater than equal to 3. Finally, sort values by date and drop duplicates by year. df['year'] = pd.to_datetime(df['date']).dt.year res = df.loc[df.groupby('year')['strat'].transform('sum') &gt;= 3]\ .sort_values('date')\ .drop_duplicates(subset=['year']) print(res) date strat year 6 2006-12-26 1 2006 Setup Modified to demonstrate the logic you wish to apply: print(df) date strat 0 2005-12-24 0 1 2005-12-25 0 2 2005-12-25 1 3 2005-12-25 0 4 2005-12-25 1 5 2005-12-26 0 6 2006-12-26 1 7 2006-12-26 1 8 2006-12-26 1 9 2006-12-27 1 10 2006-12-27 0
has comment: http://stackoverflow.com/comment/88872717
answers question: http://stackoverflow.com/q/50927753
has comment: http://stackoverflow.com/comment/88884022
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/88872333
score: 1
has comment: http://stackoverflow.com/comment/88873134

http://stackoverflow.com/comment/89012098
score: 0
comment on: http://stackoverflow.com/q/51009719
type: Comment
type: QuestionComment
has text: So if the user writes egg = up and egg_carton = upupupup the program should output [up, up, up, up]

http://stackoverflow.com/comment/88949843
has text: @scnerd Yes, exactly, which is even more infuriating. I get the same results! Are there alternatives to KDTree that I could use and you recommend? Besides the for cycle.
comment on: http://stackoverflow.com/q/50975833
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88953213
type: QuestionComment
has text: s2 doesn't meet your description of the original regex, so it's not clear what you want your regex to save. Additional explanations and/or examples are necessary.
comment on: http://stackoverflow.com/q/50978660
score: 0
type: Comment

http://stackoverflow.com/comment/88844427
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50922477
type: AnswerComment
has text: He literally mentioned 'C' is a list, so I wrapped it.

openimageio
type: Tag
tags question: http://stackoverflow.com/q/50914650
tag name: openimageio

http://stackoverflow.com/a/50978078
score: 0
has body: what do you need is an object which is associated with the function. It calls attribute. It is very handy in python. Your code may look like this: def no_repeat_rule(play_board): if not hasattr(no_repeat_rule,"mylist"): no_repeat_rule.mylist = [] if seeds_left(play_board) == 2 and sum(play_board[:6])== 1: no_repeat_rule.mylist.append(play_board) return no_repeat_rule.mylist I couldn't check this code, but it should work for local atributes. BTW it is for python 2.7
type: Answer
answers question: http://stackoverflow.com/q/50977801

http://stackoverflow.com/a/51003359
type: AcceptedAnswer
type: Answer
upvote count: 24
answers question: http://stackoverflow.com/q/51003027
downvote count: 0
has comment: http://stackoverflow.com/comment/89000491
accepted answer of: http://stackoverflow.com/q/51003027
has body: There are a few things that are unclear from the Keras documentation that I think are crucial to understanding: For each function in the keras documentation for Merge, there is a lower case and upper case one defined i.e. add() and Add(). On Github, farizrahman4u outlines the differences: Merge is a layer. Merge takes layers as input Merge is usually used with Sequential models merge is a function. merge takes tensors as input. merge is a wrapper around Merge. merge is used in Functional API Using Merge: left = Sequential() left.add(...) left.add(...) right = Sequential() right.add(...) right.add(...) model = Sequential() model.add(Merge([left, right])) model.add(...) using merge: a = Input((10,)) b = Dense(10)(a) c = Dense(10)(a) d = merge([b, c]) model = Model(a, d) To answer your question, since Merge has been deprecated, we have to define and build a layer ourselves for the cosine similarity. In general this will involve using those lowercase functions, which we wrap within a Lambda to create a layer that we can use within a model. I found a solution here: from keras import backend as K def cosine_distance(vests): x, y = vests x = K.l2_normalize(x, axis=-1) y = K.l2_normalize(y, axis=-1) return -K.mean(x * y, axis=-1, keepdims=True) def cos_dist_output_shape(shapes): shape1, shape2 = shapes return (shape1[0],1) distance = Lambda(cosine_distance, output_shape=cos_dist_output_shape)([processed_a, processed_b]) Depending on your data, you may want to remove the L2 normalization. What is important to note about the solution is that it is built using the Keras function api e.g. K.mean() - I think this is necessary when defining custom layer or even loss functions. Hope I was clear, this was my first SO answer!
score: 24

http://stackoverflow.com/comment/88760267
type: QuestionComment
has text: Which version of Django are you using? Password validation was added in Django 1.9.
comment on: http://stackoverflow.com/q/50878903
score: 0
type: Comment

http://stackoverflow.com/comment/88856702
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50916796
has text: @GrahamDumpleton - Thanks for your feedback - there are no logs yet, as it never gets up and running to make any.
score: 0

http://stackoverflow.com/q/50955451
type: Question
has title: Python Timed Rotating Logs
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/50955685
accepted answer: http://stackoverflow.com/a/50955685
has body: Asking for some clarification on this article in the section labeled "TimedRotatingLogs": https://www.blog.pythonlibrary.org/2014/02/11/python-how-to-create-rotating-logs/ handler = TimedRotatingFileHandler(path, when="m", interval=1, backupCount=5) I am curious about this part in particular. When looking at the article it says for "WeekDay" do "w0-w6". Would that look like this? : handler = TimedRotatingFileHandler(path, when="w", interval=0, backupCount=5) Or would it look like: handler = TimedRotatingFileHandler(path, when="w0", interval=1, backupCount=5) And explain why one over the other
favorite count: 0
tagged with: python-3.x
upvote count: 2
tagged with: python
tagged with: logging
score: 2
type: AnsweredQuestion

http://stackoverflow.com/comment/88809748
comment on: http://stackoverflow.com/q/50904883
type: Comment
type: QuestionComment
score: 0
has text: I don't know why it's happening but `>>> tree.find('{http://schemas.microsoft.com/developer/msbuild/2003}PropertyGroup') <Element '{http://schemas.microsoft.com/developer/msbuild/2003}PropertyGroup' at 0x7fc1bb8c81d8>` does work

http://stackoverflow.com/comment/89004306
score: 0
type: Comment
has text: I'm not sure what you're asking. `my_restaurant.pizzas_offered` is a query for pizzas offered by that restaurant; `filter` narrows that down further by the criteria supplied in the parentheses.
type: AnswerComment
comment on: http://stackoverflow.com/a/51005252

http://stackoverflow.com/comment/88720415
type: QuestionComment
score: 1
has text: Please provide a sample dataframe and expected output.
type: Comment
comment on: http://stackoverflow.com/q/50858659

http://stackoverflow.com/comment/91128827
type: QuestionComment
score: 0
has text: Zach, there isn't any magic happening here, the error message isn't lying to you: there is no "pyqt5.6" package. Pip installs packages from Pypi, including this one. You can go to Pypi and confirm this yourself. Specifying a version is optional as well, so once you figure out the actual name of the package you are trying to install (hint: read my previous answer more closely) you can leave it off
comment on: http://stackoverflow.com/q/50893317
type: Comment

http://stackoverflow.com/comment/88802481
type: QuestionComment
comment on: http://stackoverflow.com/q/50901281
has text: Please edit your question to fix your post. That'd be more helpful than posting a comment as not everyone will be reading over the comments
score: 0
type: Comment

http://stackoverflow.com/a/50971301
has comment: http://stackoverflow.com/comment/88941489
accepted answer of: http://stackoverflow.com/q/50971091
has body: You need to create the figure and subplots before hand and pass this in as an argument to df.boxplot(). This also means you can remove the argument layout=(2,2): fig, axes = plt.subplots(2,2,sharex=False,sharey=False) Then use: bp_dict = df.boxplot( by="models", ax=axes, figsize=(6,4), return_type='both', patch_artist = True, )
answers question: http://stackoverflow.com/q/50971091
downvote count: 0
upvote count: 2
type: Answer
score: 2
type: AcceptedAnswer

http://stackoverflow.com/a/50875299
score: 1
has body: Previous answers seem to be good, anyway I'll suggest to consider a regex approach. Just check, for each word, wether is present a punctuation character and if yes remove it. Here an example: import re t = 'test.' punctuations = '[!,\.:;"\']' m = re.search( punctuations, t ) t.replace( m.group(0), '') #out: 'test'
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/50875037

http://stackoverflow.com/comment/88944408
type: QuestionComment
comment on: http://stackoverflow.com/q/50972780
has text: Maybe using a [file-based ringbuffer](https://stackoverflow.com/questions/6293868/a-text-file-circular-buffer-in-python) might be useful?
score: 0
type: Comment

http://stackoverflow.com/a/50964638
accepted answer of: http://stackoverflow.com/q/50962731
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/50962731
downvote count: 0
score: 1
has body: So here's the working method that I am now using: #!/usr/bin/python2.7.x # -*- coding: utf-8 -*- #Imports from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText from email.MIMEBase import MIMEBase from email import encoders from email.Utils import COMMASPACE, formatdate import sys try: from StringIO import StringIO except: print("Could not import critical library StringIO") sys.exit(0) import smtplib import datetime def run_mail(self): date = datetime.datetime.now() dateAAAAMMDD = str(date.year) + "_" + str( date.month) + "_" +str( date.day) pj1 = StringIO(self.pj1_data) pj1_name = "my_att_name_" + str(dateAAAAMMDD) + ".csv" pj2 = StringIO(self.pj2_data) pj2_name = "my_att_name2_" + str(dateAAAAMMDD) + ".txt" pj3 = StringIO(self.pj3_data) pj3_name = "my_att_name3_" + str(dateAAAAMMDD) + ".txt" pj =[(pj1,pj1_name), (pj2,pj2_name), (pj3,pj3_name)] fromaddr = 'address@something.com' toaddr = 'toanotheraddress@something.com' msg = MIMEMultipart() subject = 'subject dated ' + dateAAAAMMDD msg['From'] = fromaddr msg['To'] = toaddr msg['Subject'] = subject msg.attach(MIMEText("Auto-generated script", 'plain')) for data, att_name in pj : part = MIMEBase('application', 'octet-stream') part.set_payload(data.read()) encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename= "%s"' % att_name) msg.attach(part) server_port = 25 server = smtplib.SMTP('myserver.com',server_port) server.starttls() #If login required, not very secure, use either input or localhost without #login required server.login(fromaddr, 'MyPasswordGoesHere') content = msg.as_string() server.sendmail(fromaddr,toaddr,content) server.quit()
type: AcceptedAnswer

http://stackoverflow.com/comment/89009648
has text: Also, this would be the best way of setting default values for some mutabe typed variable.
comment on: http://stackoverflow.com/a/51008181
score: 0
type: AnswerComment
type: Comment

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

http://stackoverflow.com/comment/88766564
has text: @Gerik `models.DateTime` field has a MySQL type `datetime` and `models.DateField` has a type `date`. Interestingly, this type of error never happened to me with a `datetime` field, although I have `created` and `last_modified` timestamps as well, the one in this error is a 3rd time stamp, and only the time part of it. Historically the date and time is split into a separate date and a time field.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50880854
score: 0

http://stackoverflow.com/comment/88913197
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50933101
has text: Yes, am using Webhook with Retrieve Poll. Initially thought it was fine but am seeing old results. Hard to tell whether Zapier step or Bing API (or my query) is at fault. "Developer app"?
type: AnswerComment

http://stackoverflow.com/q/50971988
has comment: http://stackoverflow.com/comment/88956235
answer count: 2
type: UnansweredQuestion
tagged with: python
tagged with: css
has title: How to extract specific element using Xpath or CSS?
tagged with: xpath
score: 0
has answer: http://stackoverflow.com/a/50972773
tagged with: scrapy
type: Question
has body: How do I extract the information that is within the span that in turn is found inside the li? Preço 350 € 6 €/m² Área útil (m²) 60 m² Tipologia T1 I made this code: r esponse.xpath ('// ul [@ class = "mainlist"] / li [span = "T1"] / text ()'). Extract () and the Output is: ['Typology'] But in my case I want it to return the T1 and so I did: response.xpath ('// ul [@ class = "main-list"] / span [li = "Tipology"] / text ()') .extract () but it does not return anything ... what am I doing wrong? any suggestion?
tagged with: web-crawler
has answer: http://stackoverflow.com/a/53946218

http://stackoverflow.com/a/51001873
score: 1
has comment: http://stackoverflow.com/comment/89007354
accepted answer of: http://stackoverflow.com/q/51001694
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51001694
downvote count: 0
type: Answer
has body: First add an average dividend series by group: df['Div_Grp_Avg'] = df.groupby(['Exchange', 'Ticker', 'Year'])['Dividend'].transform('mean') Then sort by this new series: df = df.sort_values('Div_Grp_Avg', ascending=False) Finally, drop the helper column: df = df.drop('Div_Grp_Avg', 1)
upvote count: 1

http://stackoverflow.com/comment/89045658
score: 0
comment on: http://stackoverflow.com/a/50891011
has text: @CallCentreExecutive - I have investigated without success to resolve this issue. The question remains unanswered. Per your note, you are welcome to close the question.
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/88727099
comment on: http://stackoverflow.com/q/50860896
has text: @Splatmistro: question should be minimal, complete & verifiable, links aren't helpful
score: 0
type: QuestionComment
type: Comment

lxml
tags question: http://stackoverflow.com/q/50913959
tags question: http://stackoverflow.com/q/50970691
tags question: http://stackoverflow.com/q/51006509
tags question: http://stackoverflow.com/q/50959006
type: Tag
tags question: http://stackoverflow.com/q/50865088
tags question: http://stackoverflow.com/q/50957772
tags question: http://stackoverflow.com/q/50859204
tag name: lxml
tags question: http://stackoverflow.com/q/50855442
tags question: http://stackoverflow.com/q/50977217
tags question: http://stackoverflow.com/q/50973241
tags question: http://stackoverflow.com/q/50891018

http://stackoverflow.com/q/50878126
has title: python kivy widgets stacking in the bottom
has answer: http://stackoverflow.com/a/50995617
has comment: http://stackoverflow.com/comment/88882361
has comment: http://stackoverflow.com/comment/88867654
type: Question
has body: I have a code that a button press should create a list and put it in list of widgets inside a window but no matter which layout I select and how I create them(specify pos or not) they are always created fine but all stack at the bottom of the screen custom kv widget: &lt;item_widget@FloatLayout&gt; Screen: size_hint:1,None height:25 id:item_space color:18/256,47/256,82/256,0.4 canvas.before: Color: rgba: self.color Rectangle: pos: self.pos size: self.size Label: id:description markup:True on_ref_press:root.open_hyperlink(args[1]) text_size : self.size shorten:True shorten_from:'right' padding_x:4 size_hint:None,1 width:item_space.width-92 pos:self.x,self.y valign:'center' Label: id:diameter text_size : self.size width:25 halign:'center' size_hint:None,1 pos:item_space.width-88,self.y valign:'center' Label: id:pitch text_size : self.size width:25 halign:'center' size_hint:None,1 pos:item_space.width-59,self.y valign:'center' Label: id:price_value text_size : self.size width:30 halign:'center' size_hint:None,1 pos:item_space.width-30,self.y valign:'center' and this function triggers to create all the widgets in a list: def put_items_inscroll(self,item_list): i=0 self.ids.menu_list_scroll.clear_widgets() for dict in item_list: self.ids.menu_list_scroll.add_widget(self.constr_widget(dict)) i+=1 constr_widget definition: def constr_widget(self,item,y=0): row_instance=item_widget() row_instance.ids.description.text='[ref='+item['link']+']'+str(item['description'])+'[/ref]' row_instance.ids.diameter.text=str(item['diameter']) row_instance.ids.pitch.text=str(item['pitch']) row_instance.ids.price_value.text=str(item['calc_valPerProp']) row_instance.size_hint = (1, None) row_instance.height=25 return row_instance Im really stuck with this and nothing i did changed it if Im only putting one widget it goes fine to the top but if I start putting them all they stack in the bottom screen definition: ScrollView: id:menu_list_scroll_window bar_width: 10 effect_cls: "ScrollEffect" sc…
has comment: http://stackoverflow.com/comment/88867956
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/88873748
has comment: http://stackoverflow.com/comment/88866723
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50881831
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88758494
tagged with: python
tagged with: kivy
tagged with: kivy-language
has comment: http://stackoverflow.com/comment/88986105

http://stackoverflow.com/q/50934086
has answer: http://stackoverflow.com/a/50934542
accepted answer: http://stackoverflow.com/a/50934207
favorite count: 0
has body: I have a list: List1 = ['M1', 'M2', 'M3', 'M4', 'M5', 'M5', 'M5', 'M6', 'M7', 'M7', 'M8', 'M9', 'M10', 'M10', 'M10', 'M11'] And I want to find all the duplicates and then add lowercase alphabetic characters after each such that it looks like this: List1 = ['M1', 'M2', 'M3', 'M4', 'M5a', 'M5b', 'M5c', 'M6', 'M7a', 'M7b', 'M8', 'M9', 'M10a', 'M10b', 'M10c', 'M11'] I can find the duplicates, but I am not really sure what to. Any help would be appreciated!
has title: Find duplicates in list and add successive alphabetic characters after each one
tagged with: python
answer count: 4
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/50934455
upvote count: 2
score: 1
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/50934207
possible better answer: http://stackoverflow.com/a/50934455
has comment: http://stackoverflow.com/comment/88867134
has answer: http://stackoverflow.com/a/50934739

http://stackoverflow.com/comment/88799253
has text: Please narrow your problem down. Is the whole selenium code really necessary to answer your (title) question?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50899707
score: 0

http://stackoverflow.com/comment/88822088
has text: @Christoph-Terasa Does this make sense? Can you tell me how to get bounding box around the human in this scenario?
type: Comment
comment on: http://stackoverflow.com/q/50906708
score: 0
type: QuestionComment

http://stackoverflow.com/comment/88844834
type: AnswerComment
has text: yeah, my df is not returning a similar result. I don't get `Name: Value, dtype: int64` in the end. Just to add more information, shape of df before transposing is (1,166) and after transposing (166,1)
type: Comment
comment on: http://stackoverflow.com/a/50922480
score: 0

http://stackoverflow.com/comment/88953208
has text: @tumbleweed Thats odd. Have you run the code step by step? Maybe you can spot something wrong in the process? Lets put it this way: in the end, you `k.id` should be a series of ids, and your `df` should have the same index as k
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/50977563
type: Comment

http://stackoverflow.com/q/50879870
downvote count: 0
has body: I need to apply a pre-defined filter in the Index View of a ModelView class, for example show 'Objects' that have 'Active == 1'. However, the user should be able to reset or modify the filtering conditions (she may want to see all 'Objects', etc.), so modifying the get_query() function is not the way. I ended up using the following solution which just hardcodes the filter arguments if the user open a blank index view from a different referrer: class MyModelView(ModelView): column_filters = ['source', 'active'] @expose('/') def index_view(self): if len(request.args) == 0 and not request.path in str(request.referrer): return redirect(request.path + '?flt2_7=1') else: return super(MyModelView, self).index_view() Is there a better way to do the job? One of the issues here is that changing filters list means having to change the redirect path
favorite count: 0
type: UnansweredQuestion
tagged with: flask-admin
tagged with: python
answer count: 0
type: Question
has title: Preset filter in Flask-Admin index view, but let user change filtering conditions
score: 4
upvote count: 4

http://stackoverflow.com/comment/88793859
score: 0
type: Comment
has text: Yes my friend, it is a library for image processing which tesseract uses and dependent for it.
type: AnswerComment
comment on: http://stackoverflow.com/a/50896952

http://stackoverflow.com/a/61962244
score: 0
type: Answer
has body: You haven't transformed back the values. The predicted value is based on transform data. This should work: predicted_stock_price_orig = inputs.inverse_transform(predicted_stock_price) Please refer to this question for more help: scikit-learn: how to scale back the 'y' predicted result
answers question: http://stackoverflow.com/q/50939347

http://stackoverflow.com/q/50935762
has title: Tensorflow python AI (tutorial by sentdex error)
type: UnansweredQuestion
tagged with: python
has body: i am trying 2 get a AI via the AI course by Sentdex i didnt get the install working at first, got the mac version (i am using win) then i try running the prepeare file in the setup dir and it gives me this error: Error importing tensorflow. Unless you are using bazel, you should not try to import tensorflow from its source directory; please exit the tensorflow source tree, and relaunch your python interpreter from there. anyone know what 2 do?
answer count: 0
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/88870400
has comment: http://stackoverflow.com/comment/88870196
score: 0
has comment: http://stackoverflow.com/comment/88870099

http://stackoverflow.com/comment/88907181
has text: Is this the same as your question from yesterday?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50954560

http://stackoverflow.com/q/50877228
answer count: 1
tagged with: url
has body: I understood that the topic already exists, but I cannot figure out what is the issue. This is the code ( I believe it is straight forward ) import requests import config import time dataID = "111111" # If reportis not generated will return 'None' def get_data(): dataChecking = None checking_url = 'https://api.example.com/v1.1/reports/{0}'.format(dataID) responseCheck = requests.get(checking_url, params=(('fields', 'generated_date'), ), auth=('' + config.authUsername + '', '' + config.authPassword + '')) report_url = responseCheck.json()['report']['generated_date'] dataChecking = requests.get(report_url).content return dataChecking def download_report(dataChecking): urlDownload = 'https://api.example.com/v1.1/reports/{0}'.format(dataID) responseDownload = requests.get(urlDownload, params=(('fields', 'download'), ), auth=('' + config.authUsername + '', '' + config.authPassword + '')) report_url = responseDownload.json()['report']['download'] dataDownload = requests.get(report_url).content with open('' + config.fileDest + '\exportReport.json', 'w') as f: f.write(dataDownload) pass # Checking report is generated generatedData = get_data() # Wating for report to generated while generatedData == None: # Check again if report is generated print("Report is generating, Please wait") generatedData = get_data() # Wait 0.25 seconds between each check time.sleep(0.25) # Report generated, need to download him download_report(dataChecking) Error is : raise InvalidSchema("No connection adapters were found for '%s'" % url) InvalidSchema: No connection adapters were found for '2018-06-15T10:37:50' I have tried to change the URL part, using different tutorials, with no success. '2018-06-15T10:37:50' - This is the date when the report is generated, so what I currently do, is trying to check if the data is empty and keep checking it it filled in (with date, as I demonstrate in the example) and then it will run the download part.
has answer: http://stackoverflow.com/a/50877533
tagged with: python
has title: InvalidSchema("No connection adapters were found for '%s'" % url) - Have tried a lot
accepted answer: http://stackoverflow.com/a/50877533
type: AnsweredQuestion
type: Question
score: 0

http://stackoverflow.com/a/50895103
score: 1
has body: You have a few issues with your solution : 1) You never use curChar, i'm guessing you wanted to enter the next_string value into it after the '==' statement. 2) You compare your next_string to answer, this will always be a false statement. 3) Also no need to use [0+i], [i] is good enough Basically what you want to do is this flow : 1) Read current char 2) Compare to next char 3) If equal put into a different variable 4) If happens again raise a flag Optional solution : vowel_list = ["a","e","i","o","u"] recuring_vowel_boolean_list = [answer[index]==answer[index+1] and answer[index] in vowel_list for index in range(len(answer)-1)] if not any(recuring_vowel_boolean_list ): print("no repeating vowels") elif (recuring_vowel_boolean_list.count(True) &gt; 1): print("More then 1 repeating vowels") else: print("The letter {} repeats".format(answer[recuring_vowel_boolean_list.index(True)]))
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50894960
upvote count: 1

http://stackoverflow.com/q/50919285
accepted answer: http://stackoverflow.com/a/50919360
has body: i'm using python 3.6 on linux, and i was using matplotlib version 1.5.1, so i updated it to latest version 2.2.2 Then there was a problem with a simple code. import matplotlib.pyplot as plt plt.plot([1,2,3,4]) plt.show() when i run this code, error occurred with this message. (the picture popped in a second then it disappeared quickly) self.canvas.manager.window.attributes('-topmost', 1) File "/home/taegyu/tkinter/init.py", line 1782, in wm_attributes return self.tk.call(args) _tkinter.TclError: wrong # args: should be "wm attributes window" After reinstalling with matplotlib version 1.5, I do not see any problem. I think it's probably a problem with tkinter and matplotlib crashes. But i don't know exactly problem and what should i do for this. Can anyone solve this problem?
downvote count: 0
has title: _tkinter.TclError: wrong # args: should be "wm attributes window"
score: 1
favorite count: 0
tagged with: python-3.x
tagged with: tkinter
upvote count: 1
tagged with: python
type: AnsweredQuestion
tagged with: matplotlib
has answer: http://stackoverflow.com/a/50919360
type: Question
answer count: 1
tagged with: python-3.6

http://stackoverflow.com/q/50890997
type: Question
tagged with: visual-studio-code
tagged with: sqlite
downvote count: 0
favorite count: 0
type: UnansweredQuestion
has title: How to colorize sqlite3 text in Virtual Studio Code
tagged with: python
tagged with: anaconda
answer count: 0
score: 1
upvote count: 1
has body: I am trying to make my sqlite code more readable but have failed miserably to find how to change the settings. When I type in something like this anything between the doc string quotes stays the same color as comments, whilst in sublime it gets colorized in a very convenient way. def create_table(): c.execute("""CREATE TABLE IF NOT EXISTS parent_reply( parent_id TEXT PRIMARY KEY, comment_id TEXT UNIQUE, parent TEXT, comment TEXT, subreddit TEXT, unix INT, score INT)""") Python is installed through anaconda: Python 3.6.5 |Anaconda, Inc.| (default, Mar 29 2018, 13:32:41) [MSC v.1900 64 bit (AMD64)] on win32 I am running the code through a virtual environment defined in the anaconda navigator

http://stackoverflow.com/q/50979323
tagged with: hashmap
answer count: 1
has comment: http://stackoverflow.com/comment/88954871
has comment: http://stackoverflow.com/comment/88955179
has comment: http://stackoverflow.com/comment/88955124
has comment: http://stackoverflow.com/comment/88955009
has comment: http://stackoverflow.com/comment/88956086
has title: Custom dict with hashable keys cannot handle recursive structures
has comment: http://stackoverflow.com/comment/88955103
score: 1
has answer: http://stackoverflow.com/a/50979579
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88955236
tagged with: hash
has comment: http://stackoverflow.com/comment/88955712
has comment: http://stackoverflow.com/comment/88956070
downvote count: 2
tagged with: python
has body: I need a dictionary-like structure that can take unhashable keys and map them to a value. I need this for two reasons: Checking if an item has already been seen in O(1) when traversing a list Mapping each item to an identifier, by example a character The created dict-like structure would be thrown away after the process so it cannot be used once keys can be mutated. Example d = MutableKeyDict() d[[1, 2, 3]] = 'a' print([1, 2, 3] in d) # True print((1, 2, 3) in d) # False Implementation tl;dr I implemented something that does not work. If you see a canonical way to implement this, skip that part. For now, I wrote a wrapper class that implements a __hash__ method that falls back on the immutable type equivalent to hash its data. class ForcedHashable: @staticmethod def hashable(obj): try: hash(obj) return obj except TypeError: if isinstance(obj, (list, tuple)): return tuple(ForcedHashable.hashable(o) for o in obj) elif isinstance(obj, set): return frozenset(ForcedHashable(o) for o in obj) elif isinstance(obj, dict): return tuple((k, ForcedHashable.hashable(v)) for k, v in obj.items()) ... def __init__(self, data): self.data = data def __eq__(self, other): return self.data == other.data def __hash__(self): return hash(self.hashable(self.data)) This allowed me to write a draft of a custom dict class that uses the ForcedHashable to wrap its keys. class MutableKeyDict(UserDict): def __setitem__(self, key, value): self.data[ForcedHashable(key)] = value def __getitem__(self, item): return self.data[ForcedHashable(item)] def __contains__(self, item): return ForcedHashable(item) in self.data It works for the basic cases... d = MutableKeyDict() d[[1, 2, 3]] = 'a' print([1, 2, 3] in d) # True print((1, 2, 3) in d) # False But encounters some issues with objects nested in themselves. d = MutableKeyDict() x = [] x.append(x) d[x] = 'foo' # raises a 'RecursionError: maximum recursion depth exceeded' The recursion of course originate from that statement: if isinstance(obj, (list, tup…
tagged with: dictionary
type: AnsweredQuestion
upvote count: 3
accepted answer: http://stackoverflow.com/a/50979579
type: Question

http://stackoverflow.com/q/50948054
favorite count: 0
tagged with: linux
has comment: http://stackoverflow.com/comment/88909337
tagged with: python
tagged with: ffmpeg
has title: openCV function '.read()' return (False, None) in remote environment
tagged with: opencv
type: AnsweredQuestion
has body: I'm running a video processing programe in docker on a remote Linux environment. I have some problems with the following code: import os import cv2 os.chdir("/home/test/wyq/object_detection/") print(os.path.exists("test.mp4")) # see if the file exists print(cv2.__version__) #check cv's version cap = cv2.VideoCapture("test.mp4") print(cap.read()) The result is : True 3.3.0 (False, None) Which means the mp4 file is definitely there and the version of openCV is fine. But it just can't read it. The Linux environment has ffmpeg as well: Here are some information about the OS and python: Ubuntu 16.04.3 LTS (GNU/Linux 4.4.0-127-generic x86_64) Python 3.5.2 (default, Nov 23 2017, 16:37:01) [GCC 5.4.0 20160609] on linux I think maybe the problem is about the ffmpeg? Maybe the opencv failed to use the existing ffmpeg? But I don't know how to test and solve it. Could somebody be so kind to give me some advice? Thank you for your attention.
upvote count: 5
has answer: http://stackoverflow.com/a/50962166
accepted answer: http://stackoverflow.com/a/50962166
type: Question
score: 5
answer count: 1
downvote count: 0

http://stackoverflow.com/q/50883784
has comment: http://stackoverflow.com/comment/88770512
has body: I'm hoping to make a bubble map, but instead of circles to have squares whose areas are scaled to their value. So something like this: Is that possible with Matplotlib? Or can bubble maps only consist of circles?
has comment: http://stackoverflow.com/comment/88774106
tagged with: python
has title: Square bubble map
type: AnsweredQuestion
type: Question
tagged with: matplotlib
tagged with: bubble-chart
has answer: http://stackoverflow.com/a/50884072
accepted answer: http://stackoverflow.com/a/50884072
score: -1
downvote count: 2
has comment: http://stackoverflow.com/comment/88822867
upvote count: 1
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/88984150
has text: Can you post the first ten lines of the file? These are errors from OWLAPI parsing, looks like there is either an error in the ontology file or the format is not a supported one.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50972464
score: 0

http://stackoverflow.com/comment/88849581
has text: I have added a sample.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50924824

http://stackoverflow.com/a/50961056
downvote count: 0
type: Answer
has body: What you wanna look out for is indentation. Python code is all about correct indentation and white space is important so structure your code nicely as python is about readable and neat code. Best of Luck, Happy Coding :) def my_age_months(x): return (x*12) a = my_age_months(36) print("a:") print(a) if a &gt; 400: return "you are not young" else: return "you are young"
answers question: http://stackoverflow.com/q/50960993
upvote count: 5
score: 5

http://stackoverflow.com/a/50867497
has body: Try nohup. In your case, it should be sufficient to run: nohup python app.py &amp; Take note of the number shown as result of this command; it is the pid of the process, and it is used to terminate the process itself, simply by killing it. Suppose that 3456 is the pid of the process, so this command will terminate your application: kill -9 3456 In case you lose the pid, it can be retrieved using this command: ps -A | grep app.py where app.py is the Python script file (the same used in the initial nohup command). Anyway, for further information you can take a look here.
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/50867251
downvote count: 0
score: 1

http://stackoverflow.com/comment/88735962
type: AnswerComment
comment on: http://stackoverflow.com/a/50866388
has text: Sure. New to stack exchange
type: Comment
score: 0

http://stackoverflow.com/a/51012802
upvote count: 1
type: Answer
has body: Far as I can tell (I'm not a Python programmer) Owlready2 is using the HermiT reasoner version 1.3.8 and the embedded OWLAPI version. This version is very ancient - HermiT 1.3.8 uses OWLAPI 3, which has been out of support for a few years now. The parser errors on this section of the ontology: &lt;Movie rdf:about="#Wonder_Woman_"&gt; &lt;isMadeIn rdf:resource="#Hong Kong"/&gt; &lt;/Movie&gt; &lt;Country rdf:about="#Hong Kong"&gt; &lt;rdf:type rdf:resource="http://www.w3.org/2002/07/owl#NamedIndividual"/&gt; &lt;/Country&gt; It is complaining of the #Hong Kong fragment - it cannot cope with the space. Changing to: &lt;Movie rdf:about="#Wonder_Woman_"&gt; &lt;isMadeIn rdf:resource="#Hong_Kong"/&gt; &lt;/Movie&gt; &lt;Country rdf:about="#Hong_Kong"&gt; &lt;rdf:type rdf:resource="http://www.w3.org/2002/07/owl#NamedIndividual"/&gt; &lt;/Country&gt; allows the parser to cope. Long term, Owlready2 should update to a more recent HermiT release. OWLAPI copes with the file in version 4, and HermiT 1.3.8.413 is the version used in Protege.
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/50972464

http://stackoverflow.com/comment/89052567
type: QuestionComment
has text: @mkrieger1 My question was "How to insert a number in between two adjacent numbers". I updated the title and the body section so that it's more obvious/clear what my question is
comment on: http://stackoverflow.com/q/50899951
score: 0
type: Comment

http://stackoverflow.com/q/51009887
tagged with: linestyle
favorite count: 0
linked to: http://stackoverflow.com/q/33936134
answer count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: plot
linked to: http://stackoverflow.com/q/7799156
score: 2
has title: Matplotlib cycle through linestyles and custom dashes
tagged with: matplotlib
tagged with: loops
has body: I am setting up a plot for multiple lines using a for loop. However, I would like to use more than the four standard linestyles (e.g ':', '--' etc). From here I understand I can create custom linestyles using the dashes argument. There are four default linestyles. I set the styles using the code below which works linestyles = ['-', '--', '-.', ':'] plt.figure() for indx in range(4): plt.plot(range(10), range(10), linestyle=linestyles[indx]) and the same would work if I switched to setting the dashes argument e.g dashes = [[3,6,3,6,3,18],[12,6,12,6,3,6],[12,6,3,6,3,6]] plt.figure() for indx in range(4): plt.plot(range(10), range(10), dashes=dashes[indx] however, I would like it such that the first four lines use the standard linestyles and lines after this use the dash styles. Is there an efficient way to do this? Ideally, the solution would use a single list of n linestyles that could also be cycled over as given here. Thanks
type: Question
downvote count: 0
tagged with: python

http://stackoverflow.com/a/50912377
has comment: http://stackoverflow.com/comment/88825659
has comment: http://stackoverflow.com/comment/114190608
downvote count: 0
has comment: http://stackoverflow.com/comment/88828385
score: 5
has comment: http://stackoverflow.com/comment/88825919
has comment: http://stackoverflow.com/comment/88825554
has comment: http://stackoverflow.com/comment/88828098
accepted answer of: http://stackoverflow.com/q/50911887
has comment: http://stackoverflow.com/comment/88845908
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88849047
answers question: http://stackoverflow.com/q/50911887
upvote count: 5
has comment: http://stackoverflow.com/comment/88825046
type: Answer
has body: If right understand, you are trying to avoid handling with a native window. You can try this: # get all inputs inputs = driver.find_elements_by_xpath("//input[@accept = 'image/jpeg']").send_keys(os.getcwd() + "/image.png") Now you can try all of them. I don't know which of them will work. More about os.getcwd() is here To be able to perform this code you have to have an element like this: &lt;input type="file" name="fileToUpload" id="fileToUpload2" class="fileToUpload"&gt; EDIT: It looks like instagram turned of input fields interaction for posts. For Account image it still works, but not for posting. I assume it is was done to prevent bots to post images. Anyway, there is a solution for this problem. You can use AutoIt like this: import autoit from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.desired_capabilities import DesiredCapabilities from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.keys import Keys ActionChains(driver).move_to_element( driver.find_element_by_xpath("//path/to/upload/button")).click().perform() handle = "[CLASS:#32770; TITLE:Open]" autoit.win_wait(handle, 60) autoit.control_set_text(handle, "Edit1", "\\file\\path") autoit.control_click(handle, "Button1")

http://stackoverflow.com/a/50963637
has comment: http://stackoverflow.com/comment/88936710
has comment: http://stackoverflow.com/comment/88935807
answers question: http://stackoverflow.com/q/50962716
has body: Slightly different approach using pool import pandas as pd from multiprocessing import Pool # First make sure each process has its own data groups = df_in['groupid'].unique().values data = [(group_id, holder[group_id], df_in.ix[group_id]) for group for groups] # Prepare a function that can take this data as input def help_func(current_group, holder, current_df): return holder.process_datapoint(current_df, current_group) # Run in parallel with Pool(processes=4) as p: p.map(help_func, data)
has comment: http://stackoverflow.com/comment/88933740
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50962716
has comment: http://stackoverflow.com/comment/88933843
has comment: http://stackoverflow.com/comment/88924511
type: Answer
has comment: http://stackoverflow.com/comment/88933331
has comment: http://stackoverflow.com/comment/89076785
has comment: http://stackoverflow.com/comment/89107228

http://stackoverflow.com/a/50986065
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50985979
has body: In [200]: df Out[200]: col1 col2 0 animal cat;dog;cat 1 animal dog 2 animal fish 3 color black;green 4 color red In [201]: (df.set_index('col1') .col2.str.split(';', expand=True) .stack() .reset_index(level=1, drop=True) .reset_index(name='col2')) Out[201]: col1 col2 0 animal cat 1 animal dog 2 animal cat 3 animal dog 4 animal fish 5 color black 6 color green 7 color red
score: 1
answers question: http://stackoverflow.com/q/50985979

http://stackoverflow.com/q/51007035
tagged with: python-imaging-library
has body: I try to run script for my TFT screen. When I start it within environment IT WORKS. So script is fine. When I start it outside environment I get: ./test Traceback (most recent call last): File "./test", line 5, in &lt;module&gt; from PIL import Image File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 60, in &lt;module&gt; from . import _imaging as core ImportError: cannot import name _imaging i started to think that I have wrong version of PIL or Pillow, but both are uninstalled. pip show shows empty result for both. When I want to install pip install pillow I get few screens of logs and errors (unlike other installed packages). sudo pip install pillow Collecting pillow Using cached https://files.pythonhosted.org/packages/89/b8/2f49bf71cbd0e9485bb36f72d438421b69b7356180695ae10bd4fd3066f5/Pillow-5.1.0.tar.gz Building wheels for collected packages: pillow Running setup.py bdist_wheel for pillow ... error Complete output from command /usr/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-gMbMIp/pillow/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d /tmp/tmpxj0jEHpip-wheel- --python-tag cp27: running bdist_wheel running build running build_py creating build creating build/lib.linux-armv7l-2.7 creating build/lib.linux-armv7l-2.7/PIL copying src/PIL/SpiderImagePlugin.py -&gt; build/lib.linux-armv7l-2.7/PIL copying src/PIL/PdfImagePlugin.py -&gt; build/lib.linux-armv7l-2.7/PIL copying src/PIL/PcfFontFile.py -&gt; build/lib.linux-armv7l-2.7/PIL copying src/PIL/MspImagePlugin.py -&gt; build/lib.linux-armv7l-2.7/PIL copying src/PIL/GbrImagePlugin.py -&gt; build/lib.linux-armv7l-2.7/PIL copying src/PIL/XVThumbImagePlugin.py -&gt; build/lib.linux-armv7l-2.7/PIL copying src/PIL/ExifTags.py -&gt; build/lib.linux-armv7l-2.7/PIL copying src/PIL/JpegPresets.py -&gt; build/lib.linux-armv7l-2.7/PIL copying src/PIL/version.py -&gt; build/lib.linux-armv7…
score: 0
has comment: http://stackoverflow.com/comment/89007460
tagged with: environment-variables
has title: Python: Strange behavior of PIL and cannot install pillow with pip
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89007378
has comment: http://stackoverflow.com/comment/89008004
answer count: 0
has comment: http://stackoverflow.com/comment/89008058
has comment: http://stackoverflow.com/comment/89007347
tagged with: pip
type: Question

http://stackoverflow.com/a/50862563
has comment: http://stackoverflow.com/comment/111648503
score: 8
upvote count: 8
type: Answer
accepted answer of: http://stackoverflow.com/q/50862101
answers question: http://stackoverflow.com/q/50862101
has comment: http://stackoverflow.com/comment/111649955
type: AcceptedAnswer
has body: I think one way of achieving that is using a Keras backend function. Here we define a function that takes as input two tensors and returns as output a tensor: from keras import Model from keras import layers x = layers.Input(shape=(None,)) y = layers.Input(shape=(None,)) loss_func = K.function([x, y], [masked_loss_function(x, y, 0)]) And now we can use loss_func to run the computation graph we have defined: assert loss_func([[[1,0]], [[1,1]]]) == [[0]] Note that keras backend function, i.e. function, expects that the input and output arguments be an array of tensors. Additionally, x and y takes a batch of tensors, i.e. an array of tensors, with undefined shape.
downvote count: 0

http://stackoverflow.com/a/71404643
type: Answer
has comment: http://stackoverflow.com/comment/126212002
downvote count: 6
has comment: http://stackoverflow.com/comment/126216260
answers question: http://stackoverflow.com/q/50982064
score: -6
upvote count: 0
has body: I found a simpliest way to do that in Linux Env... import os os.system("lowriter --convert-to pdf" +str(" ") + str(file_path))

http://stackoverflow.com/comment/95284432
type: Comment
comment on: http://stackoverflow.com/a/50969140
type: AnswerComment
has text: The next answer makes the simple change of including the multiplication _inside_ the `np.array()` invocation. From the wording of your answer it would appear you were not aware of it.
score: 0

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

http://stackoverflow.com/comment/88934212
comment on: http://stackoverflow.com/a/50967282
type: AnswerComment
score: 0
type: Comment
has text: @SarvagyaGupta Difference between python 2 and 3 OR between the two methods in the answer?

http://stackoverflow.com/q/50864469
has answer: http://stackoverflow.com/a/50864856
upvote count: 0
has comment: http://stackoverflow.com/comment/88732342
has title: Different implementations of repr
answer count: 3
has answer: http://stackoverflow.com/a/50864997
has comment: http://stackoverflow.com/comment/88732715
score: -2
has comment: http://stackoverflow.com/comment/88731451
favorite count: 0
downvote count: 2
tagged with: python
tagged with: repr
has comment: http://stackoverflow.com/comment/88732775
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50864997
has comment: http://stackoverflow.com/comment/88731491
linked to: http://stackoverflow.com/q/3691101
has comment: http://stackoverflow.com/comment/88731617
possible better answer: http://stackoverflow.com/a/50865045
has body: So I have this class with the repr method implemented import reprlib class Test: def __init__(self, aList): self.my_list = [c for c in aList] def __repr__(self): # return " ".join((str(i) for i in self.my_list)) # return reprlib.repr(self.my_list) # return repr(self.my_list) # builtin repr method return str(self.my_list) What are the differences between the various implementations of the repr method? They all have the same output. Code used on all implementations: x = [2, 5, 11] t = Test(x) print(t) # &gt;&gt; [2, 5, 11] t # &gt;&gt; output [2, 5, 11] Edit: The first implementation (join method) will produce the items without brackets. Disregard that if you like. My focus is what are differences among the last three and which is the better implementation among all four implementation. Edit: This is clearly not about the differences between the repr and str methods. It's about which implementation should I consistently adopt when implementing the repr method (or the str method for that matter).
type: Question
has answer: http://stackoverflow.com/a/50865045
has comment: http://stackoverflow.com/comment/88732783

http://stackoverflow.com/comment/88761509
type: Comment
has text: Possibly but I am really impressed with people here who have in depth knowledge not only in Python/R coding but in statistics as well
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50860512

http://stackoverflow.com/comment/88836556
type: QuestionComment
has text: Any chance you can create an example and share your custom function? When I read your question, my mind thinks scipy optimize or custom scikit-learn [make_scorer](http://scikit-learn.org/stable/modules/generated/sklearn.metrics.make_scorer.html).
score: 1
comment on: http://stackoverflow.com/q/50917864
type: Comment

http://stackoverflow.com/q/50948910
tagged with: upgrade
tagged with: python
has body: i am trying to upgrade pip using pip install --upgrade pip but getting error File "&lt;stdin&gt;", line 1 pip install --upgrade pip ^ SyntaxError: invalid syntax can anyone tell me what's the exact issue?
favorite count: 0
score: -1
has answer: http://stackoverflow.com/a/50949034
tagged with: installation
downvote count: 2
tagged with: pip
upvote count: 1
answer count: 1
has title: Invalid syntax error for 'pip install --upgrade pip'
has comment: http://stackoverflow.com/comment/88895307
has comment: http://stackoverflow.com/comment/88895543
accepted answer: http://stackoverflow.com/a/50949034
linked to: http://stackoverflow.com/q/8548030
type: Question
duplicate of: http://stackoverflow.com/q/8548030
type: AnsweredQuestion

http://stackoverflow.com/comment/88979995
has text: @AndrewSvetlov I've solved the problem. I need to import request handler to file, where i create and run web.Application.
comment on: http://stackoverflow.com/q/50984282
type: QuestionComment
type: Comment
score: 1

http://stackoverflow.com/comment/88828245
type: AnswerComment
has text: Please add more explanation.
type: Comment
comment on: http://stackoverflow.com/a/50909708
score: 2

http://stackoverflow.com/comment/88826622
score: 0
type: AnswerComment
has text: Great that you compared the answers.
type: Comment
comment on: http://stackoverflow.com/a/50900687

http://stackoverflow.com/comment/88822471
has text: could you just explain me what does the `index=`do
comment on: http://stackoverflow.com/a/50909859
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/50975317
has comment: http://stackoverflow.com/comment/88947044
has body: I suggest you create copies of the dict and store the specific data in each one. For example: result = [] for pos in range(0, len(original_dict['headliner'])): new_dict = original_dict.copy() new_dict['data'] = original_dict['data'][pos*3:(pos+1)*3] new_dict['headliner'] = original_dict['headliner'][pos] result.append(new_dict) print(result)
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/50975224
upvote count: 1

http://stackoverflow.com/comment/88755766
comment on: http://stackoverflow.com/q/50872972
score: 0
has text: @user3280146 but do you want the output as rows (with many columns) or as columns, knowing that you want to interpolate between Time0 and Time1 from a same row?
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/88778810
type: QuestionComment
has text: is there any single paramiko script for 30 hosts which takes donwload parallely
comment on: http://stackoverflow.com/q/50888082
score: 0
type: Comment

http://stackoverflow.com/a/50867091
type: Answer
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50867030
upvote count: 2
has body: Using only the standard library: import random test = [[1, 5, 4, 3, 5, 2], [4, 2], [5, 2, 4, 3, 5], [5, 3, 1]] min_size = float("inf") for sublist in test: length = len(sublist) if length &lt; min_size: min_size = length new_list = [random.sample(sublist, min_size) for sublist in test] # [[5, 4], [2, 4], [5, 3], [1, 5]]

http://stackoverflow.com/comment/102786245
comment on: http://stackoverflow.com/a/50882601
type: AnswerComment
has text: There is now a nice documentation on how to use gradient tape in general and stop_recording in particular: https://www.tensorflow.org/api_docs/python/tf/GradientTape
score: 0
type: Comment

http://stackoverflow.com/q/50950046
upvote count: 2
score: 1
has comment: http://stackoverflow.com/comment/88905708
has body: This sounds like a stupid question, but I can't get it to work. from pygame import * from random import * from math import * import os from datetime import datetime #importing all needed modules mixer.init() #initializing mixer for sound use init() #initializing pygame font.init() #Just to prove that it still doesn't work SCREEN = (1000,700) os.environ['SDL_VIDEO_WINDOW_POS'] = "%d, %d" %(350, 25) screen = display.set_mode(SCREEN) font = font.SysFont("Times New Roman", 52) font2 = font.SysFont("Times New Roman", 12) the first one works but the second one throws an error: builtins.AttributeError: 'pygame.font.Font' object has no attribute 'SysFont' been having this problem and need to use fonts because I need to blit a variable that changes.
has comment: http://stackoverflow.com/comment/88897915
downvote count: 1
type: Question
has title: I cannot use more than one font in pygame
answer count: 1
has answer: http://stackoverflow.com/a/51178849
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: pygame
has comment: http://stackoverflow.com/comment/88897789

http://stackoverflow.com/comment/88884478
comment on: http://stackoverflow.com/q/50943381
has text: You should review the documentation of the module that provides the database API. Also have a look at this: https://stackoverflow.com/q/902408/1025391 and this: https://stackoverflow.com/a/42947632/1025391
score: 0
type: Comment
type: QuestionComment

mysql
tags question: http://stackoverflow.com/q/50880854
tags question: http://stackoverflow.com/q/50934373
tags question: http://stackoverflow.com/q/50917997
tags question: http://stackoverflow.com/q/50905720
tags question: http://stackoverflow.com/q/50948263
tags question: http://stackoverflow.com/q/50946993
tags question: http://stackoverflow.com/q/50907013
tag name: mysql
tags question: http://stackoverflow.com/q/50881441
tags question: http://stackoverflow.com/q/51002735
tags question: http://stackoverflow.com/q/50855155
tags question: http://stackoverflow.com/q/51003239
tags question: http://stackoverflow.com/q/50867356
tags question: http://stackoverflow.com/q/50970504
tags question: http://stackoverflow.com/q/50871526
tags question: http://stackoverflow.com/q/50881698
tags question: http://stackoverflow.com/q/50979415
tags question: http://stackoverflow.com/q/50953508
tags question: http://stackoverflow.com/q/50896935
tags question: http://stackoverflow.com/q/50871088
tags question: http://stackoverflow.com/q/51004941
tags question: http://stackoverflow.com/q/50897891
tags question: http://stackoverflow.com/q/50878337
tags question: http://stackoverflow.com/q/50864602
tags question: http://stackoverflow.com/q/50948777
tags question: http://stackoverflow.com/q/50884396
tags question: http://stackoverflow.com/q/50890519
tags question: http://stackoverflow.com/q/50879900
tags question: http://stackoverflow.com/q/50926769
tags question: http://stackoverflow.com/q/50945391
tags question: http://stackoverflow.com/q/50932144
tags question: http://stackoverflow.com/q/50973191
tags question: http://stackoverflow.com/q/50906335
tags question: http://stackoverflow.com/q/50886423
tags question: http://stackoverflow.com/q/50988960
type: Tag
tags question: http://stackoverflow.com/q/50978144
tags question: http://stackoverflow.com/q/50944601
tags question: http://stackoverflow.com/q/51005745
tags question: http://stackoverflow.com/q/50893458
tags question: http://stackoverflow.com/q/50999160
tags question: http://stackoverflow.com/q/50931416
tags question: http://stackoverflow.com/q/50969484
tags question: http://stackoverflow.com/q/50899707
tags question: http://stackoverflow.com/q/50862238
tags question: http://stackoverflow.com/q/50938216
tags question: http://stackoverflow.com/q/50948385
tags question: http://stackoverflow.com/q/50960258
tags question: http://stackoverflow.com/q/50982284
tags question: http://stackoverflow.com/q/50866370
tags question: http://stackoverflow.com/q/50896631
tags question: http://stackoverflow.com/q/50999447
tags question: http://stackoverflow.com/q/50933434
tags question: http://stackoverflow.com/q/50884857
tags question: http://stackoverflow.com/q/50889692
tags question: http://stackoverflow.com/q/50906416
tags question: http://stackoverflow.com/q/50992334

http://stackoverflow.com/q/50975343
accepted answer: http://stackoverflow.com/a/50975570
type: AnsweredQuestion
type: Question
answer count: 1
tagged with: django-rest-framework
has answer: http://stackoverflow.com/a/50975570
score: 0
tagged with: python
has body: We have 2 approach ideas that we are trying to consider here for the Django REST api. At the moment, we have implemented 1 filter option: class APINewsViewSet(viewsets.ModelViewSet): serializer_class = APINewsSerialiser def get_queryset(self): queryset = NewsBackup.objects.all() source = self.request.query_params.get('source', None) if source is not None: queryset = queryset.filter(news_source = source) return queryset This achieves: 127.0.0.1/news?source=xxx Something additional that we would like to do is have other filter options that the user can type in such as 127.0.0.1/news?source=xxx&amp;sourcename=xxx which would then return them the JSON object with only data that has a source_id of xx and source_name of xx. Is this possible with the Django REST framework? We have tried to add other options within the method: query_params.get()
tagged with: python-3.x
has title: django multiple filter options on queryset
tagged with: django

http://stackoverflow.com/q/51003898
has title: Getting app cannot be run on your PC after compiling python script using pyinstaller
has body: I wrote a program that takes a screenshot and sends it to my e-mail address. I made my python scripts executable using pyinstaller. I did it by executing command: pyinstaller -w screenshot.py -F The executable program ran perfectly on my PC but when I ran it to my friend's PC, I got error saying "This app can't run on your PC. To find a version for PC, check with the software publisher." How can I solve this problem?
type: Question
has answer: http://stackoverflow.com/a/51004342
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/51004342
upvote count: 2
tagged with: python
score: 2
type: AnsweredQuestion

http://stackoverflow.com/a/50911946
has comment: http://stackoverflow.com/comment/88847441
has comment: http://stackoverflow.com/comment/88846952
score: 0
has comment: http://stackoverflow.com/comment/88847269
type: AcceptedAnswer
has body: You can use cumcount to align index by group, then concat to concatenate series. # normalize to zero out time df['StartTime'] = pd.to_datetime(df['StartTime']).dt.normalize() # get unique days and make index count by group cols = df['StartTime'].unique() df.index = df.groupby('StartTime').cumcount() # concatenate list comprehension of series res = pd.concat([df.loc[df['StartTime'] == i, 'Id'] for i in cols], axis=1) res.columns = cols print(res) 2018-04-24 2018-04-25 2018-04-26 2018-04-27 0 aaa ccc ddd ggg 1 bbb aaa fff NaN Performance For smaller dataframes, use @ScottBoston's more succinct solution. For larger dataframes, concat seems to scale better than unstack: def scott(df): df['StartTime'] = pd.to_datetime(df['StartTime']) return df.set_index([df['StartTime'].dt.floor('D'), df.groupby(df['StartTime'].dt.floor('D')).cumcount()])['Id'].unstack(0) def jpp(df): df['StartTime'] = pd.to_datetime(df['StartTime']).dt.normalize() df.index = df.groupby('StartTime').cumcount() res = pd.concat([df.loc[df['StartTime'] == i, 'Id'] for i in df['StartTime'].unique()], axis=1) res.columns = cols return res df2 = pd.concat([df]*100000) %timeit scott(df2) # 1 loop, best of 3: 681 ms per loop %timeit jpp(df2) # 1 loop, best of 3: 271 ms per loop
has comment: http://stackoverflow.com/comment/88847531
accepted answer of: http://stackoverflow.com/q/50911198
answers question: http://stackoverflow.com/q/50911198
has comment: http://stackoverflow.com/comment/88847953
type: Answer
has comment: http://stackoverflow.com/comment/88847560
has comment: http://stackoverflow.com/comment/88846805

http://stackoverflow.com/q/50901680
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/50901728
has answer: http://stackoverflow.com/a/50901773
accepted answer: http://stackoverflow.com/a/50901773
type: Question
possible better answer: http://stackoverflow.com/a/50901728
has body: So I have a generated JSON which one looks like ( there is a lot of it just with unique ID ) { "id": 1, "name": "name", "dep": "dep", "Title": "Title', "email": "email" } I'm trying to do "append" a new field but I get an error with open('data.json', 'w') as file: json.dump(write_list, file) file.close() with open('data.json', 'w') as json_file: entry = {'parentId': random.randrange(0, 487, 2)} json_file.append(entry, json_file) json_file.close() It there is some way to add one more "key: value" to it after generating ?
has comment: http://stackoverflow.com/comment/88803306
has comment: http://stackoverflow.com/comment/88803336
score: 0
tagged with: random
answer count: 3
has comment: http://stackoverflow.com/comment/88803286
has answer: http://stackoverflow.com/a/50909016
tagged with: python
has title: Add one more attribute to JSON file
has comment: http://stackoverflow.com/comment/88803313

http://stackoverflow.com/comment/88845165
comment on: http://stackoverflow.com/q/50922691
score: 0
type: Comment
type: QuestionComment
has text: @TobiasDex I'm not sure but passing either `header` or `names` in `read_csv` should work.

http://stackoverflow.com/q/50955782
answer count: 1
has title: Best way to remove rows that have more of a certain value than a given amount (numpy)
has body: I created an array of numbers of column size d, where the numbers are different combinations of set(p). Next, I want to delete the rows where there are more instances of a number than there were in p. I can do it with a for loop, here is my code: import numpy as np import itertools as it from collections import Counter p = [0,0,0,1,1,1,1,2,2,2,2,2,3,3,3,4,4,4,4,4,5,5,5] assert (len(set(p)) != 1) cnt = Counter(p) pos = np.array(list(it.product(set(p), repeat=d))) ds = [] for i in range(len(pos)): for j, k in cnt.items(): if len(np.where(pos[i] == j)[0]) &gt; k: ds.append(i) pos = np.delete(pos, ds, axis=0) I am looking for a faster way to do this. Thank you!
favorite count: 0
has answer: http://stackoverflow.com/a/50956127
upvote count: 2
tagged with: python
linked to: http://stackoverflow.com/q/46256279
score: 2
type: AnsweredQuestion
tagged with: list
accepted answer: http://stackoverflow.com/a/50956127
type: Question
tagged with: numpy
tagged with: arrays
downvote count: 0

http://stackoverflow.com/comment/88783006
type: Comment
has text: @coldspeed Sorry, and thank you. I think it's fixed now.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50891043

http://stackoverflow.com/a/51749850
type: Answer
answers question: http://stackoverflow.com/q/51007214
has body: Since you have both versions of Python installed in your system, you need to direct your default Python to Python 3.x. You can do that by adding a few lines to your .bashrc file. Open your .bashrc file nano ~/.bashrc. Type alias python=python3 on to a new line at the top of the file then save the file with ctrl+o and close the file with ctrl+x. Then, back at your command line type source ~/.bashrc. Now your alias should be permanent. EDIT: For update alternatives, the priority is an integer. The priority represents which program should be the first used. This article sums it all up pretty well. Here is the related question: https://stackoverflow.com/a/41986843/4982185
score: 0

http://stackoverflow.com/a/50877207
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50876976
has body: You can use pandas apply function. You can pass axis=1 to apply a given function to every row: df.apply( creational_function, # Method that creates your structure axis=1, # Apply to every row args=(arg1, arg2) # Additional args to creational_function ) in creational_function the first argument received is the row, where you can access specific columns likewise the original dataframe def creational_function(row, arg1, arg2): s = row['Series_reference'] # For brevity I skip the others arguments... # Create TestData # Save Note that arg1 and arg2 are the same for every row. If you want to do something more with your created TestData objects, you can change creational_function to return a value, then df.apply will return a list containing all elements returned by the passed function.

http://stackoverflow.com/q/50876568
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88755186
has body: I want to create a program that only runs when a number of valid arguments have been typed from command prompt. But the program will keep looping until "" is entered. For example: C:\User\ABC&gt;python example.py "argv1" "argv2" -&gt; do something, then ask to keep prompting for more arguments in command prompt C:\User\ABC&gt;python example.py -&gt; no argument, the program will ask for arguments. If "" is entered, the program will exit C:\User\ABC&gt;python example.py "argv1" "argv2" "argv3" -&gt; too many arguments, error code display sys.exit(1)
accepted answer: http://stackoverflow.com/a/50877865
has comment: http://stackoverflow.com/comment/88755247
has comment: http://stackoverflow.com/comment/88754919
answer count: 1
has comment: http://stackoverflow.com/comment/88755428
favorite count: 0
has comment: http://stackoverflow.com/comment/88755200
score: 0
has comment: http://stackoverflow.com/comment/88755273
has comment: http://stackoverflow.com/comment/88755480
has comment: http://stackoverflow.com/comment/88754928
tagged with: python
has answer: http://stackoverflow.com/a/50877865
tagged with: python-3.x
linked to: http://stackoverflow.com/q/35491845
has title: Looping for more arguments in sys
has comment: http://stackoverflow.com/comment/88755096
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/89007458
type: Comment
comment on: http://stackoverflow.com/a/50942372
score: 0
type: AnswerComment
has text: I am very sorry. It seems that I missed the space you have added at the end. I have removed my answer and accepted yours as soon as I noticed that. Please accept my sincere apology =>

http://stackoverflow.com/a/51266437
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50971533
answers question: http://stackoverflow.com/q/50971533
type: Answer
upvote count: 1
score: 1
has body: modalClientPopup() is referring to window.showModalDialog(), which is deprecated. So I have altered the html code on the fly, with a piece of JavaScript : browser.execute_script(""" setInterval (function() { override (); }, 500); function override () { var divElem; var innerDoc; var focus; divElem = document.getElementsByClassName('content_sub_zone'); innerDoc = divElem[0].childNodes[0].contentDocument; focus = innerDoc.getElementsByTagName('span')[0]; focus.setAttribute("onclick", "window.open('http://myserver.local/target', '', 'width=800,height=400');"); } """)
type: AcceptedAnswer

http://stackoverflow.com/tag/csv
tags question: http://stackoverflow.com/q/50991084
tags question: http://stackoverflow.com/q/50955504
type: Tag
tags question: http://stackoverflow.com/q/50990042
tags question: http://stackoverflow.com/q/50960123
tags question: http://stackoverflow.com/q/50999981
tags question: http://stackoverflow.com/q/51005244
tags question: http://stackoverflow.com/q/50872534
tags question: http://stackoverflow.com/q/50990679
tags question: http://stackoverflow.com/q/50899880
tags question: http://stackoverflow.com/q/50966822
tags question: http://stackoverflow.com/q/50958377
tags question: http://stackoverflow.com/q/50933170
tags question: http://stackoverflow.com/q/50895398
tag name: csv
tags question: http://stackoverflow.com/q/50910915
tags question: http://stackoverflow.com/q/50865164
tags question: http://stackoverflow.com/q/50988588
tags question: http://stackoverflow.com/q/50952675
tags question: http://stackoverflow.com/q/50858552
tags question: http://stackoverflow.com/q/50936747
tags question: http://stackoverflow.com/q/50963689
tags question: http://stackoverflow.com/q/50908246
tags question: http://stackoverflow.com/q/50942996
tags question: http://stackoverflow.com/q/50997936
tags question: http://stackoverflow.com/q/50959561
tags question: http://stackoverflow.com/q/50969750
tags question: http://stackoverflow.com/q/50876776
tags question: http://stackoverflow.com/q/50993993
tags question: http://stackoverflow.com/q/50909650
tags question: http://stackoverflow.com/q/50917616
tags question: http://stackoverflow.com/q/50917484
tags question: http://stackoverflow.com/q/50880487
tags question: http://stackoverflow.com/q/50967803
tags question: http://stackoverflow.com/q/50859987
tags question: http://stackoverflow.com/q/50953013
tags question: http://stackoverflow.com/q/50923028
tags question: http://stackoverflow.com/q/50877681
tags question: http://stackoverflow.com/q/50912945
tags question: http://stackoverflow.com/q/50955219
tags question: http://stackoverflow.com/q/50949238
tags question: http://stackoverflow.com/q/50977683
tags question: http://stackoverflow.com/q/50941059
tags question: http://stackoverflow.com/q/51001165
tags question: http://stackoverflow.com/q/50925340
tags question: http://stackoverflow.com/q/50990123
tags question: http://stackoverflow.com/q/50975025
tags question: http://stackoverflow.com/q/50859316
tags question: http://stackoverflow.com/q/50868998
tags question: http://stackoverflow.com/q/50921058
tags question: http://stackoverflow.com/q/50974293
tags question: http://stackoverflow.com/q/50907291
tags question: http://stackoverflow.com/q/50932096
tags question: http://stackoverflow.com/q/50882547
tags question: http://stackoverflow.com/q/50876470
tags question: http://stackoverflow.com/q/50889248
tags question: http://stackoverflow.com/q/50914083
tags question: http://stackoverflow.com/q/50979628
tags question: http://stackoverflow.com/q/50861567
tags question: http://stackoverflow.com/q/51010574
tags question: http://stackoverflow.com/q/51010502
tags question: http://stackoverflow.com/q/50914835
tags question: http://stackoverflow.com/q/50881944
tags question: http://stackoverflow.com/q/50922691
tags question: http://stackoverflow.com/q/50991397
tags question: http://stackoverflow.com/q/50861253
tags question: http://stackoverflow.com/q/50884835
tags question: http://stackoverflow.com/q/50921608
tags question: http://stackoverflow.com/q/50899612
tags question: http://stackoverflow.com/q/50993064
tags question: http://stackoverflow.com/q/50991909
tags question: http://stackoverflow.com/q/50923413
tags question: http://stackoverflow.com/q/50959078
tags question: http://stackoverflow.com/q/50901326
tags question: http://stackoverflow.com/q/50936756
tags question: http://stackoverflow.com/q/50939977
tags question: http://stackoverflow.com/q/50907531
tags question: http://stackoverflow.com/q/50896193
tags question: http://stackoverflow.com/q/50915041
tags question: http://stackoverflow.com/q/50895144

http://stackoverflow.com/a/51003061
accepted answer of: http://stackoverflow.com/q/51001968
upvote count: 3
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51001968
type: Answer
score: 3
downvote count: 0
has body: You could achieve this with torch.bmm() and some torch.squeeze()/torch.unsqueeze(). I am personally rather fond of the more generictorch.einsum() (which I find more readable): import torch import numpy as np A = torch.from_numpy(np.array([[[1, 10, 100], [2, 20, 200], [3, 30, 300]], [[4, 40, 400], [5, 50, 500], [6, 60, 600]]])) B = torch.from_numpy(np.array([[ 1, 2, 3], [-1, -2, -3]])) AB = torch.einsum("nbh,nb-&gt;nh", (A, B)) print(AB) # tensor([[ 14, 140, 1400], # [ -32, -320, -3200]])

http://stackoverflow.com/comment/88717941
type: AnswerComment
comment on: http://stackoverflow.com/a/50857539
has text: Agreed, just a stylistic point, I often see `{k: foo(d[k]) for k in d}` instead of `{k: foo(v) for k, v in d.items()}`, always thought the latter is clearer.
score: 0
type: Comment

http://stackoverflow.com/a/50890904
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50890844
type: Answer
has body: One option is to use pd.DataFrame.query: res = df.query('((A == 1) &amp; (B == 1)) | ((A == 2) &amp; (B == 2))') print(res) Col1 A B C 1 1 1 0.981483 2 0.851543 2 2 7 -0.522760 8 -0.332099 For a more generic solution, you can use f-strings (Python 3.6+), which should perform better than str.format or manual concatenation. filters = [(1,1), (2,2)] filterstr = '|'.join(f'(A=={i})&amp;(B=={j})' for i, j in filters) res = df.query(filterstr) print(filterstr) (A==1)&amp;(B==1)|(A==2)&amp;(B==2)
answers question: http://stackoverflow.com/q/50890844
score: 0

http://stackoverflow.com/a/71798541
upvote count: 0
downvote count: 3
has comment: http://stackoverflow.com/comment/126884353
answers question: http://stackoverflow.com/q/50951955
score: -3
has body: pytesseract.pytesseract.tesseract_cmd = 'C:\\Program Files (x86)\\Tesseract-OCR\\tesseract.exe' this helped in my case
type: Answer

http://stackoverflow.com/a/50875445
has body: With Pandas, you should aim to use vectorised operations: # convert series to datetime, if not already df['last_login'] = pd.to_datetime(df['last_login']) # calculate Boolean series mask mask = df['last_login'].dt.normalize() == pd.to_datetime('today') # apply mask df_filtered = df[mask] # optionally, convert to list of lists df_filtered_L = df_filtered.values.tolist() Normalizing a datetime series flattens the time component to zero, so you can compare it with pd.to_datetime('today'), which is already normalized. For example, pd.to_datetime('now').normalize() == pd.to_datetime('today') returns True.
downvote count: 0
answers question: http://stackoverflow.com/q/50875363
has comment: http://stackoverflow.com/comment/88753125
has comment: http://stackoverflow.com/comment/88752791
type: Answer
has comment: http://stackoverflow.com/comment/88755779
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/88753238
has comment: http://stackoverflow.com/comment/88753208

http://stackoverflow.com/a/50893252
has comment: http://stackoverflow.com/comment/88786975
type: Answer
has body: If you want to send goldCount through to HTML you need to use a render_template rather than a redirect. Store the goldCount into session then just call {{request.session.goldCount}} in your HTML. Also, the correct if statement would be: if 'goldCount' not in request.session: request.session['goldCount'] = 0
accepted answer of: http://stackoverflow.com/q/50891877
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50891877
score: 0

json-rpc
tag name: json-rpc
type: Tag
tags question: http://stackoverflow.com/q/50948223

http://stackoverflow.com/comment/88949407
has text: Good observation. That was previously posted by me. but after incorporating those changes I was facing this new issue. But this is an entirely different topic.so I had to post it again.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50976432

http://stackoverflow.com/comment/88924595
comment on: http://stackoverflow.com/q/50962722
type: Comment
has text: @sudonym my guess is that you have to imagine starting times as they are (00:00) and ending times as if they had minutes and seconds set to 59:59
score: 0
type: QuestionComment

http://stackoverflow.com/comment/88749097
comment on: http://stackoverflow.com/q/50871343
score: 0
type: Comment
type: QuestionComment
has text: As far as I understood it, you need three points for a quadratic Bezier curve: start, end and control point. You pass start and end point as well as rad (for calculation of control point) to Fancyarrow, whereas you give all three points to the path patch (and specify the connection with CURVE3) I do not think that the red curve consists of two quadratic Bezier curves, because the labels, which are plotted on a Bezier curve, calculated separately from the path, align with it. But maybe I understood some of the definitions wrong?

http://stackoverflow.com/q/50896631
tagged with: database-connection
tagged with: database-security
type: UnansweredQuestion
tagged with: python
tagged with: mysql
has body: I am writing a Python test class with methods relying on a connection to a MySQL database. The purpose of the test class is to test another class used for simplifying interaction with the same database. The interaction is managed through pymysql which requires login credentials to a MySQL account. I am investigating the possibility of automatically creating a MySQL test user on any server when executing the tests. My goal is to be able to install the code as a package and have the tests run with a setup procedure that returns the connection to a database without any involvement from the user. I am currently only familiar with creating MySQL users through an already existing superuser. The temporary solution is to include a file with login credentials that is read and used by the test module. I might be that I approach the problem from a completely wrong angle. In general I am trying to test code that executes MySQL commands and commits changes to a database. I am grateful of any tips, ideas or experiences. Cheers,
type: Question
tagged with: pymysql
has title: Python tests to functions relying on a MySQL user and connetion
has answer: http://stackoverflow.com/a/50896734
score: 0
linked to: http://stackoverflow.com/q/28431452
answer count: 1

http://stackoverflow.com/comment/88987768
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50996525
type: Comment
has text: Thank you so much it worked!! Now how can I change the value of product.in_cart to true or false according to which link the user clicks?

http://stackoverflow.com/q/50924723
favorite count: 0
has answer: http://stackoverflow.com/a/50924995
has title: requests.get is very slow while fetching websites
accepted answer: http://stackoverflow.com/a/50924995
tagged with: python-3.x
tagged with: time
tagged with: python
has comment: http://stackoverflow.com/comment/88848899
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88849022
downvote count: 0
score: 1
tagged with: web-scraping
tagged with: python-requests
type: Question
has comment: http://stackoverflow.com/comment/88848731
has body: I am trying to build a simple terminal app to search stuff online through the terminal. When I submit get requests through the library, I get very large wall times. I can't seem to pinpoint the problem. Its fast when I directly type into the browser. I have already skipped proxies in my script file (not shown here). The question has already been closed on requests as it is not a bug in requests according to peers. In [ 1 ]: import requests In [ 2 ]: %%time ...: response = requests.get('http://en.wikipedia.org') ...: CPU times: user 123 ms, sys: 11.9 ms, total: 135 ms Wall time: 4min 22s
upvote count: 1
answer count: 1

http://stackoverflow.com/comment/88952994
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50975545
has text: @VenkataGogu Sorry! I didn't know you could only accept one answer at a time
score: 0

http://stackoverflow.com/a/56105202
has body: The accepted answer does not work for me because my query set logic on listing breaks detail and delete endpoints. Instead I pasted the list implementation and tweaked the logic to my needs class MyViewSet(viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) serializer_class = MySerializer filter_fields = ["a_id", "b_id"] def get_queryset(self): return My.objects.all() def list(self, request): # my custom query set logic a = self.request.query_params.get("a_id", None) b = self.request.query_params.get("b_id", None) if a is None and b is None: queryset = My.objects.none() else: queryset = My.objects.all() # end custom page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) See http://www.cdrf.co/3.9/rest_framework.viewsets/ModelViewSet.html
type: Answer
answers question: http://stackoverflow.com/q/50878730
upvote count: 1
score: 1
downvote count: 0

http://stackoverflow.com/q/50951274
tagged with: pandas
has comment: http://stackoverflow.com/comment/88900736
has answer: http://stackoverflow.com/a/50951623
score: -1
favorite count: 0
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88900700
accepted answer: http://stackoverflow.com/a/50951623
downvote count: 1
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/50951652
answer count: 2
tagged with: time-series
upvote count: 0
has body: I have a time series of events that spans multiple days-I'm mostly interested in counts/10min interval. So currently, after resampling, it looks like this 2018-02-27 16:20:00 5 2018-02-27 16:30:00 4 2018-02-27 16:40:00 0 2018-02-27 16:50:00 0 2018-02-27 17:00:00 0 ... 2018-06-19 05:30:00 0 2018-06-19 05:40:00 0 2018-06-19 05:50:00 1 How can I "fold" this data over to have just one "day" of data, with the counts added up? So it would look something like this 00:00:00 0 00:10:00 0 ... 11:00:00 47 11:10:00 36 11:20:00 12 ... 23:40:00 1 23:50:00 0
has title: Folding pandas time series into single day
possible better answer: http://stackoverflow.com/a/50951652

http://stackoverflow.com/q/50903622
has comment: http://stackoverflow.com/comment/88807234
tagged with: pandas
has answer: http://stackoverflow.com/a/50903736
downvote count: 0
has comment: http://stackoverflow.com/comment/88807075
has body: I have a df like this, df, AAA BBB CCC 0 4 10 100 1 5 20 50 2 6 30 -30 3 7 40 -50 df_mask = pd.DataFrame({'AAA' : [True] * 4, 'BBB' : [False] * 4,'CCC' : [True,False] * 2}) and df.where(df_mask) is AAA BBB CCC 0 4 NaN 100.0 1 5 NaN NaN 2 6 NaN -30.0 3 7 NaN NaN I am trying to extract the non null values like this. I tried, df[df.where(df_mask).notnull()].to_dict() but it gives all the values My expected output is, {'AAA': {0: 4, 1: 5, 2: 6, 3: 7}, 'CCC': {0: 100.0, 2: -30.0}}
favorite count: 0
tagged with: data-analysis
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50903736
possible better answer: http://stackoverflow.com/a/50903772
has answer: http://stackoverflow.com/a/50903772
type: Question
has title: How to extract non NA values in a list or dict from a pandas dataframe
tagged with: dataframe
score: 4
upvote count: 4
answer count: 2

http://stackoverflow.com/comment/88780792
has text: @Solaiman do you have something in your file? i think it is empty
comment on: http://stackoverflow.com/a/50889777
type: AnswerComment
type: Comment
score: 0

http://stackoverflow.com/q/50915593
accepted answer: http://stackoverflow.com/a/50919821
has body: I have a simple flask app with only an index.html page (so far), it's located in a folder with a bunch of javascript and CSS, which makes it a bit difficult to render. I tried listing the file path for my HTML, however, it gives an internal server error, when I open the browser. Should I instead declare the path as a variable and pass that in? I'm on Linux Ubuntu 16.04 btw. here is my sample code: from flask import Flask, render_template app = Flask(__name__) @app.route("/") @app.route("/home") def home(): return render_template('/frontend/index.html') here is how my directory is listed --flaskwebsite ----routes.py ----routes.pyc ----templates ------frontend(other folders, javascript files etc) ------index.html
type: Question
has title: Flask rendering templates from another folder
has comment: http://stackoverflow.com/comment/88831550
tagged with: flask
upvote count: 1
tagged with: http://stackoverflow.com/tag/html
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88832011
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/50919821

http://stackoverflow.com/q/50900301
has title: How to rename columns to get one line of column names?
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/26323926
score: -1
type: Question
has answer: http://stackoverflow.com/a/50900347
accepted answer: http://stackoverflow.com/a/50900347
answer count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/26323926
upvote count: 3
tagged with: pandas
tagged with: python
downvote count: 4
has body: I have this pandas DataFrame df: df.head() windIntensity year month day hour AOBT delay 3 2015 1 1 0 0 0.0 15.0 2 2015 1 1 0 0 0.0 10.0 2 2015 1 1 1 0 0.0 5.0 2 2015 1 1 1 0 0.0 0.0 1 2015 1 1 2 0 0.0 0.0 When I execute this code: df = dfj.groupby(["year","hour"]).agg({'windIntensity':'mean','delay':['mean','count']}).reset_index() I get this result: year hour windIntensity delay mean mean count 0 2015 0 4.239207 24.240373 857 1 2015 1 4.029024 15.770449 758 2 2015 2 3.863928 7.431322 779 3 2015 3 3.859801 4.161290 806 4 2015 4 3.782659 4.722230 6851 But how can I rename columns to get one line of column, not two lines? Expected result: year hour windIntensity_mean delay_mean count 0 2015 0 4.239207 24.240373 857 1 2015 1 4.029024 15.770449 758 2 2015 2 3.863928 7.431322 779 3 2015 3 3.859801 4.161290 806 4 2015 4 3.782659 4.722230 6851

http://stackoverflow.com/comment/88935115
comment on: http://stackoverflow.com/q/50957080
type: Comment
has text: I've added more context. Thanks @BowlingHawk95
score: 0
type: QuestionComment

http://stackoverflow.com/q/50964665
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 2
tagged with: arduino
has title: Python NRF24 convert Payload
type: Question
has comment: http://stackoverflow.com/comment/88932255
has body: since some days I try to connect an Arduino with a Raspberry by an NRF24 module. By the examples i got some working code in C (@raspberry) but I want to use python due to the web app. The problem is I can't interpret the msq send by the Arduino. The Arduino should send 8 times uint32_t in one payload. After receive in Raspberry I got 8 times 4 uint8_t. Arduino MSG: uint32_t SendMsg[8] = {222, micros(), 10, 20, 30, 40, 50, 60}; Raspberry RCV: Received: [222, 0, 0, 0, 24, 22, 97, 210, 10, 0, 0, 0, 20, 0, 0, 0, 30, 0, 0, 0, 40, 0, 0, 0, 50, 0, 0, 0, 60, 0, 0, 0] The Raspberry "destroy" the int32 to 4 times int8 ... how I may combine them again? The RCV is a list of int. Here the complete code: Raspberry: import RPi.GPIO as GPIO from lib_nrf24 import NRF24 import time import spidev GPIO.setmode(GPIO.BCM) pipes = [0xAB, 0xCD, 0xAB, 0xCD, 0x71] radio = NRF24(GPIO, spidev.SpiDev()) radio.begin(0, 22) radio.setPayloadSize(32) radio.setChannel(77) radio.setDataRate(NRF24.BR_1MBPS) radio.setPALevel(NRF24.PA_MIN) radio.setAutoAck(True) radio.enableDynamicPayloads() radio.enableAckPayload() radio.openReadingPipe(1,pipes) radio.printDetails() radio.startListening() while(1): # ackPL = [1] while not radio.available(0): time.sleep(1 / 100) receivedMessage = [] radio.read(receivedMessage, radio.getDynamicPayloadSize()) print("Received: {}".format(receivedMessage)) Arduino //Send.ino #include&lt;SPI.h&gt; #include&lt;RF24.h&gt; // ce, csn pins RF24 radio(6, 10); uint32_t RcvMsg[8] = {0, 0, 0, 0, 0, 0, 0, 0}; void setup(void){ radio.begin(); radio.setPALevel(RF24_PA_MAX); radio.setChannel(77); radio.openWritingPipe(0xABCDABCD71LL); radio.enableDynamicPayloads(); radio.powerUp(); } void loop(void){ const char text[] = "Hello World is awe DOAs"; uint32_t SendMessage; uint32_t SendMsg[8] = {222, micros(), 10, 20, 30, 40, 50, 60}; radio.write(&amp;SendMsg, sizeof(SendMsg)); if ( radio.isAckPayloadAvailable() ) { radio.read(&amp;RcvMsg, sizeof(RcvMsg)); } Serial.print(" SendMsg[0]: ");Ser…
has answer: http://stackoverflow.com/a/51102864
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/89008058
comment on: http://stackoverflow.com/q/51007035
has text: it is for external tft touch screen connected via SPI... so not normal monitor :).
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88901611
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/50951972
has text: does not work unless you declar x/y/z as `global` inside the functions.
type: Comment

http://stackoverflow.com/q/50967223
score: 0
answer count: 1
tagged with: python
has title: Accessing variable from file pyspark
type: UnansweredQuestion
type: Question
tagged with: pyspark
has answer: http://stackoverflow.com/a/50967667
has body: I have one variable.list file. All variables are defined here, like: Tablename="emp" Dbname="hr" Now I want access all these variables from main.py script. I have seen some thread on this where it is suggested to do following. From variable.list import * But it is throwing error that variable.list not defined. No module name variable.list Where to keep variable.list file? How to import all the variables?

jira
tags question: http://stackoverflow.com/q/50881224
tags question: http://stackoverflow.com/q/50916167
tag name: jira
type: Tag

matplotlib
tags question: http://stackoverflow.com/q/50912591
tags question: http://stackoverflow.com/q/50855834
tags question: http://stackoverflow.com/q/50890267
tags question: http://stackoverflow.com/q/51000166
tags question: http://stackoverflow.com/q/50965335
tags question: http://stackoverflow.com/q/50880284
tags question: http://stackoverflow.com/q/50901865
tags question: http://stackoverflow.com/q/50939821
tags question: http://stackoverflow.com/q/50948211
tags question: http://stackoverflow.com/q/50898341
tags question: http://stackoverflow.com/q/50878598
tags question: http://stackoverflow.com/q/50911036
tags question: http://stackoverflow.com/q/50953645
tags question: http://stackoverflow.com/q/50896785
tags question: http://stackoverflow.com/q/50993804
tags question: http://stackoverflow.com/q/50871461
tags question: http://stackoverflow.com/q/51001858
tags question: http://stackoverflow.com/q/50975701
tags question: http://stackoverflow.com/q/50867961
tags question: http://stackoverflow.com/q/50930049
tags question: http://stackoverflow.com/q/50996826
tags question: http://stackoverflow.com/q/50911316
tags question: http://stackoverflow.com/q/50966342
tags question: http://stackoverflow.com/q/50959533
tags question: http://stackoverflow.com/q/50946973
tags question: http://stackoverflow.com/q/50919285
tags question: http://stackoverflow.com/q/50963960
tags question: http://stackoverflow.com/q/50971871
tags question: http://stackoverflow.com/q/50923442
tags question: http://stackoverflow.com/q/50872815
tags question: http://stackoverflow.com/q/50976177
tag name: matplotlib
tags question: http://stackoverflow.com/q/51008008
tags question: http://stackoverflow.com/q/50939065
tags question: http://stackoverflow.com/q/50968838
tags question: http://stackoverflow.com/q/51011187
tags question: http://stackoverflow.com/q/50979020
tags question: http://stackoverflow.com/q/50911478
tags question: http://stackoverflow.com/q/50976260
tags question: http://stackoverflow.com/q/50961057
tags question: http://stackoverflow.com/q/50928942
tags question: http://stackoverflow.com/q/50888397
tags question: http://stackoverflow.com/q/50889973
tags question: http://stackoverflow.com/q/51005829
tags question: http://stackoverflow.com/q/50968217
tags question: http://stackoverflow.com/q/50990947
tags question: http://stackoverflow.com/q/50939778
tags question: http://stackoverflow.com/q/50875637
tags question: http://stackoverflow.com/q/50859183
tags question: http://stackoverflow.com/q/50929202
tags question: http://stackoverflow.com/q/50977764
tags question: http://stackoverflow.com/q/50921345
tags question: http://stackoverflow.com/q/50958913
tags question: http://stackoverflow.com/q/50871343
tags question: http://stackoverflow.com/q/50993314
tags question: http://stackoverflow.com/q/50883784
tags question: http://stackoverflow.com/q/50862920
tags question: http://stackoverflow.com/q/50890518
tags question: http://stackoverflow.com/q/50886030
tags question: http://stackoverflow.com/q/50991674
tags question: http://stackoverflow.com/q/50918400
tags question: http://stackoverflow.com/q/50885312
tags question: http://stackoverflow.com/q/50891952
tags question: http://stackoverflow.com/q/50911227
tags question: http://stackoverflow.com/q/50866373
tags question: http://stackoverflow.com/q/50955112
tags question: http://stackoverflow.com/q/50939900
tags question: http://stackoverflow.com/q/50881017
tags question: http://stackoverflow.com/q/50879760
tags question: http://stackoverflow.com/q/51010200
tags question: http://stackoverflow.com/q/50993194
tags question: http://stackoverflow.com/q/50903919
tags question: http://stackoverflow.com/q/50911722
tags question: http://stackoverflow.com/q/50917216
tags question: http://stackoverflow.com/q/50951790
tags question: http://stackoverflow.com/q/50997997
tags question: http://stackoverflow.com/q/50881652
tags question: http://stackoverflow.com/q/50937470
tags question: http://stackoverflow.com/q/50981514
tags question: http://stackoverflow.com/q/51010142

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

http://stackoverflow.com/a/50954308
has comment: http://stackoverflow.com/comment/88906384
has body: Another way is using groupby and apply df2.groupby('A').apply(lambda x: x[x['B'].isin(['one','two'])]) A B A bar 1 bar one 5 bar two foo 0 foo one 2 foo two 4 foo two 6 foo one
has comment: http://stackoverflow.com/comment/88906434
score: 0
answers question: http://stackoverflow.com/q/50954131
type: Answer

http://stackoverflow.com/comment/88961721
has text: Ah! I see, I just tested it and it confirms what you said. In that case... what could I do to modify the code so that any message that gets sent to `DataHandler` can get routed to the `on_message` method of all the instances of `TestHandler`?
type: Comment
comment on: http://stackoverflow.com/q/50982203
score: 0
type: QuestionComment

http://stackoverflow.com/q/50919752
has title: Can't open jupyter notebook in docker
downvote count: 0
tagged with: jupyter
tagged with: jupyter-notebook
favorite count: 0
has answer: http://stackoverflow.com/a/71122908
score: 5
tagged with: python
type: AnsweredQuestion
tagged with: pytorch
has answer: http://stackoverflow.com/a/50920208
type: Question
upvote count: 5
has comment: http://stackoverflow.com/comment/88839596
possible better answer: http://stackoverflow.com/a/72599711
has body: I am trying to open the jupyter notebook in a container, but I just came cross this situation: [I 10:01:25.051 NotebookApp] The Jupyter Notebook is running at: [I 10:01:25.051 NotebookApp] http://8c1eb91f0492:8888/?token=7671a7abe557349c8d8ad1cbf207702451925efd2c27c84e [I 10:01:25.051 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation). [C 10:01:25.051 NotebookApp] Copy/paste this URL into your browser when you connect for the first time, to login with a token: http://8c1eb91f0492:8888/?token=7671a7abe557349c8d8ad1cbf207702451925efd2c27c84e&amp;token=7671a7abe557349c8d8ad1cbf207702451925efd2c27c84e As you can see the url is the container ID, I tried many solutions, like the ip setting. All don't help at all. Could someone give the hints? Thanks in advance!
has answer: http://stackoverflow.com/a/72599711
tagged with: docker
has comment: http://stackoverflow.com/comment/88839418
answer count: 3
accepted answer: http://stackoverflow.com/a/50920208

http://stackoverflow.com/q/50882808
tagged with: python-3.x
tagged with: installation
score: 0
tagged with: python
answer count: 1
has answer: http://stackoverflow.com/a/50883211
has body: I am trying to install the Python module simplecrypto on a Windows machine. To do this I run the following: C:\Python36\Scripts&gt;pip install simplecrypto However, upon running this partway through the installation process I receive the following error: ... Crypto.PublicKey._fastmath. building 'Crypto.Random.OSRNG.winrandom' extension error: [WinError 3] The system cannot find the path specified: 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\PlatformSDK\\lib' ---------------------------------------- Command "c:\python36\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\EDM-P\\AppData\\Local\\Temp\\pip-build-teqxfnwt\\PyCrypto\\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\EDM-P\AppData\Local\Temp\pip-nrmsip8r-record\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\EDM-P\AppData\Local\Temp\pip-build-teqxfnwt\PyCrypto\ Why is this the case?
type: UnansweredQuestion
has title: Error when Installing simplecrypto on Windows
linked to: http://stackoverflow.com/q/3297254
type: Question

http://stackoverflow.com/q/50998679
tagged with: matlab
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50999158
accepted answer: http://stackoverflow.com/a/50999158
tagged with: image-processing
type: Question
score: 0
answer count: 1
has title: How to convert color grain image to black and white (0,1) so that grain boundary remain identifiable
tagged with: voronoi
has body: I want to convert color image to binary image (0,1) using simple code im2bw(). But in this case grain boundaries are lost or not properly visible I would like to design grain boundary like . Any matlab or python explanation is highly acceptable.
tagged with: python

http://stackoverflow.com/comment/88775497
comment on: http://stackoverflow.com/q/50886889
score: 0
type: Comment
type: QuestionComment
has text: self.tableWidget.setItem(i,j, QTableWidgetItem(cust_data.iloc[i, j]) misses a )

http://stackoverflow.com/q/50954686
tagged with: python
has comment: http://stackoverflow.com/comment/88906983
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50954781
has comment: http://stackoverflow.com/comment/88907187
has answer: http://stackoverflow.com/a/50954824
has answer: http://stackoverflow.com/a/50954781
type: Question
accepted answer: http://stackoverflow.com/a/50954824
score: 0
has title: TypeError: strptime() argument 1 must be str, not list
answer count: 3
has body: I am trying to plot the following data: 01/01/2012 01:00 01/01/2012 02:00 01/01/2012 03:00 01/01/2012 04:00 01/01/2012 05:00 01/01/2012 06:00 01/01/2012 07:00 01/01/2012 08:00 01/01/2012 09:00 01/01/2012 10:00 01/01/2012 11:00 01/01/2012 12:00 01/01/2012 13:00 01/01/2012 14:00 01/01/2012 15:00 01/01/2012 16:00 01/01/2012 17:00 01/01/2012 18:00 01/01/2012 19:00 01/01/2012 20:00 01/01/2012 21:00 01/01/2012 22:00 01/01/2012 23:00 02/01/2012 00:00 04/01/2012 23:00 ................ 05/01/2012 00:00 05/01/2012 01:00 ................ Against wind_speed data which is in the format: [ 3.30049159 2.25226244 1.44078451 ... 12.8397099 9.75722427 7.98525797] My code is: T = T[1:] print( datetime.datetime.strptime(T, "%m/%d/%Y %H:%M:%S").strftime("%Y%m%d %I:%M:%S") #pharsing the time TIMESTAMP = [str (i) for i in T] plt.plot_date(TIMESTAMP, wind_speed) plt.show() However, I am receiving the error message "TypeError: strptime() argument 1 must be str", not list. I am new to Python and would appreciate help on how to either convert to the list to a string or another method on how to resolve this. Thank you!
has comment: http://stackoverflow.com/comment/88907100
tagged with: datetime
has comment: http://stackoverflow.com/comment/88907069
has answer: http://stackoverflow.com/a/50954818
has comment: http://stackoverflow.com/comment/88907036
tagged with: utc

http://stackoverflow.com/q/50888630
has title: simple python regular ex not working
upvote count: 1
has comment: http://stackoverflow.com/comment/88778553
type: Question
has answer: http://stackoverflow.com/a/50888702
accepted answer: http://stackoverflow.com/a/50888791
downvote count: 4
answer count: 3
has body: Try to regex phone numbers, can't get it to work and don't see what's wrong with my regular expression. here is the code i'm running: import re text = 'random text 058-6959503 -' cellular = re.findall(r'/^05\d([-]{0,1})\d{7}$/',text ) print(cellular) it returns nothing. help?
favorite count: 0
possible better answer: http://stackoverflow.com/a/50888682
has answer: http://stackoverflow.com/a/50888682
score: -3
tagged with: python
tagged with: regex
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50888791

http://stackoverflow.com/comment/88992056
has text: Your function doesn't return anything, it only prints. So, first think about whether that is right and whether it should return or yield anything and what that should be. Please also upgrade to Python 3 right away, starting to learn the old Python 2 will partially be a waste of time.
comment on: http://stackoverflow.com/q/50998880
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50999564
type: Answer
downvote count: 0
has body: import sqlite3 import pandas as pd # Create the connection cnx = sqlite3.connect(r'C:\mydatabases\bigdata.db') # create the dataframe from a query df = pd.read_sql_query("SELECT * FROM userdata", cnx)
upvote count: 8
score: 8
answers question: http://stackoverflow.com/q/50996820

http://stackoverflow.com/a/50900332
has comment: http://stackoverflow.com/comment/88826681
downvote count: 0
has body: Scipy's shift function from scipy.ndimage.interpolation is what you are looking for, as long as the grid spacings between data and frame overlap. If not, look to the other answer. The shift function can take floating point numbers as input and will do a spline interpolation. First, I put the data into an array as large as frame, then shift it, and then add it. Make sure to reverse the coordinate list, as x is the rightmost dimension in numpy arrays. One of the nice features of shift is that it sets to zero those values that go out of bounds. import numpy as np import matplotlib.pyplot as plt from scipy.ndimage.interpolation import shift # A gaussian to add to the frame. x, y = np.meshgrid(np.linspace(-1,1,10), np.linspace(-1,1,10)) data = 50*np.exp(-np.sqrt(x**2+y**2)**2) # The frame to add the gaussian to frame = np.random.normal(size=(100,50)) x_frame = np.arange(50) y_frame = np.arange(100) # The desired (x,y) location of the gaussian center on the new frame. coords = np.array([23.4, 22.6]) # First, create a frame as large as the frame. data_large = np.zeros(frame.shape) data_large[:data.shape[0], :data.shape[1]] = data[:,:] # Subtract half the distance as the bottom left is at 0,0 instead of the center. # The shift of 4.5 is because data is 10 points wide. # Reverse the coords array as x is the last coordinate. coords_shift = -4.5 data_large = shift(data_large, coords[::-1] + coords_shift) frame += data_large # Plot the result and add lines to indicate to coordinates plt.figure() plt.pcolormesh(x_frame, y_frame, frame, cmap=plt.cm.jet) plt.axhline(coords[1], color='w') plt.axvline(coords[0], color='w') plt.colorbar() plt.gca().invert_yaxis() plt.show() The script gives you the following figure, which has the desired coordinates indicated with white dotted lines.
has comment: http://stackoverflow.com/comment/88808353
answers question: http://stackoverflow.com/q/50881318
upvote count: 2
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/88808275

divide-and-conquer
tags question: http://stackoverflow.com/q/50886890
type: Tag
tag name: divide-and-conquer
tags question: http://stackoverflow.com/q/51003564

http://stackoverflow.com/a/50946087
upvote count: 10
type: AcceptedAnswer
score: 10
downvote count: 0
has body: Probably the event queue fills up and so the window won't react to events from your operating system/window manager. Make sure to call pygame.event.get() (or pygame.event.pump) in your game loop. From pygame.event.pump: For each frame of your game, you will need to make some sort of call to the event queue. This ensures your program can internally interact with the rest of the operating system. If you are not using other event functions in your game, you should call pygame.event.pump() to allow pygame to handle internal actions. This function is not necessary if your program is consistently processing events on the queue through the other pygame.event functions. There are important things that must be dealt with internally in the event queue. The main window may need to be repainted or respond to the system. If you fail to make a call to the event queue for too long, the system may decide your program has locked up.
type: Answer
accepted answer of: http://stackoverflow.com/q/50945295
answers question: http://stackoverflow.com/q/50945295

http://stackoverflow.com/comment/96613271
has text: Does NOT install on MacOS 10.13.6, Python 3.7.2.
comment on: http://stackoverflow.com/a/52724994
type: Comment
score: 3
type: AnswerComment

http://stackoverflow.com/q/50986580
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/88968027
has title: Using keras but got Error AttributeError: 'Tensor' object has no attribute '_keras_history'
tagged with: deep-learning
upvote count: 1
answer count: 1
tagged with: keras
has comment: http://stackoverflow.com/comment/88968213
favorite count: 0
has body: I am currently using keras to implement an autoencoder in order to upsampling images. The idea is that I want to use the information of the neighboring images to create an upsampled center image. Both the vertical and horizontal neighbors should share the weights in the encoder. At the bottle neck the vertical and horizontal image patches were concatenated and begin the decoding. Here is the code: from keras.models import Model from keras.layers import Input, Concatenate from keras.layers import Conv3D, Conv3DTranspose, Conv2DTranspose from keras.utils import np_utils from keras import backend as K # number of feature maps L = 16 L0 = 24 L1 = 2*L #32 L2 = 4*L #64 L3 = 6*L #96 # input layers input_LF_v = Input(shape=[5,12,12,3]) input_LF_h = Input(shape=[5,12,12,3]) # 5x12x12 # Encoding path encoded_1 = Conv3D(L0,(3,3,3),strides=(1, 1, 1),input_shape=[5, 12, 12, 3], padding='SAME',data_format="channels_last") encoded_2 = Conv3D(L0,(3,3,3),strides=(1, 1, 1),padding='SAME',data_format="channels_last") encoded_3 = Conv3D(L1,(3,3,3),strides=(1, 2, 2),padding='SAME',data_format="channels_last") # now 5x6x6 encoded_4 = Conv3D(L1,(3,3,3),strides=(1, 1, 1),padding='SAME',data_format="channels_last") encoded_5 = Conv3D(L1,(3,3,3),strides=(1, 1, 1),padding='SAME',data_format="channels_last") encoded_6 = Conv3D(L2,(3,3,3),strides=(1, 2, 2),padding='SAME',data_format="channels_last") # now 5x3x3 encoded_v1 = encoded_1(input_LF_v) encoded_v2 = encoded_2(encoded_v1) encoded_v3 = encoded_3(encoded_v2) encoded_v4 = encoded_4(encoded_v3) encoded_v5 = encoded_5(encoded_v4) encoded_v6 = encoded_6(encoded_v5) encoded_h1 = encoded_1(input_LF_h) encoded_h2 = encoded_2(encoded_h1) encoded_h3 = encoded_3(encoded_h2) encoded_h4 = encoded_4(encoded_h3) encoded_h5 = encoded_5(encoded_h4) encoded_h6 = encoded_6(encoded_h5) # skip paths encoded_vh2 = Concatenate()([encoded_v2,encoded_h2]) # 5x12x12x48 encoded_vh5 = Concatenate()([encoded_v5,encoded_h5]) # 5x6x6x64 # bottle neck of encoder encode…
tagged with: python
accepted answer: http://stackoverflow.com/a/50990718
type: AnsweredQuestion
downvote count: 0
tagged with: autoencoder
score: 1
has answer: http://stackoverflow.com/a/50990718

http://stackoverflow.com/comment/88860353
score: 1
has text: Thank you for referring. @Mr.T . That solved my problem.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50930280

http://stackoverflow.com/q/50923923
tagged with: machine-learning
type: Question
has answer: http://stackoverflow.com/a/50924588
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/88848417
answer count: 1
has body: I have trained an PassiveAggressiveClassifier with a set of 165 categories. Now I can already use it to predict certain inputs but it fails sometimes and it would be very helpful know how "confident" is the classifier on each prediction and what are the other considerations. As far as I understand I get the distances for each category using decision_function distances = np.array(ppl.decision_function(sample)) which gives me something like this for the distances: [-1.4222 -1.5083 -2.6488 -2.3428 -1.3167 -3.9615 -2.7804 -1.9563 -0.5054 -1.9524 -3.0026 -3.422 -2.1301 -2.0119 -2.1381 -2.2186 -2.0848 -2.4514 -1.9478 -2.3101 -2.4044 -1.9155 -1.569 -1.31 -1.4865 -2.3251 -1.7773 -1.304 -1.5215 -2.0634 -1.6987 -1.9217 -2.2863 -1.8166 -2.0219 -1.9594 -1.747 -2.1503 -2.162 -1.9507 -1.5971 -3.4499 -1.8946 -2.4328 -2.2415 -1.9045 -2.065 -1.9671 -1.8592 -1.6283 -1.7626 -2.2175 -2.1725 -3.7855 -5.1397 -3.6485 -4.4072 -2.2109 -2.048 -2.4887 -2.2324 -2.7897 -1.2932 -1.975 -1.516 -1.6127 -1.7135 -1.8243 -1.4887 -2.8973 -1.9656 -2.2236 -2.2466 -2.1224 -1.2247 -1.9657 -1.6138 -2.7787 -1.5004 -2.0136 -1.1001 -1.7226 -1.5829 -2.0317 -1.0834 -1.7444 -1.356 -2.3453 -1.7161 -2.2683 -2.2725 -0.4512 -4.5038 -2.0386 -2.1849 -2.4256 -1.5678 -1.8114 -2.2138 -2.2654 -1.8823 -2.7489 -1.8477 -2.1383 -1.6019 -2.84 -2.2595 -2.0764 -1.6758 -2.4279 -2.3489 -2.1884 -2.1888 -1.6289 -1.7358 -1.2989 -1.5656 -1.3362 -1.888 -2.1061 -1.4517 -2.0572 -2.4971 -2.2966 -2.6121 -2.4728 -2.8977 -1.7571 -2.4363 -1.4775 -1.7144 -2.047 -3.9252 -1.9907 -2.1808 -2.066 -1.9862 -1.4898 -2.3335 -2.6088 -2.4554 -2.4139 -1.7187 -2.2909 -1.4846 -1.8696 -2.444 -2.6253 -1.7738 -1.7192 -1.8737 -1.9977 -1.9948 -1.7667 -2.0704 -3.0147 -1.9014 -1.7713 -2.2551] Now I have two questions: 1st whether it is possible to map the distances back to the categories since the length of the array (159) does not match my categories array. 2nd how can I calculate a confidence for the single prediction using the distances?
tagged with: scikit-learn
accepted answer: http://stackoverflow.com/a/50924588
has title: Extracting confidence from scikit PassiveAggressiveClassifier() for single prediction
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88847564

http://stackoverflow.com/a/50903736
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/88808383
has comment: http://stackoverflow.com/comment/88808134
has comment: http://stackoverflow.com/comment/88808326
accepted answer of: http://stackoverflow.com/q/50903622
has comment: http://stackoverflow.com/comment/88808074
answers question: http://stackoverflow.com/q/50903622
has comment: http://stackoverflow.com/comment/88808196
score: 2
has body: Let's use agg here: v = df.where(df_mask).agg(lambda x: x.dropna().to_dict()) On older versions, apply does the same thing (albeit a bit slower). v = df.where(df_mask).apply(lambda x: x.dropna().to_dict()) And now, filter out rows with empty dictionaries for the final step: res = v[v.str.len() &gt; 0].to_dict() print(res) {'AAA': {0: 4.0, 1: 5.0, 2: 6.0, 3: 7.0}, 'CCC': {0: 100.0, 2: -30.0}} Another apply-free option is a dict-comprehension: v = df.where(df_mask) res = {k : v[k].dropna().to_dict() for k in df} print(res) {'AAA': {0: 4, 1: 5, 2: 6, 3: 7}, 'BBB': {}, 'CCC': {0: 100.0, 2: -30.0}} Note that this (slightly) simpler solution retains keys with empty values.
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88807257

http://stackoverflow.com/a/50982165
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/88968553
has body: try this, import pandas as pd import numpy as np df1=pd.DataFrame(np.random.randint(1,100,size=(18,40))) df1_cols=df1.columns.values req_cols= sum([[col]*3 if col%4!=0 else [col] for col in df1_cols],[]) res=pd.concat(df2,df1[req_cols]) # req_cols: [0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 8, 9, 9, 9, 10, 10, 10, 11, 11, 11, 12, 13, 13, 13, 14, 14, 14, 15, 15, 15, 16, 17, 17, 17, 18, 18, 18, 19, 19, 19, 20, 21, 21, 21, 22, 22, 22, 23, 23, 23, 24, 25, 25, 25, 26, 26, 26, 27, 27, 27, 28, 29, 29, 29, 30, 30, 30, 31, 31, 31, 32, 33, 33, 33, 34, 34, 34, 35, 35, 35, 36, 37, 37, 37, 38, 38, 38, 39, 39, 39] Explanation: You need to first take a columns into list. then repeat column into 3 times when %4!=0 for your problem. so req_cols contains a columns which you required. then slice this from df1. Finally to copy contents merge with df2. you will get a desired result successfully.
answers question: http://stackoverflow.com/q/50981228
downvote count: 0
score: 1

http://stackoverflow.com/a/51005939
has comment: http://stackoverflow.com/comment/89006194
score: 1
has comment: http://stackoverflow.com/comment/89006186
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51005926
has comment: http://stackoverflow.com/comment/89006103
has comment: http://stackoverflow.com/comment/89005966
has body: "Merge" these DataFrames using pd.concat. df3 = (pd.concat([budgetedDF, actualDF]) .sort_index() .reset_index(drop=True) ) df3 amount category months 0 2183 budgeted 2018-01-31 1 3612 actual 2018-01-31 2 8902 budgeted 2018-02-28 3 3357 actual 2018-02-28 4 9956 budgeted 2018-03-30 5 2828 actual 2018-03-30 6 14475 budgeted 2018-04-30 7 2990 actual 2018-04-30 8 25385 budgeted 2018-05-31 9 4446 actual 2018-05-31 10 19119 actual 2018-06-29 11 29119 budgeted 2018-06-29 12 27296 actual 2018-07-31 13 40869 budgeted 2018-07-31 14 38443 actual 2018-08-31 15 43400 budgeted 2018-08-31 16 47978 actual 2018-09-28 17 52686 budgeted 2018-09-28 18 49612 actual 2018-10-31 19 63384 budgeted 2018-10-31 20 49272 actual 2018-11-30 21 74107 budgeted 2018-11-30 22 83653 budgeted 2018-12-31 23 56907 actual 2018-12-31 However, you might prefer this representation instead: df3 = (pd.concat([budgetedDF, actualDF]) .drop('months', 1) .set_index('category', append=True) .unstack() ) df3 amount category actual budgeted 2018-01-31 3612 2183 2018-02-28 3357 8902 2018-03-30 2828 9956 2018-04-30 2990 14475 2018-05-31 4446 25385 2018-06-29 19119 29119 2018-07-31 27296 40869 2018-08-31 38443 43400 2018-09-28 47978 52686 2018-10-31 49612 63384 2018-11-30 49272 74107 2018-12-31 56907 83653
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51005926

http://stackoverflow.com/q/50951033
type: Question
accepted answer: http://stackoverflow.com/a/50952062
has comment: http://stackoverflow.com/comment/88900451
tagged with: sorting
score: 0
tagged with: max
has body: I am trying to find the file with the largest number in the filename in each subdirectory. This is so I can acomplish opening the most recent file in each subdirectory. Each file will follow the naming convetion of date filename.xlsx. Ex. 20180620 file name.xlsx I have a code that works for searching one directory for largest numbers. dirname = py.path.local(path) list_of_files = [] for file in dirname.visit(fil='*.xlsx', bf=True): list_of_files.append(file) largest = max(list_of_files) print (largest) I am pretty new to Python and I can't quite figure out how to make this style of code work looking for the file with the largest number in each subdirectory within a directory. I have tried many variations off of this following code, but I can't get it to print out just the file with the largest number from each subdirectory. list_of_files = [] for root, dirs, files in os.walk(path): for name in files: if name.endswith((".xlsx")): list_of_files.append(files) largest = max(list_of_files) print (largest) Any help would be greatly appreciated!
answer count: 1
has title: Find file with largest number in filename in each sub-directory with python?
tagged with: arrays
has comment: http://stackoverflow.com/comment/88900559
has answer: http://stackoverflow.com/a/50952062
tagged with: python
type: AnsweredQuestion

opencv
tags question: http://stackoverflow.com/q/50870189
type: Tag
tags question: http://stackoverflow.com/q/50913339
tags question: http://stackoverflow.com/q/50967808
tags question: http://stackoverflow.com/q/50950588
tags question: http://stackoverflow.com/q/51006008
tags question: http://stackoverflow.com/q/50892153
tags question: http://stackoverflow.com/q/50881585
tags question: http://stackoverflow.com/q/50856449
tags question: http://stackoverflow.com/q/51005083
tags question: http://stackoverflow.com/q/51002881
tags question: http://stackoverflow.com/q/50972401
tags question: http://stackoverflow.com/q/50924974
tags question: http://stackoverflow.com/q/50857278
tags question: http://stackoverflow.com/q/50947010
tags question: http://stackoverflow.com/q/50948658
tags question: http://stackoverflow.com/q/50987324
tags question: http://stackoverflow.com/q/50901786
tags question: http://stackoverflow.com/q/50881207
tags question: http://stackoverflow.com/q/50939323
tags question: http://stackoverflow.com/q/50963283
tags question: http://stackoverflow.com/q/50937982
tags question: http://stackoverflow.com/q/50882663
tags question: http://stackoverflow.com/q/50863397
tags question: http://stackoverflow.com/q/50855076
tags question: http://stackoverflow.com/q/50922175
tags question: http://stackoverflow.com/q/50945385
tags question: http://stackoverflow.com/q/50909569
tags question: http://stackoverflow.com/q/51009135
tags question: http://stackoverflow.com/q/50885585
tags question: http://stackoverflow.com/q/50894377
tags question: http://stackoverflow.com/q/50883330
tags question: http://stackoverflow.com/q/50957151
tags question: http://stackoverflow.com/q/50966412
tags question: http://stackoverflow.com/q/50900423
tags question: http://stackoverflow.com/q/50895717
tags question: http://stackoverflow.com/q/50939402
tags question: http://stackoverflow.com/q/50881756
tags question: http://stackoverflow.com/q/50948054
tags question: http://stackoverflow.com/q/51009126
tags question: http://stackoverflow.com/q/50995950
tags question: http://stackoverflow.com/q/50907220
tags question: http://stackoverflow.com/q/51009991
tag name: opencv
tags question: http://stackoverflow.com/q/50990627
tags question: http://stackoverflow.com/q/50985319
tags question: http://stackoverflow.com/q/51007129
tags question: http://stackoverflow.com/q/50910945
tags question: http://stackoverflow.com/q/50900249
tags question: http://stackoverflow.com/q/50988192
tags question: http://stackoverflow.com/q/50948655
tags question: http://stackoverflow.com/q/50938738
tags question: http://stackoverflow.com/q/50935330
tags question: http://stackoverflow.com/q/50989759
tags question: http://stackoverflow.com/q/50920685
tags question: http://stackoverflow.com/q/50988223
tags question: http://stackoverflow.com/q/50889958
tags question: http://stackoverflow.com/q/50966725
tags question: http://stackoverflow.com/q/51001356
tags question: http://stackoverflow.com/q/50916903
tags question: http://stackoverflow.com/q/50858778
tags question: http://stackoverflow.com/q/51007536
tags question: http://stackoverflow.com/q/50882971
tags question: http://stackoverflow.com/q/50876292
tags question: http://stackoverflow.com/q/50870405
tags question: http://stackoverflow.com/q/50899692
tags question: http://stackoverflow.com/q/50972987
tags question: http://stackoverflow.com/q/50902490
tags question: http://stackoverflow.com/q/50873319
tags question: http://stackoverflow.com/q/50909993
tags question: http://stackoverflow.com/q/50912978
tags question: http://stackoverflow.com/q/50966269
tags question: http://stackoverflow.com/q/50889501
tags question: http://stackoverflow.com/q/50880850
tags question: http://stackoverflow.com/q/50906708
tags question: http://stackoverflow.com/q/50926151
tags question: http://stackoverflow.com/q/50957574
tags question: http://stackoverflow.com/q/50907540
tags question: http://stackoverflow.com/q/50921967
tags question: http://stackoverflow.com/q/50983996

http://stackoverflow.com/q/50991076
type: UnansweredQuestion
tagged with: python
has body: I was trying to understand how DataLoader works. This is how I applied it: # DATASET class Word2VecDataset(torch_data.Dataset): def __init__(self, vocabulary): super(Word2VecDataset, self).__init__() self.data_list = [] self.vocab = vocabulary self.generate_batch_list() def __getitem__(self, index): return self.data_list[index] def __len__(self): return len(self.data_list) def generate_batch_list(self): training_data = self.vocab.get_training_phrases() for query in training_data.Query: query = utils.skip_gram_tokenize(vocab=self.vocab, sentence=query) for entry in query: self.data_list.append(entry) for response in training_data.Response: response = utils.skip_gram_tokenize(vocab=self.vocab, sentence=response) for entry in response: self.data_list.append(entry) And this is the actual dataloader part: dataset = Word2VecDataset(self.vocab) data_loader = torch_data.DataLoader(dataset, self.batch_size, True, num_workers=4) print('Model Initialized') for epo in range(self.num_epochs): loss_val = None for i_batch, sample_batched in enumerate(data_loader): # This seems to be causing issues. For some reason this is the part that 'reboots' the whole model, making it print twice (more info under the code) loss_val = 0 for data, target in sample_batched: .... Now, weirdly enough both the initialization phase (which you don't see here) that says 'This is the gpu detected: xxx', and the print('Model Initialized') get printed two times. Finally here (pastebin) is the full console log (with the error).
score: 1
has title: Broken Pipe in pytorch DataLoader
type: Question
upvote count: 2
answer count: 1
favorite count: 0
downvote count: 1
has answer: http://stackoverflow.com/a/58233444
tagged with: pytorch

http://stackoverflow.com/comment/88782748
type: AnswerComment
type: Comment
has text: If you could provide some test data, I would be able to check where the issue is hiding.
comment on: http://stackoverflow.com/a/50889747
score: 0

http://stackoverflow.com/comment/88856140
comment on: http://stackoverflow.com/a/50928583
type: Comment
has text: Thanks, anonymous downvoter. Would you care to explain why you think this answer is unsuitable?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88980398
has text: Is it mandatory that the LSTM input is the CNN output? I know of image-to-caption decoders that do not operate on the CNN output but rather simply condition on it.
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/50992840

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

http://stackoverflow.com/q/51003647
tagged with: templates
has comment: http://stackoverflow.com/comment/89001886
has answer: http://stackoverflow.com/a/69378239
type: UnansweredQuestion
upvote count: 1
tagged with: python
tagged with: jinja2
has comment: http://stackoverflow.com/comment/89000936
has answer: http://stackoverflow.com/a/53571961
has comment: http://stackoverflow.com/comment/89001185
has comment: http://stackoverflow.com/comment/89001206
score: 1
has title: jinja2.exceptions.TemplateNotFound: hello.html
has comment: http://stackoverflow.com/comment/89001808
type: Question
linked to: http://stackoverflow.com/q/23327293
has body: My project structure is as below : flask-blog/ application.py templates/ home.html My templates folder is also correctly named. I don't understand where the issue is! File "C:\Users\Aswathi\Anaconda3\lib\site-packages\flask\app.py", line 1799, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "C:\project\application.py", line 6, in hello return render_template('hello.html') File "C:\Users\Aswathi\Anaconda3\lib\site-packages\flask\templating.py", line 134, in render_template return _render(ctx.app.jinja_env.get_or_select_template(template_name_or_list), File "C:\Users\Aswathi\Anaconda3\lib\site-packages\jinja2\environment.py", line 869, in get_or_select_template return self.get_template(template_name_or_list, parent, globals) File "C:\Users\Aswathi\Anaconda3\lib\site-packages\jinja2\environment.py", line 830, in get_template return self._load_template(name, self.make_globals(globals)) File "C:\Users\Aswathi\Anaconda3\lib\site-packages\jinja2\environment.py", line 804, in _load_template template = self.loader.load(self, name, globals) File "C:\Users\Aswathi\Anaconda3\lib\site-packages\jinja2\loaders.py", line 113, in load source, filename, uptodate = self.get_source(environment, name) File "C:\Users\Aswathi\Anaconda3\lib\site-packages\flask\templating.py", line 58, in get_source return self._get_source_fast(environment, template) File "C:\Users\Aswathi\Anaconda3\lib\site-packages\flask\templating.py", line 86, in _get_source_fast raise TemplateNotFound(template) jinja2.exceptions.TemplateNotFound: hello.html
downvote count: 0
has answer: http://stackoverflow.com/a/61226575
favorite count: 0
has comment: http://stackoverflow.com/comment/89001488
has comment: http://stackoverflow.com/comment/89001648
answer count: 3
has comment: http://stackoverflow.com/comment/89001264

http://stackoverflow.com/comment/88830475
comment on: http://stackoverflow.com/q/50900148
type: QuestionComment
has text: Yes I am trying this on MNIST and the accuracy varies around .09 to .11 which means (and I've checked), it's all predicted outputs are same. @David
score: 0
type: Comment

http://stackoverflow.com/comment/88762530
has text: Thanks. Adding `--process-dependency-links` indeed makes one step closer to the solution, but it still causes the same error due to the unrecognized link format. I just figured out that adding `git+` and 'the dependency version' makes it correct. I edited the answer a little bit so that it can be accepted.
comment on: http://stackoverflow.com/a/50878879
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/a/50969037
type: Answer
answers question: http://stackoverflow.com/q/50950953
upvote count: 5
has body: You can also use a compiler like Numba to do this job. This would also outperform the vectorized solution and doesn't need a temporary array. Example import numba as nb import numpy as np import pandas as pd import time @nb.njit(fastmath=True,parallel=True,error_model='numpy') def your_function(df1_in,df1_out,df1_vals,df2_in,df2_out,df2_vals): sum=0. for i in nb.prange(len(df1_in)): for j in range(len(df2_in)): if (df1_in[i] &lt;= df2_out[j] and df1_out[i] &gt;= df2_in[j]): sum+=df1_vals[i]*df2_vals[j] return sum Testing dict1 = {'vals': np.random.randint(1, 100, 1000), 'in': np.random.randint(1, 10, 1000), 'out': np.random.randint(1, 10, 1000)} df1 = pd.DataFrame(data=dict1) dict2 = {'vals': np.random.randint(1, 100, 1500), 'in': 5*np.random.random(1500), 'out': 5*np.random.random(1500)} df2 = pd.DataFrame(data=dict2) # First call has some compilation overhead res=your_function(df1['in'].values, df1['out'].values, df1['vals'].values, df2['in'].values, df2['out'].values, df2['vals'].values) t1 = time.time() for i in range(1000): res = your_function(df1['in'].values, df1['out'].values, df1['vals'].values, df2['in'].values, df2['out'].values, df2['vals'].values) print(time.time() - t1) Timings vectorized solution @AGN Gazer: 9.15ms parallelized Numba Version: 0.7ms
score: 5
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50950953
has comment: http://stackoverflow.com/comment/89158764

http://stackoverflow.com/comment/88980476
has text: Yeah, your while loop worked (after being properly indented)
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50992038

http://stackoverflow.com/a/50994187
answers question: http://stackoverflow.com/q/50993810
type: Answer
has body: Try: {% with article=post.article|safe %} {% endwith %}
score: 0

http://stackoverflow.com/comment/88887016
comment on: http://stackoverflow.com/a/50922784
has text: Yeah I’ve tried that too. I think fieldsets overrides custom forms. So I’ve gotta write in my fieldsets into a form
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/88733694
type: AnswerComment
type: Comment
has text: @LucasDresl but if you do `drop_duplicates(['id'],keep='last')` you will ends up with one row for each id. Of what I understand of the quetion, the OP wants to keep two rows for id=2 as they have the same value in some_type and some_date :)
comment on: http://stackoverflow.com/a/50865442
score: 0

http://stackoverflow.com/a/50954884
has body: The portaudio library that Homebrew installs appears to be a C and C++ library only, not Python.
type: Answer
answers question: http://stackoverflow.com/q/50954833
score: 0
has comment: http://stackoverflow.com/comment/88916306

http://stackoverflow.com/a/50979122
has body: You have to return a value from a function using "return". Otherwise the default is to return None. You're not returning anything from calculate_palindrome.
upvote count: 1
answers question: http://stackoverflow.com/q/50979114
downvote count: 0
score: 1
type: Answer

http://stackoverflow.com/a/50949803
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50949646
upvote count: 1
downvote count: 1
has body: Use: for yielded in generators: for _yielded in yielded: if isinstance(_yielded, ValueError): value_errors.append(_yielded)

http://stackoverflow.com/comment/88837640
has text: I'll be sure to look at that tutorial. Thanks again
comment on: http://stackoverflow.com/a/50918304
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/69842793
downvote count: 0
has body: Yes, they do give different results. And I think you should trust the results from scipy, and reject the results from sklearn. But let me provide details of my reasoning, because I could be wrong. I lately observed a similar effect to what you describe, with a data set of 300 data points: the results of the two chi2 implementations differ indeed. In my case the difference was striking. I described the issue in details in this article , followed by this Cross Validated discussion thread and I also submitted a bug request to sklearn, available for review here. The added value from my research, if any, seems to be that the results delivered by the scipy implementation seem correct, while the results from sklearn are incorrect. Please see the article for the details. But I only focused on my sample, so the conclusion may not be universally true. Sadly the source code analysis is beyond my capability, but I hope this input can help someone to possibly either improve the code, or disprove my reasoning if wrong.
upvote count: 3
answers question: http://stackoverflow.com/q/50932433
type: Answer
score: 3

http://stackoverflow.com/comment/88821234
comment on: http://stackoverflow.com/q/50910558
score: 0
type: Comment
has text: This is pygybu `https://github.com/alejandroautalan/pygubu`, it is a Rapid Application Development tool for tkinter. Saves lots of time
type: QuestionComment

http://stackoverflow.com/a/61897381
type: Answer
has body: The problem with what you are doing is that you are passing 3 parameters instead of 2 to the "shape" argument. A perspective transform is performed on a gray-scale image which has shape as (H,W). A RGB image has shape (H,W,3) where the last dimension shows the number of channels--red, green and blue. Try with gray-scale image and no errors will be there :) Edit : Just saw the date. Guess I am too late :P
answers question: http://stackoverflow.com/q/50947010
score: 0

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

http://stackoverflow.com/a/60970537
type: Answer
answers question: http://stackoverflow.com/q/50971869
has body: I'm not sure if I understand your question correctly, but I think you are looking for: go.Bar( x=['April Sales'], y=df[(df['TYPE'] == typePicker) &amp; (df['IND'] == indPicker)]['April_sales'] )
score: 0

http://stackoverflow.com/q/51002866
has title: unable to add image binary into multipart/form-data
upvote count: 3
has body: I received an error: expected str instance, bytes found when i tried to add image binary into multipart/form-data. The problem is i tried to append the imageData in binary format to strings. Is there a way to add binary image to multipart/form data? I'm at my wits end, would appreciate some help for this. imageData = request.FILES['filePath'].read() content_type, request_body = encode_multipart_formdata([('include_target_data', targetMetaDataRet), ('max_num_results', str(maxNoResultRet))], [('image', imagePath, imageData)]) def encode_multipart_formdata(fields, files): BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$' CRLF = '\r\n' lines = [] for (key, value) in fields: lines.append('--' + BOUNDARY) lines.append('Content-Disposition: form-data; name="%s"' % key) lines.append('') lines.append(value) for (key, filename, value) in files: lines.append('--' + BOUNDARY) lines.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename)) lines.append('Content-Type: %s' % get_content_type(filename)) lines.append('') lines.append(value) lines.append('--' + BOUNDARY + '--') lines.append('') body = CRLF.join(lines) content_type = 'multipart/form-data; boundary=%s' % BOUNDARY return content_type, body Traceback: 35. response = get_response(request) 128. response = self.process_exception_by_middleware(e, request) 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) 166. [('image', imagePath, imageData)]) 232. body = CRLF.join(lines) Exception Type: TypeError at /identify_shrine Exception Value: sequence item 12: expected str instance, bytes found as per @coltoneakins request I modified request body to bytes, but I seem to be getting a bad request error any idea why? Code: content_type = 'multipart/form-data; boundary=----------ThIs_Is_tHe_bouNdaRY_$' request_body = '----------ThIs_Is_tHe_bouNdaRY_$' + '\n'+'Content-Disposition: form-data; name="include_target_data"' + '\n' + '\n' + 'top'+ '\n' + '----------ThIs_Is_tHe_bouNdaRY_$' +'\n' …
type: Question
has comment: http://stackoverflow.com/comment/89005316
linked to: http://stackoverflow.com/q/16958448
score: 3
has answer: http://stackoverflow.com/a/51003723
linked to: http://stackoverflow.com/q/12385179
has comment: http://stackoverflow.com/comment/89010288
answer count: 1
tagged with: multipartform-data
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/89000177
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51003723
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/50945999
upvote count: 3
tagged with: xlsxwriter
type: Question
has answer: http://stackoverflow.com/a/66976974
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/50950555
has comment: http://stackoverflow.com/comment/88889355
has body: when I write an image to an excel file, I need to make the image fit one excel cell. I know the size(in pixel) of the image, but I have no idea how to use xlsxwriter to adjust the height and width of the excel cell so that my image fits the cell perfectly.
has comment: http://stackoverflow.com/comment/118606093
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: resize excel cell to fit an image
tagged with: excel
score: 3

http://stackoverflow.com/q/51005244
has title: How can I preserve the data type of a column when using pandas.read_sas()?
has comment: http://stackoverflow.com/comment/89004201
score: 0
has comment: http://stackoverflow.com/comment/89005949
has answer: http://stackoverflow.com/a/51005427
tagged with: pandas
has answer: http://stackoverflow.com/a/51006266
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has body: All column types are converted to floats (column type is not preserved) when read from this SAS file into a pandas dataframe. Following is the Python code: import os import pandas as pd data_dir = os.getcwd() sas_file = os.path.join(data_dir, 'airline.sas7bdat') iter_sas = pd.read_sas(sas_file, iterator=True, chunksize=1000) for chunk in iter_sas: print(chunk.head()) Outputting the following: YEAR Y W R L K 0 1948.000888 1.214 0.243 0.1454 1.415 0.612 1 1949.000888 1.354 0.260 0.2181 1.384 0.559 2 1950.000011 1.569 0.278 0.3157 1.388 0.573 3 1951.000011 1.948 0.297 0.3940 1.550 0.564 4 1952.000000 2.265 0.310 0.3559 1.802 0.574 How can I preserve the column's data type when using pandas.read_sas()?
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/89005866
linked to: http://stackoverflow.com/q/49059421
answer count: 2

http://stackoverflow.com/q/50957382
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88912904
tagged with: oop
has comment: http://stackoverflow.com/comment/88912760
score: -1
has comment: http://stackoverflow.com/comment/88913053
has answer: http://stackoverflow.com/a/50957675
has comment: http://stackoverflow.com/comment/88912794
answer count: 2
has body: I'm wondering how you can access outer classes from the scope of class instances in an attribute of the outer class. I have heard of the super() function, but it only works for inheritance. To make things clear, I have given an example: class Outside: def __init__(self, spam, ham): self.eggs = spam * ham self.inside_class = Inside() class Inside: def double_eggs(self): # TODO: return the attribute eggs mulitplied by 2
favorite count: 0
tagged with: class
has comment: http://stackoverflow.com/comment/88912384
has comment: http://stackoverflow.com/comment/88912899
downvote count: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/50957458
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50957458
upvote count: 0
has comment: http://stackoverflow.com/comment/88913013
has comment: http://stackoverflow.com/comment/88912261
has comment: http://stackoverflow.com/comment/88912959
has title: Can a class instance in a class attribute access its outer class? ~ Python
accepted answer: http://stackoverflow.com/a/50957675
has comment: http://stackoverflow.com/comment/88912875
has comment: http://stackoverflow.com/comment/88912424
type: Question

http://stackoverflow.com/comment/88772535
score: 0
type: Comment
has text: This throws `1054, "Unknown column '17' in 'order clause'"`. I'm guessing it's because I'm forming my queryset by a union of two different querysets from the same model - but there is a missing value for the column I'm performing the `order_by` on. ?
type: AnswerComment
comment on: http://stackoverflow.com/a/50885275

http://stackoverflow.com/q/50934415
accepted answer: http://stackoverflow.com/a/50953683
type: AnsweredQuestion
has body: I want to extract a huge table from spanner and instead of the regular execute_sql function, I wish to stream data. But I don't see a lot of documentation around it. I am using google cloud python libraries and I couldn't find a solution either Has anyone tried it? import os,sys import subprocess import glob from os import path from google.cloud.spanner_v1.streamed import StreamedResultSet def run_quickstart(): # [START spanner_quickstart] # Imports the Google Cloud Client Library. from google.cloud import spanner # Instantiate a client. spanner_client = spanner.Client.from_service_account_json('&lt;stripped Auth Key&gt;') # Your Cloud Spanner instance ID. instance_id = 'spannereval' # Get a Cloud Spanner instance by ID. instance = spanner_client.instance(instance_id) # Your Cloud Spanner database ID. database_id = 'ias-ei-test' # Get a Cloud Spanner database by ID. database = instance.database(database_id) # Execute a simple SQL statement. with database.snapshot() as snapshot: results = snapshot.execute_sql('SELECT * from product_inventory_status') for row in results: print(row) # [END spanner_quickstart]
has comment: http://stackoverflow.com/comment/88869729
has answer: http://stackoverflow.com/a/50953683
type: Question
score: 0
tagged with: google-cloud-platform
answer count: 1
has title: Has anyone queried Google Spanner using StreamedResultSet in Python
has comment: http://stackoverflow.com/comment/88867907
tagged with: google-cloud-spanner
tagged with: python

http://stackoverflow.com/q/50997921
has answer: http://stackoverflow.com/a/50997965
type: AnsweredQuestion
has body: Since I started using version 3 of Python I have had many problems with sending string through sockets. I know that to send a string in a socket, a 'b' must be placed before the string to convert it to bytes. But what happens when I have to convert an input() to bytes? How is it done? I need to send a message written by keyboard to a socket: import socket client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect(("localhost",7500)) msg = input() client.send(msg) However, when I try it, I get the following error: TypeError: a bytes-like object is required, not 'str' Can someone tell me how I convert input() to bytes? I always use version 2.7 and I do not understand why version 3 is so irritating for the handling of sockets. :(
score: 3
type: Question
linked to: http://stackoverflow.com/q/7585435
answer count: 2
has title: Convert input () to bytes in Python 3?
possible better answer: http://stackoverflow.com/a/50997965
upvote count: 3
tagged with: python
favorite count: 0
tagged with: python-3.x
downvote count: 0
has answer: http://stackoverflow.com/a/50997971
duplicate of: http://stackoverflow.com/q/7585435
accepted answer: http://stackoverflow.com/a/50997971

http://stackoverflow.com/q/50914776
possible better answer: http://stackoverflow.com/a/50914873
tagged with: list
has answer: http://stackoverflow.com/a/50914802
accepted answer: http://stackoverflow.com/a/50914802
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/88829711
tagged with: string
upvote count: 3
has answer: http://stackoverflow.com/a/50914873
score: 0
downvote count: 3
has body: I have written a simple program to reverse a string but I am getting different result with i write a = "" and when I write a = []. Please can someone help me explain why this happens: Input is: "Argument goes here" 1st way a= [] for i in range(( len(text)-1,-1,-1): a+= text[i] return a Output is: ['e', 'r', 'e', 'h', ' ', 's', 'e', 'o', 'g', ' ', 't', 'n', 'e', 'm', 'u', 'g', 'r', 'A'] 2nd way a = "" for i in range(1, len(text) + 1): a += text[len(text) - i] return a Output is: ereh seog tnemugrA
favorite count: 0
tagged with: python-3.x
has title: Difference Between " " and [ ] in Python
tagged with: python
has comment: http://stackoverflow.com/comment/88830166
type: AnsweredQuestion

http://stackoverflow.com/q/50975313
tagged with: dataframe
type: Question
upvote count: 4
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/88947464
has title: if value is less than prior value in a pandas dataframe series
score: 4
has comment: http://stackoverflow.com/comment/88950848
has answer: http://stackoverflow.com/a/50975866
tagged with: pandas
tagged with: compare
tagged with: python
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88952351
tagged with: diff
has body: this is what my dataframe looks like after I extract the day from the date (see last column): Date AAPL NFLX INTC day 0 2008-01-02 27.834286 3.764286 25.350000 2 1 2008-01-03 27.847143 3.724286 24.670000 3 2 2008-01-04 25.721428 3.515714 22.670000 4 3 2008-01-07 25.377142 3.554286 22.879999 7 4 2008-01-08 24.464285 3.328571 22.260000 8 For my next step, I want to append another column called "Month_End" with a true/false marker if the current day is &lt; prior day. This step is to identify the end of the month. How to do this? Thanks much. I've tried the following with no luck so far (I'm a noob, just started python) for i, row in df.iterrows(): if df.day.iloc[i+1] &lt; df.day.iloc[i]: print (df['day']) and df.assign(Month_End = df.day.diff() &lt; 0) print(df.head())
has answer: http://stackoverflow.com/a/50975731

http://stackoverflow.com/comment/88909047
comment on: http://stackoverflow.com/q/50955568
has text: What do you mean @Fabre. Isnt using the dict?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/88726745
type: QuestionComment
comment on: http://stackoverflow.com/q/50862052
has text: No. The string is quite long and have multiple end strings. So finding the exact string "end vjk" is important
score: 0
type: Comment

http://stackoverflow.com/comment/88945916
has text: You might find some useful information [here](https://stackoverflow.com/questions/50471895/inaccurate-while-loop-timing-in-python/50472499#50472499)
comment on: http://stackoverflow.com/q/50974899
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88834503
has text: This is impossible to answer for us without seeing the code that produced the output.
comment on: http://stackoverflow.com/q/50917228
type: QuestionComment
type: Comment
score: 3

http://stackoverflow.com/comment/88978464
score: 0
comment on: http://stackoverflow.com/q/50991679
type: Comment
type: QuestionComment
has text: googling "find top k elements numpy array" gives [this SO thread](https://stackoverflow.com/questions/6910641/how-to-get-indices-of-n-maximum-values-in-a-numpy-array) as a first result, and [`numpy.argsort`](https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.argsort.html) as second - http://idownvotedbecau.se/noresearch/

http://stackoverflow.com/a/50970556
score: 2
downvote count: 0
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50953526
answers question: http://stackoverflow.com/q/50953526
type: Answer
has body: You are indexing a sparse matrix so you need to look into the Sparse class which is part of liboctave which is in C++. The method you seem to be looking for is Sparse&lt;T&gt; Sparse&lt;T&gt;::index (const idx_vector&amp; idx_i, const idx_vector&amp; idx_j, bool resize_ok). If you plan on using that implementation on another program, note the license of the code which is GPLv3+.

for-loop
tags question: http://stackoverflow.com/q/50955427
tags question: http://stackoverflow.com/q/50873376
tags question: http://stackoverflow.com/q/50960451
tags question: http://stackoverflow.com/q/50973041
tags question: http://stackoverflow.com/q/50959275
tags question: http://stackoverflow.com/q/50923756
tags question: http://stackoverflow.com/q/50911501
tags question: http://stackoverflow.com/q/50926669
tags question: http://stackoverflow.com/q/50897860
tags question: http://stackoverflow.com/q/50982326
tag name: for-loop
tags question: http://stackoverflow.com/q/50876768
tags question: http://stackoverflow.com/q/51006814
tags question: http://stackoverflow.com/q/50921718
tags question: http://stackoverflow.com/q/50926084
tags question: http://stackoverflow.com/q/50907375
tags question: http://stackoverflow.com/q/50903737
tags question: http://stackoverflow.com/q/50967065
tags question: http://stackoverflow.com/q/50901653
tags question: http://stackoverflow.com/q/50988546
tags question: http://stackoverflow.com/q/51002096
type: Tag
tags question: http://stackoverflow.com/q/51009483
tags question: http://stackoverflow.com/q/50981503
tags question: http://stackoverflow.com/q/51009376
tags question: http://stackoverflow.com/q/50926560
tags question: http://stackoverflow.com/q/50973663
tags question: http://stackoverflow.com/q/50892601
tags question: http://stackoverflow.com/q/50980635
tags question: http://stackoverflow.com/q/51004990
tags question: http://stackoverflow.com/q/50955719
tags question: http://stackoverflow.com/q/50979879
tags question: http://stackoverflow.com/q/50981037
tags question: http://stackoverflow.com/q/50936756
tags question: http://stackoverflow.com/q/50923069
tags question: http://stackoverflow.com/q/50874514

pandas
tags question: http://stackoverflow.com/q/50991327
tags question: http://stackoverflow.com/q/50988918
tags question: http://stackoverflow.com/q/50942847
tags question: http://stackoverflow.com/q/50912255
tags question: http://stackoverflow.com/q/50947447
tags question: http://stackoverflow.com/q/50911651
tags question: http://stackoverflow.com/q/50970063
tags question: http://stackoverflow.com/q/50899676
tags question: http://stackoverflow.com/q/50934941
tags question: http://stackoverflow.com/q/50895454
tags question: http://stackoverflow.com/q/50866340
tags question: http://stackoverflow.com/q/50927753
tags question: http://stackoverflow.com/q/50881917
tags question: http://stackoverflow.com/q/50900002
tags question: http://stackoverflow.com/q/51000586
tags question: http://stackoverflow.com/q/50892492
tags question: http://stackoverflow.com/q/50906899
tags question: http://stackoverflow.com/q/50923929
tags question: http://stackoverflow.com/q/50864599
tags question: http://stackoverflow.com/q/50979873
tags question: http://stackoverflow.com/q/51002869
tags question: http://stackoverflow.com/q/50934852
tags question: http://stackoverflow.com/q/50897552
tags question: http://stackoverflow.com/q/50955547
tags question: http://stackoverflow.com/q/50924788
tags question: http://stackoverflow.com/q/50987639
tags question: http://stackoverflow.com/q/50929613
tags question: http://stackoverflow.com/q/50892788
tags question: http://stackoverflow.com/q/50951837
tags question: http://stackoverflow.com/q/50981879
tags question: http://stackoverflow.com/q/50978127
tags question: http://stackoverflow.com/q/50878794
tags question: http://stackoverflow.com/q/50903185
tags question: http://stackoverflow.com/q/50978860
tags question: http://stackoverflow.com/q/50937891
tags question: http://stackoverflow.com/q/50864881
tags question: http://stackoverflow.com/q/50885861
tags question: http://stackoverflow.com/q/50860187
tags question: http://stackoverflow.com/q/51004076
tags question: http://stackoverflow.com/q/50998588
tags question: http://stackoverflow.com/q/50935495
tags question: http://stackoverflow.com/q/50916860
tags question: http://stackoverflow.com/q/50856859
tags question: http://stackoverflow.com/q/50930393
tags question: http://stackoverflow.com/q/50939977
tags question: http://stackoverflow.com/q/50868339
tags question: http://stackoverflow.com/q/50931416
tags question: http://stackoverflow.com/q/50973827
tags question: http://stackoverflow.com/q/50983646
tags question: http://stackoverflow.com/q/50941472
tags question: http://stackoverflow.com/q/51002344
tags question: http://stackoverflow.com/q/50930683
tags question: http://stackoverflow.com/q/50978660
tags question: http://stackoverflow.com/q/50938144
tags question: http://stackoverflow.com/q/50989975
tags question: http://stackoverflow.com/q/50870045
tags question: http://stackoverflow.com/q/50970326
tags question: http://stackoverflow.com/q/50951274
tags question: http://stackoverflow.com/q/50911316
tags question: http://stackoverflow.com/q/50955112
tags question: http://stackoverflow.com/q/50947184
tags question: http://stackoverflow.com/q/50970859
tags question: http://stackoverflow.com/q/50867085
tags question: http://stackoverflow.com/q/50994949
tags question: http://stackoverflow.com/q/50891974
tags question: http://stackoverflow.com/q/50886269
tags question: http://stackoverflow.com/q/50978944
tags question: http://stackoverflow.com/q/50976793
tags question: http://stackoverflow.com/q/50892171
tags question: http://stackoverflow.com/q/50914568
tags question: http://stackoverflow.com/q/50920960
tags question: http://stackoverflow.com/q/50991899
tags question: http://stackoverflow.com/q/50915424
tags question: http://stackoverflow.com/q/50960537
tags question: http://stackoverflow.com/q/50972431
tags question: http://stackoverflow.com/q/50882495
tags question: http://stackoverflow.com/q/50945231
tags question: http://stackoverflow.com/q/50899707
tags question: http://stackoverflow.com/q/50888847
tags question: http://stackoverflow.com/q/50874618

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

http://stackoverflow.com/comment/88745682
comment on: http://stackoverflow.com/a/50871906
type: Comment
has text: So, in case if words is a really long string, comprising around 1000000+ independent words, the first way of making the dict, i.e. using a generator expression would take comparatively more time to execute?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88884595
score: 0
type: Comment
type: QuestionComment
has text: Please provide [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve)
comment on: http://stackoverflow.com/q/50943381

http://stackoverflow.com/comment/91962634
has text: @ZakiIndra if an answer resolves your problem, please consider [accepting](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) it.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50939977

http://stackoverflow.com/a/50873067
answers question: http://stackoverflow.com/q/50872865
upvote count: 1
has body: If you are getting such an error code, and it is working as expected in your other IDE, it appears that IDLE is using python 2.x, for which the input/print syntax has slightly different effects. python 2 person = raw_input("enter your name: ") print("hello {}".format(person)) python 3 person = input("enter your name: ") print("hello ",person)
has comment: http://stackoverflow.com/comment/88747753
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/comment/88736521
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/50867085
has text: You could have printed `set(output['propertyID'])` and found out....
type: Comment

http://stackoverflow.com/a/50891958
score: 0
has body: It is not clearly advertised in the doc yet, but in eager mode, each Tensor and Variable has a device field which shows where a variable is located or where an operation took place. However AFAIK there is no automatic device placement log that would trigger whenever an operation is run. So it may take some work to get device placements of operations that occur within a hierarchy of objects.
type: Answer
answers question: http://stackoverflow.com/q/50891957

http://stackoverflow.com/a/50858014
score: 2
downvote count: 0
upvote count: 2
answers question: http://stackoverflow.com/q/50857937
has body: It unfortunately won't work in Python3x, since a list is considered unhashable in the same. How about just comparing them directly, this should work for most scenarios. x == y
type: Answer

http://stackoverflow.com/q/50969050
possible better answer: http://stackoverflow.com/a/50969829
upvote count: 2
tagged with: numpy
has answer: http://stackoverflow.com/a/50969140
tagged with: numpy-ndarray
answer count: 3
tagged with: arrays
favorite count: 0
has answer: http://stackoverflow.com/a/50969829
has title: Numpy - create a multidimensional array of a copy of an array
has comment: http://stackoverflow.com/comment/88934534
tagged with: multidimensional-array
tagged with: python
has comment: http://stackoverflow.com/comment/88934378
has comment: http://stackoverflow.com/comment/88934320
score: 2
downvote count: 0
has answer: http://stackoverflow.com/a/50969159
accepted answer: http://stackoverflow.com/a/50969159
type: Question
has body: I want to generate a an array of ordered numbers and then multiply it into another array : [ [0,1,2,3,4,5] [0,1,2,3,4,5] [0,1,2,3,4,5] ... [0,1,2,3,4,5] ] I can generate the first [0,1,2,3,4,5] with nums = np.arange(0, 6) but then if I multiply by a number inside a list it just increases the values = [nums* 3] = [0,3,6,9,12,15]. How can I do this ?
type: AnsweredQuestion

http://stackoverflow.com/a/50926636
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50926518
type: Answer
answers question: http://stackoverflow.com/q/50926518
has body: Send the tuple with * so you can pass the ints inside the tuple to the datetime function properly: from datetime import datetime, date def epochConverter(a): return datetime(*a).timestamp() print(epochConverter((2018,6,19,0,0,0)))
upvote count: 1
has comment: http://stackoverflow.com/comment/88857707

http://stackoverflow.com/a/50893728
has comment: http://stackoverflow.com/comment/88787764
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50893696
score: 3
answers question: http://stackoverflow.com/q/50893696
has body: You can use TemplateView for this. Just add to your urlpattern: from django.views.generic import TemplateView urlpatterns =[ path('',views.list_of_issue,name='list_of_issue'), path('&lt;int:issue_id&gt;/',views.issue_detail,name='issue_detail'), path('&lt;int:issue_id&gt;/comment',views.add_comment,name='add_comment'), path('new_issue/',views.new_issue,name='new_issue'), path('&lt;int:issue_id&gt;/edit_issue/',views.edit_issue,name='edit_issue'), path('&lt;int:issue_id&gt;/delete_issue/',views.delete_issue,name='delete_issue'), path('deleted/', TemplateView.as_view(template_name="nice_delete.html"), name='success_deletion'), ] And use success_deletion url in delete_issue view for redirection: def delete_issue(request,project_id,issue_id): if not request.user.is_staff or not request.user.is_superuser: raise Http404 issue = get_object_or_404(Issue,id=issue_id) issue.delete() return redirect('success_deletion')
type: AcceptedAnswer
upvote count: 3
type: Answer
has comment: http://stackoverflow.com/comment/88795002

http://stackoverflow.com/q/51006509
has comment: http://stackoverflow.com/comment/89006325
downvote count: 4
has title: Python how to parsing HTML with BS4
tagged with: lxml
upvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/51006516
favorite count: 0
tagged with: parsing
tagged with: beautifulsoup
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has body: K/D 8.66 ( If not clear the two divs below the top div are its children ) I'm currently trying to parse for 8.66 and I have made many attempts to parse for it using lxml and beautifulsoup. I tried running a loop to search for that value but it seems like nothing works! If you can help please do I am absolutely lost on how to do this. Thank you in advance!!
has comment: http://stackoverflow.com/comment/89006444
type: Question
score: -4

http://stackoverflow.com/a/51006545
has body: This CSS selector will do it. #listingInfoModal button.close
has comment: http://stackoverflow.com/comment/89007279
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51006315
answers question: http://stackoverflow.com/q/51006315
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/89019371
has comment: http://stackoverflow.com/comment/89006585

http://stackoverflow.com/q/50864087
tagged with: indexing
type: AnsweredQuestion
type: Question
tagged with: numpy
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/50864508
accepted answer: http://stackoverflow.com/a/50864508
has body: As stated in the title, I have a list of tuples that look like (numpy_array,id) where the numpy array is m x m. I need to access each element of the numpy array (i.e. all m^2 of them) but am having a tough time doing this without unpacking the tuple. I would rather not unpack the tuple because of how much data it is/how long that would take due to the amount of data. If I unpack the tuple the code would look like below, is there a way to index this so that I don't need to unpack? for x in range(length): for y in range(length): if(instance1[x][y]==instance2[x][y]): distance -=1
tagged with: tuples
tagged with: python
has title: Accessing MxM numpy array that is first index of a tuple

http://stackoverflow.com/comment/89005538
type: Comment
comment on: http://stackoverflow.com/a/51003723
score: 0
type: AnswerComment
has text: Hi, I made changes to my code, need your assistance, thanks!

http://stackoverflow.com/q/50980852
has comment: http://stackoverflow.com/comment/88957285
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/88957180
has comment: http://stackoverflow.com/comment/88957317
tagged with: numpy
score: 2
has answer: http://stackoverflow.com/a/50980943
tagged with: arrays
downvote count: 0
has comment: http://stackoverflow.com/comment/88957300
accepted answer: http://stackoverflow.com/a/50980943
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88957256
tagged with: matrix
has comment: http://stackoverflow.com/comment/88957181
has title: Large numpy matrix memory issues
favorite count: 0
tagged with: memory-management
type: Question
upvote count: 2
has body: I have two questions, but the first takes precedence. I was doing some timeit testing of some basic numpy operations that will be relevant to me. I did the following n = 5000 j = defaultdict() for i in xrange(n): print i j[i] = np.eye(n) What happened is, python's memory use almost immediately shot up to 6gigs, which is over 90% of my memory. However, numbers printed off at a steady pace, about 10-20 per second. While numbers printed off, memory use sporadically bounced down to ~4 gigs, and back up to 5, back down to 4, up to 6, down to 4.5, etc etc. At 1350 iterations I had a segmentation fault. So my question is, what was actually occurring during this time? Are these matrices actually created one at a time? Why is memory use spiking up and down? My second question is, I may actually need to do something like this in a program I am working on. I will be doing basic arithmetic and comparisons between many large matrices, in a loop. These matrices will sometimes, but rarely, be dense. They will often be sparse. If I actually need 5000 5000x5000 matrices, is that feasible with 6 gigs of memory? I don't know what can be done with all the tools and tricks available... Maybe I would just have to store some of them on disk and pull them out in chunks? Any advice for if I have to loop through many matrices and do basic arithmetic between them? Thank you.

http://stackoverflow.com/comment/88975810
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50990154
has text: Some of your eigenvalues are complex numbers so having the form ```a+bj```. You will not be able to plot this on a standard x-y plane or serialize it normally. [this SO](https://stackoverflow.com/questions/29473953/how-to-serialize-an-array-list-mat-filled-with-complex-number) question talks about serializing complex numbers. Consider using ```np.real()``` to plot just the real parts for now.
score: 0

http://stackoverflow.com/q/50918043
has answer: http://stackoverflow.com/a/50918082
accepted answer: http://stackoverflow.com/a/50918082
tagged with: email-bounces
tagged with: python
downvote count: 0
possible better answer: http://stackoverflow.com/a/50918135
type: Question
type: AnsweredQuestion
tagged with: mailgun
score: 1
has body: In the MailGun backend, I've noticed a "Not delivering to previously bounced address" error: This is probably because, at that time, the email address was not properly set up yet, but now it is. Therefore, I'd like to remove the address kurt@hicleo.com from the list of previously bounced addresses. Following https://documentation.mailgun.com/en/latest/api-bounces.html#bounces, I've implemented a get_bounces() method for our sender domain, mg.startwithlucy.com: In [1]: import requests In [2]: def get_bounces(): ...: return requests.get('https://api.mailgun.net/v3/mg.startwithlucy.com ...: /bounces', auth=('api', '&lt;our_api_key&gt;') ...: ) ...: In [3]: response = get_bounces() In [4]: response.status_code Out[4]: 200 In [6]: import json In [7]: content = json.loads(response.content) In [14]: next(item for item in content['items'] if item['address'] == 'kurt@hicleo.com') Out[14]: {'MessageHash': '0f35b8112739c23d996bece18755de105a8422ad', 'address': 'kurt@hicleo.com', 'code': '550', 'created_at': 'Thu, 07 Jun 2018 17:48:28 UTC', 'error': 'No Such User Here'} Next, I defined a delete_bounce(address) function and called it for kurt@hicleo.com. However, I still see the corresponding email address showing up in the result of get_bounces(): In [21]: def delete_bounce(address): ...: return requests.delete(f'https://api.mailgun.net/v3/mg.startwithlucy.com/{address ...: }', auth=('api', '&lt;our_api_key&gt;')) ...: In [22]: delete_response = delete_bounce('kurt@hicleo.com') In [23]: delete_response.status_code Out[23]: 200 In [24]: delete_response.content Out[24]: b'Mailgun Magnificent API' In [25]: response = get_bounces() In [26]: response.status_code Out[26]: 200 In [27]: content = json.loads(response.content) In [28]: kurt_bounces = [item for item in content['items'] if item['address'] == 'kurt@hicleo. ...: com'] In [29]: kurt_bounces Out[29]: [{'MessageHash': '0f35b8112739c23d996bece18755de105a8422ad', 'address': 'kurt@hicleo.com', 'code': '550', 'created_at': 'Thu, 07…
answer count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/50918135
favorite count: 0
has title: Can't delete MailGun bounces?

http://stackoverflow.com/a/53672281
has comment: http://stackoverflow.com/comment/122229377
has comment: http://stackoverflow.com/comment/111327666
has comment: http://stackoverflow.com/comment/114738061
has comment: http://stackoverflow.com/comment/106999053
has comment: http://stackoverflow.com/comment/138609973
has comment: http://stackoverflow.com/comment/117672326
has comment: http://stackoverflow.com/comment/112495319
has comment: http://stackoverflow.com/comment/138094766
has comment: http://stackoverflow.com/comment/135281237
has comment: http://stackoverflow.com/comment/139938673
has comment: http://stackoverflow.com/comment/118447955
has comment: http://stackoverflow.com/comment/114678325
has comment: http://stackoverflow.com/comment/137346475
type: AcceptedAnswer
downvote count: 1
score: 353
answers question: http://stackoverflow.com/q/50951955
has comment: http://stackoverflow.com/comment/128662342
has comment: http://stackoverflow.com/comment/108406169
has comment: http://stackoverflow.com/comment/118445427
accepted answer of: http://stackoverflow.com/q/50951955
upvote count: 354
has body: I see steps are scattered in different answers. Based on my recent experience with this pytesseract error on Windows, writing different steps in sequence to make it easier to resolve the error: 1. Install tesseract using windows installer available at: https://github.com/UB-Mannheim/tesseract/wiki 2. Note the tesseract path from the installation. Default installation path at the time of this edit was: C:\Users\USER\AppData\Local\Tesseract-OCR. It may change so please check the installation path. 3. pip install pytesseract 4. Set the tesseract path in the script before calling image_to_string: pytesseract.pytesseract.tesseract_cmd = r'C:\Users\USER\AppData\Local\Tesseract-OCR\tesseract.exe'
type: Answer
has comment: http://stackoverflow.com/comment/137274644

http://stackoverflow.com/a/50976691
answers question: http://stackoverflow.com/q/50976187
type: Answer
has comment: http://stackoverflow.com/comment/88983486
has comment: http://stackoverflow.com/comment/88956471
has comment: http://stackoverflow.com/comment/89027663
downvote count: 1
has body: If you use ast.literal_eval then you can use the same string .replace: &gt;&gt;&gt; from ast import literal_eval &gt;&gt;&gt; li=[1, [0], 'a', 1, [0], 'a'] &gt;&gt;&gt; literal_eval(repr(li).replace("1, [0], 'a', 1", '5')) [5, [0], 'a'] As pointed out in comments, you can also use json to do a similar thing: &gt;&gt;&gt; import json &gt;&gt;&gt; json.loads(json.dumps(li).replace('1, [0], "a", 1','5')) [5, [0], 'a']
score: 3
upvote count: 4
has comment: http://stackoverflow.com/comment/89050338

http://stackoverflow.com/comment/88830705
type: Comment
type: QuestionComment
score: 6
has text: `user_input1.isalpha()` returns either `True` or `False`. There's no way your input could be either of those values, so the ceeck will always fail.
comment on: http://stackoverflow.com/q/50915346

http://stackoverflow.com/a/51001699
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51001582
answers question: http://stackoverflow.com/q/51001582
type: AcceptedAnswer
downvote count: 0
has body: Here's another solution using .transform: df_bob_removed = df.loc[ df.groupby('foo')['foo'].transform('count') &gt; 1, ] foo bar 0 Alice 42 1 Alice 44
type: Answer

http://stackoverflow.com/q/50971442
tagged with: java.util.scanner
score: -4
tagged with: input
tagged with: python
type: AnsweredQuestion
tagged with: java
accepted answer: http://stackoverflow.com/a/50974646
type: Question
answer count: 2
downvote count: 4
upvote count: 0
has body: Is there any possible way to accept a arbitrary(unknown) no. of input lines of string from the user until user explicitly enters -1 and store it in a string for further manipulation.
possible better answer: http://stackoverflow.com/a/50972922
has answer: http://stackoverflow.com/a/50972922
favorite count: 0
has title: Accept arbitrary multi-line input of String type and store it in a variable
has answer: http://stackoverflow.com/a/50974646

http://stackoverflow.com/a/50879825
type: Answer
has body: Try to downgrade to pip install --upgrade html5lib==1.0b8 if upgrading didn't work.
answers question: http://stackoverflow.com/q/50879241
score: 0

http://stackoverflow.com/comment/88918915
score: 0
comment on: http://stackoverflow.com/q/50960583
has text: There are a few different things that can cause this. First, see [this question](https://stackoverflow.com/questions/25981703/). Do what the answer says to `install -U pip setuptools`. If that works, see if `pip` now works without the `trusted-host` stuff. If so, that was your problem. If not, you need to give u more information: what platform you're on, what Python version and how you installed it (python.org installer, apt-get, whatever), which of those steps failed, and what the output was.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89008995
score: 0
type: AnswerComment
type: Comment
has text: Python 3 uses "/usr/bin/pip" head /usr/local/bin/pip shows "No such file or directory".
comment on: http://stackoverflow.com/a/51007958

http://stackoverflow.com/q/50890836
type: AnsweredQuestion
has body: I'm a newbie in a Neural Networks. I'm doing my university NN project in Keras. I assembled and trained the one-layer sequential model using SGD optimizer: [...] nn_model = Sequential() nn_model.add(Dense(32, input_dim=X_train.shape[1], activation='tanh')) nn_model.add(Dense(1, activation='tanh')) sgd = keras.optimizers.SGD(lr=0.001, momentum=0.25) nn_model.compile(loss='mean_squared_error', optimizer=sgd, metrics=['accuracy']) history = nn_model.fit(X_train, Y_train, epochs=2000, verbose=2, validation_data=(X_test, Y_test)) [...] I've tried various learning rate, momentum, neurons and get satisfying accuracy and error results. But, I have to know how keras works. So could you please explain me how exactly fitting in keras works, because I can't find it in Keras documentation? How does Keras update weights? Does it use a backpropagation algorithm? (I'm 95% sure.) How SGD algorithm is implemented in Keras? Is it similar to Wikipedia explanation? How Keras exactly calculate a gradient? Thank you kindly for any information.
accepted answer: http://stackoverflow.com/a/50891049
tagged with: deep-learning
answer count: 1
tagged with: keras
score: 0
tagged with: python
has answer: http://stackoverflow.com/a/50891049
has title: How does exactly fitting with SGD in Keas works?
tagged with: tensorflow
type: Question

http://stackoverflow.com/a/50985842
has body: Ok, you are using Python 2, so what you read from the file is a byte string. More according to the error message, you have the default for ensure_ascii parameter which is true. In that case, all strings are decoded with the default encoding (utf8). If your input is not utf8 encode you get a UnicodeDecodeError. What can be done? If you are not sure of the initial encoding and just want to leave everything as is you can just declare a Latin1 encoding. It just changes every byte in the unicode character having that code. The ensure_ascii is a bit different: it just allows any byte in the resulting json string, which may lead to non portable Json: The RFC does not explicitly forbid JSON strings which contain byte sequences that don’t correspond to valid Unicode characters (e.g. unpaired UTF-16 surrogates), but it does note that they may cause interoperability problems. By default, this module accepts and outputs (when present in the original str) code points for such sequences. So this is a bullet proof way: def convert2json(filename): with open(filename) as I: for line in I: d = {"data": line} print(json.dumps(d, encoding='Latin1')) Simply a non ascii character in the input file ,say '\x..', will be coded in the Json as '\u00..'
answers question: http://stackoverflow.com/q/50983959
type: Answer
score: 0

http://stackoverflow.com/q/50971119
has comment: http://stackoverflow.com/comment/88938892
type: Question
has body: When I evaluate the following snippet of code I get the value True import pandas as pd df = pd.DataFrame({'a': ['assa', '100', 'AJSAND']}) (df &lt; 0).all() Is it always the case that strings evaluate to less than zero in a Pandas DataFrame? However, the following results in an error 's' &lt; 0
answer count: 1
downvote count: 0
has title: Are strings in pandas.Series always smaller than 0?
favorite count: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/50971443
tagged with: python
upvote count: 1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50971443
score: 1

http://stackoverflow.com/comment/88912792
type: QuestionComment
comment on: http://stackoverflow.com/q/50957627
score: 0
has text: This is not an appropriate use of exception handling. Simply remove the `try:` and the `except:`. Leave the print statement. Re-indent your code. I think it will work as you intend.
type: Comment

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

http://stackoverflow.com/q/50862207
has comment: http://stackoverflow.com/comment/88727561
upvote count: 1
tagged with: discord.py
has body: async def on_message(self, message): attachmentimage = re.compile(r'(.(jpe?g|JPE?G|png|PNG))') attachmentgif = re.compile(r'(.(gif|GIF))') streamables = re.compile(r'streamable(\.com)\/([\w-]{2,50})') customemoji = re.compile(r'&lt;:[\w]+:[\d]+&gt;') animatedcustomemoji = re.compile(r'&lt;a:[\w]+:[\d]+&gt;') username = re.compile(r'@([A-Za-z0-9`~!@#$%^&amp;*()_|+\-=?;:\'",.&lt;&gt;\{\}\[\]\\\/]{2,32})') path = 'C:/xxxx/xxxx/xxxx/xxxx/Images/' words = re.sub(r'(@([A-Za-z0-9`~!@#$%^&amp;*()_|+\-=?;:\'",.&lt;&gt;\{\}\[\]\\\/]{2,32}))', '', message.clean_content) if message.author == self.user: return if len(message.attachments) &gt; 0 and attachmentimage.search(message.attachments[0].url) and message.channel.id == 423899570871861252: if message.mentions or customemoji.search(message.clean_content) or animatedcustomemoji.search(message.clean_content): print(re.sub(r'(&lt;:|&lt;a:|:[\d]+&gt;)', '', words)) When I run it, there is an extra space with everything else next to it. I want to remove mentions completely but even though the '' creates an extra space somehow. Here is the output: hype As you can see, it does remove the mention because of the: re.sub(r'(@([A-Za-z0-9`~!@#$%^&amp;*()_|+\-=?;:\'",.&lt;&gt;\{\}\[\]\\\/]{2,32}))', '', message.clean_content) But there is still a space before hype when there shouldn't be. How do I fix that?
answer count: 0
downvote count: 0
type: UnansweredQuestion
score: 1
favorite count: 0
has title: Extra space with re.sub when wanting to remove mentions
type: Question
has comment: http://stackoverflow.com/comment/88727247
tagged with: python
tagged with: regex
tagged with: python-3.x

http://stackoverflow.com/comment/88861224
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50931098
has text: Why don't you just store everything in a dataframe?

http://stackoverflow.com/comment/88937094
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50970266
has text: @FHTMitchell, @pLOPeGG; Thanks, but i am using Python 3...
score: 0

http://stackoverflow.com/q/50989605
tagged with: grammar
linked to: http://stackoverflow.com/q/50928531
favorite count: 0
has comment: http://stackoverflow.com/comment/88978356
has comment: http://stackoverflow.com/comment/88978482
has comment: http://stackoverflow.com/comment/90006813
type: UnansweredQuestion
tagged with: python
tagged with: lark-parser
has body: I was trying to simplifying the case presented in another question and got to the following parsing attempt using lark: from lark.lark import Lark text = """ start_thing { loc int { from 0, to 1093, strand plus, id gi 384632836 } } """ grammar = """\ thing: "start_thing" node locus_info: "loc int" "{" int_info "," int_info "," STRAND_INFO "," int_info "}" int_info: TAGS? INT node: locus_info | int_info | TAGS? "{" nodes "}" -&gt; subnodes | TAGS -&gt; onlytags nodes: node? | node ("," node)* STRAND_INFO: "strand" SIGN SIGN: "plus" | "minus" TAGS: TAGWORD (WS TAGWORD)* TAGWORD: ("_"|LETTER)("_"|"-"|LETTER|DIGIT)* %import common.WS %import common.LETTER %import common.DIGIT %import common.INT %ignore WS """ parser = Lark(grammar, start="thing", ambiguity="explicit") parsed = parser.parse(text) print(parsed.pretty()) Output: thing subnodes nodes subnodes loc int nodes node int_info from 0 node int_info to 1093 onlytags strand plus node int_info id gi 384632836 As shown in this example, the ambiguity="explicit" option should enable the displaying of alternative matching possibilities, preceded by an _ambig label. This does not appear in the above output. It seems I don't get what an ambiguity is. Why is "strand plus" not considered ambiguous? It seems to me that it could either be matched by STRAND_INFO or onlytags. Similarly, I would expect "loc int {...}" to be matched by either locus_info or subnodes.
has comment: http://stackoverflow.com/comment/89072736
has title: Understanding what constitutes an ambiguity in a lark grammar
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/88978881
has comment: http://stackoverflow.com/comment/89573593
upvote count: 1
type: Question
downvote count: 0

http://stackoverflow.com/a/50914316
has comment: http://stackoverflow.com/comment/88829148
has comment: http://stackoverflow.com/comment/88831665
type: Answer
answers question: http://stackoverflow.com/q/50913856
score: 0
has body: The function you give to minimize should take x, a variable shaped like x0, and the values that you pass via the args. minimize steps through various x as it searches, but passes the same *args each time. If you change class to: class Neural: def __init__(self, X, y, lambda1): --- def costFunction(self, params): --- return J you should be able use it as: myobj = Neural(X, y, 1) opt.minimize(myobj.costFunction, x0=params_init, method='CG',jac=myobj.backPropogate) backPropogate needs a similar adjustment. I'd test it with a call like Neural(X, y, 1).costFunction(params_init) To use args,costFunctionneeds to acceptX, y, lambda1`, eg: .... def costFunction(self, params, X, y, lambda1): and is created with Neural().costFunction.
has comment: http://stackoverflow.com/comment/88837298
has comment: http://stackoverflow.com/comment/88829998
has comment: http://stackoverflow.com/comment/88829045

http://stackoverflow.com/comment/88828675
score: 0
comment on: http://stackoverflow.com/q/50913866
type: Comment
type: QuestionComment
has text: @Simon I think that’s fine. The OP can always revert if they disagree, and if not, you’ve improved their question for them.

http://stackoverflow.com/comment/88938364
type: Comment
has text: If I want to apply samething to letters dataset available in uci what all should I change and how?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50872497

http://stackoverflow.com/comment/88810222
comment on: http://stackoverflow.com/a/50905237
type: Comment
has text: `[^A-Za-z0-9\s]` is very bold. (Also, regex always as raw strings! `r''[^A-Za-z0-9\s]"`)
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88857904
type: QuestionComment
has text: do you want to then add these new columns to the dataframe?
score: 0
comment on: http://stackoverflow.com/q/50929361
type: Comment

http://stackoverflow.com/q/50919635
downvote count: 0
has comment: http://stackoverflow.com/comment/88839130
linked to: http://stackoverflow.com/q/2861501
type: Question
tagged with: mypy
has answer: http://stackoverflow.com/a/50920235
has comment: http://stackoverflow.com/comment/88839244
score: 9
answer count: 3
has title: Is typed implicit conversion (coercion) in Python 3.x possible?
has answer: http://stackoverflow.com/a/50919719
has answer: http://stackoverflow.com/a/50920647
favorite count: 0
upvote count: 9
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88839165
type: UnansweredQuestion
tagged with: python
has body: Is it possible to implement custom automatic/implicit conversion (aka coercion) in Python 3.6+ that won't make mypy and other static analyzers sad? An example would be a def(foo: A), and given def b_to_a(b: B) -&gt; A, is there a way I could potentially write foo(some_b) (where some_b: B ) instead of foo(b_to_a(some_b))? I think there are definitely some good ways to do this in the dynamics of Python (tacking on members to classes that include converters, for instance), or even tacking on such converters to the function object itself so that it can handle conversion for selected types, but my current understanding of Python types makes me thing it would not satisfy mypy and the like. For comparison, see Scala's implicit conversions.

http://stackoverflow.com/comment/88979571
type: Comment
has text: If plotting, would you say I should just use `testers_time` as x and `prob` as y and do `plt.plot(x, y, marker='.', linestyle='none')`? Or `plt.hist()` is a better idea?
comment on: http://stackoverflow.com/a/50992317
type: AnswerComment
score: 0

http://stackoverflow.com/comment/88818210
score: 0
has text: AKX - Thanks! That worked perfectly. After not being able to directly modify slices of the array as above, I'd just assumed that maybe array slicing in general didn't work with device arrays.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50902981

http://stackoverflow.com/comment/88732579
comment on: http://stackoverflow.com/q/50864988
has text: You could if it were writable, but the readonly attribute conflicts with the superclass init.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50950141
has body: You want to basically reindex your DataFrame. from itertools import product idx = list(product(df['user'].unique(), df['cat'].unique())) df = df.set_index(['user', 'cat']).reindex(idx).reset_index() The second part seems to be setting the missing values (in this case NaN after the reindex) to the average value from that category. You can accomplish this with a mapping and groupby to calculate the average. df.loc[df.val.isnull(), 'val'] = df.loc[df.val.isnull(), 'cat'].map(df.groupby('cat').val.mean()) df is now: user cat val 0 u1 cat1 1.0 1 u1 cat2 2.0 2 u1 cat3 3.0 3 u1 cat4 4.0 4 u2 cat1 5.0 5 u2 cat2 2.0 6 u2 cat3 3.0 7 u2 cat4 4.0 8 u3 cat1 3.0 9 u3 cat2 2.0 10 u3 cat3 3.0 11 u3 cat4 4.0
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/50947280
score: 1
upvote count: 1

http://stackoverflow.com/comment/89015601
comment on: http://stackoverflow.com/q/51010317
has text: Hey, so heres the finalish thing?, but it doesn't input any of the files into the INPUT, it just looks TIME = QBAER = ,,,,
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50879827
downvote count: 0
tagged with: firebase-storage
type: UnansweredQuestion
score: 6
has title: Get Firebase Storage Token of a blob/file that has been uploaded
tagged with: firebase
has answer: http://stackoverflow.com/a/53264701
has body: I have a python application which requires me to dump a few files into a Firebase Storage bucket, update an HTML file's img links so they point to the previously uploaded files + Token, and then save off the HTML file itself into the bucket for later use. The problem I'm having is that I can't seem to find a way in Python to fetch the unique token of the blob/file. For reference, I have been accomplishing this in Javascript using getDownloadURL which provides me with a URL that looks like this: https://firebasestorage.googleapis.com/v0/b/[project].appspot.com/o/[bucket]%2Ffile.png?alt=media&amp;token=[token] When I use the google-cloud-python blob method 'path' it gives me a URL without the token, which I can already construct on my own: /b/[project].appspot.com/o/[bucket]%2Ffile.png Can anybody please help point me in the direction of what method I can use to retrieve the blob/file's token so I can construct the full URL? from firebase_admin import credentials from firebase_admin import storage try: cred = credentials.Certificate("serviceAccountKey.json") firebase_admin.initialize_app(cred, { 'databaseURL': 'https://[project].firebaseio.com' }) except Exception as e: print str(e.message) bucket = storage.bucket('[project].appspot.com') blob1 = bucket.blob(userId + '/' + file) with open(os.path.join(tmp_dir, file), 'rb') as my_file: blob1.upload_from_file(my_file) #Now I need the token but this only prints the path I already know print blob1.path
type: Question
answer count: 3
upvote count: 6
favorite count: 0
linked to: http://stackoverflow.com/q/56366142
has answer: http://stackoverflow.com/a/72617086
tagged with: python
has answer: http://stackoverflow.com/a/73398562

http://stackoverflow.com/a/51079764
type: Answer
answers question: http://stackoverflow.com/q/50892989
score: 0
has body: I'm not quite sure what you're asking, but if you want to find nodes that overlap among different communities in a network then there are several algorithms for this. Here is an article that will get you started: https://arxiv.org/pdf/1110.5813.pdf. The CFinder algorithm in particular has received alot of attention. Listed here, you'll find an implementation of the algorithm that you may find useful. Here is code provided by Tamas for CFinder: # CFINDER IMPLEMENTATION #!/usr/bin/env python from itertools import combinations import igraph import optparse parser = optparse.OptionParser(usage="%prog [options] infile") parser.add_option("-k", metavar="K", default=3, type=int, help="use a clique size of K") options, args = parser.parse_args() if not args: parser.error("Required input file as first argument") k = options.k g = igraph.load(args[0], format="ncol", directed=False) cls = map(set, g.maximal_cliques(min=k)) edgelist = [] for i, j in combinations(range(len(cls)), 2): if len(cls[i].intersection(cls[j])) &gt;= k-1: edgelist.append((i, j)) cg = igraph.Graph(edgelist, directed=False) clusters = cg.clusters() for cluster in clusters: members = set() for i in cluster: members.update(cls[i]) print "\t".join(g.vs[members]["name"]) Alternatively, I believe NetworkX have a similar interpretation that can be found here.

http://stackoverflow.com/a/50913316
answers question: http://stackoverflow.com/q/50909957
accepted answer of: http://stackoverflow.com/q/50909957
score: 0
type: AcceptedAnswer
type: Answer
has body: I used the Flyweight Pattern as suggested by avix and as explained on this article by Yannick Loiseau, especially the Gang of Four Version. For creation of the classes this gives: class FlyweightFactory(object): def __init__(self, cls): self._cls = cls self._instances = dict() def get_instance(self, *args, **kargs): return self._instances.setdefault((args, tuple(kargs.items())), self._cls(*args, **kargs)) class Match(object): def __init__(self, link, tournament): self.tn = tournament self.link = link MatchFactory = FlyweightFactory(Match) Then I wrote a simple check function to verify at creation if the object already exists: def get_match_object(link, tournament): try: match = MatchFactory.get_instance(link, tournament) except: match = Match(link, tournament) Also did it for Tournament &amp; Team classes, it works perfectly.

http://stackoverflow.com/q/50944186
type: Question
type: AnsweredQuestion
favorite count: 0
accepted answer: http://stackoverflow.com/a/50944220
has title: Python IF/Else syntax not working
tagged with: python
answer count: 1
downvote count: 3
upvote count: 0
has body: I am facing problem in if/else condition. my code and error was as following &gt;&gt;&gt; y=50 &gt;&gt;&gt; if y&lt;0: y=0 print('Negative not acceptable.') elif y==0: SyntaxError: invalid syntax please suggest me to solve the problem. Thanks in advance. Saroware Mahmud.
score: -3
has answer: http://stackoverflow.com/a/50944220

http://stackoverflow.com/comment/89019342
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51012003
has text: Thank you, That's what I did. I forgot to close my own question. I have had issues with using Canopy together with Anaconda environment so I was hesitant in installing another version of OpenCV that maybe it would cause some issues

http://stackoverflow.com/comment/88826107
has text: You're right, there is a `run` method in [DiscoverRunner](https://github.com/django/django/blob/master/django/test/runner.py#LC569). Could you print what happen if you run tests with this runner but removing your own `run` method ?
comment on: http://stackoverflow.com/q/50912620
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88862307
type: QuestionComment
score: 0
has text: Your order for the second column is wrong I think. Also for the first column
comment on: http://stackoverflow.com/q/50931528
type: Comment

http://stackoverflow.com/comment/88984724
type: AnswerComment
type: Comment
score: 2
comment on: http://stackoverflow.com/a/50994231
has text: @minion See http://regex101.com/r/FH1zBY/1, last `A` is removed and it is not inside parentheses. Well, there is a problem with defining a string between parentheses. Is `( ( A )` inside parentheses here? If yes, you should replace all `[^()]` with `[^)]` in my patterns. If you also decide that `A` in `(bb(d(dcv)A))` is also inside parentheses, you would need a different approach. With PyPi regex, it would be `regex.sub(r'\((?:[^()]++|(?R))*\)', lambda x: x.group().replace('A', ''), s)`.

http://stackoverflow.com/comment/88918380
type: QuestionComment
comment on: http://stackoverflow.com/q/50939323
score: 0
has text: @api55 I fixed a problem. i changed "tcp" to "udp" on opencv code, and compiled. but show crash frame... hmm
type: Comment

http://stackoverflow.com/comment/88809399
type: Comment
score: 1
comment on: http://stackoverflow.com/q/50904327
type: QuestionComment
has text: @dozer: the accepted answer also suggest to use `shlex` which could help here.

http://stackoverflow.com/comment/89030026
type: Comment
has text: @user726763 are you sure that you use `(` and `)` correct ?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51007306

http://stackoverflow.com/q/50877011
score: 0
has body: I am work actually on a machine learning system using : GA (Genetics Algorithm) + NN (Neural Network) using native Python. Concerning the NN part: All NN are multi layered neural network (inspired by this), the layers topology (number of neurons inside each layer and the number of layers) are randomly chose initially, then each NN are train (Reinforcement Learning) with the same training data. All NN have the exact same number of input and output, but not the same deep layer topology. Concerning the GA part: The population is composed by list of trained multi layered NN I confront population to the "reality" [reality is a list of life frame, the reality is encoded as pandas data-frame where each line is corresponding to a frame (I use the frame as NN input) ], and depending on the NN output, the individual will act or not. After that all frames are treated, I note the population ( relatively to the action), then make selection, keep elite, generate random new NN but also apply reproduction scheme via GA to generate new childs NN. Child NN will herit the layer topology of one of the parent and genetics of the mix of the parents (with alteration via cross over and mutation) All children will then be trained (with the same training data than parents) then I confront them to the reality then note each children etc... and do that generation after generation. I expect that this work, because the note will increase generation after generation I hope to implement something like parental education: I expect that children will be "helped/or receive live feedback" by parent : during a part of the child NN reinforcement learning procedure in order to "optimize" how the child neuronal weight are change during child training procedure. during the phase where the child NN is confront to the reality Anyone could share some source, or share feedback if already work on this kind of implementation ? Do you think it may help to increase learning efficiency or it is absolutely un-useful…
has comment: http://stackoverflow.com/comment/88762786
answer count: 0
type: UnansweredQuestion
tagged with: machine-learning
upvote count: 1
tagged with: python
has title: Best way to implement a "parental help/feedback" during child training in a GA+NN
downvote count: 1
tagged with: genetic-algorithm
type: Question
has comment: http://stackoverflow.com/comment/88762408
tagged with: neural-network
favorite count: 0
has comment: http://stackoverflow.com/comment/88763014

http://stackoverflow.com/q/50951632
has comment: http://stackoverflow.com/comment/88901976
has title: "OSError: [Errno 24] Too many open files:" with sockets from aiocoap context.request()
has comment: http://stackoverflow.com/comment/88902847
tagged with: coap
has comment: http://stackoverflow.com/comment/88904396
type: Question
has comment: http://stackoverflow.com/comment/88903258
has comment: http://stackoverflow.com/comment/88902476
has comment: http://stackoverflow.com/comment/88902315
has comment: http://stackoverflow.com/comment/88902464
has comment: http://stackoverflow.com/comment/88902334
score: 0
has answer: http://stackoverflow.com/a/50953654
accepted answer: http://stackoverflow.com/a/50953654
tagged with: raspberry-pi
has comment: http://stackoverflow.com/comment/88902538
has comment: http://stackoverflow.com/comment/88902712
answer count: 1
has comment: http://stackoverflow.com/comment/88902582
has comment: http://stackoverflow.com/comment/88902227
has body: Hello i am working on a raspberry PI which is supposed to send continuously data from sensors connected to this PI so here is my script : import logging import asyncio from grovepi import* import time import json from aiocoap import * logging.basicConfig(level=logging.INFO) def createMsg( file,value ) : f= open(file + "Config.json") data = json.load(f) f.close() data["timestamp"] = str(round(time.time(), 3)) data["value"] = value return json.dumps( data ) async def main(): #analog soundSensorPort=0 lightSensorPort=1 #digital motionSensorPort=2 tempSensorPort=2 ultrasonicSensorPort=5 pinMode(tempSensorPort, "INPUT") while True: context = await Context.create_client_context() await asyncio.sleep(2) [ tempSensorValue, humiditySensorValue ] = dht(tempSensorPort, 0) tempMsg = createMsg( "temperatureSensor", tempSensorValue) humidityMsg = createMsg( "humiditySensor", humiditySensorValue) payloadTemp = tempMsg.encode('utf-8') payloadHumidity = humidityMsg.encode('utf-8') requestTemp = Message(code=PUT, payload=payloadTemp) requestHumidity = Message(code=PUT, payload=payloadHumidity) requestTemp.opt.uri_host = '129.6.60.38' requestHumidity.opt.uri_host = '129.6.60.38' requestTemp.opt.uri_path = ("other", "sensors","temperature") requestHumidity.opt.uri_path = ("other", "sensors","humidity") responseTemp = await context.request(requestTemp).response responseHumidity = await context.request(requestHumidity).response print('Result: %s\n%r'%(responseTemp.code, responseTemp.payload)) print('Result: %s\n%r'%(responseHumidity.code, responseHumidity.payload)) if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main()) but after maybe 20/25 mins of running i have this error : File "clientPUT.py", line 84, in &lt;module&gt; File "/usr/lib/python3.5/asyncio/base_events.py", line 466, in run_until_complete File "/usr/lib/python3.5/asyncio/futures.py", line 293, in result File "/usr/lib/python3.5/asyncio/tasks.py", line 239, in _step File "clientPUT.py", line 63, in m…
has comment: http://stackoverflow.com/comment/88902673
has comment: http://stackoverflow.com/comment/88901875
tagged with: python-asyncio
has comment: http://stackoverflow.com/comment/88902078
has comment: http://stackoverflow.com/comment/88902500
has comment: http://stackoverflow.com/comment/88902820
tagged with: python
has comment: http://stackoverflow.com/comment/88902941
type: AnsweredQuestion

http://stackoverflow.com/q/50999768
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/51000045
tagged with: python
has comment: http://stackoverflow.com/comment/88993424
has comment: http://stackoverflow.com/comment/88993951
tagged with: bigdata
downvote count: 1
tagged with: indexing
type: AnsweredQuestion
tagged with: yelp
score: -1
type: Question
has body: I want to change this code to specifically read from line 1400001 to 1450000. What is modification? file is composed of a single object type, one JSON-object per-line. I want also to save the output to .csv file. what should I do? revu=[] with open("review.json", 'r',encoding="utf8") as f: for line in f: revu = json.loads(line[1400001:1450000)
has answer: http://stackoverflow.com/a/51000045
upvote count: 0
has comment: http://stackoverflow.com/comment/88993896
has title: read from line to line yelp dataset by python

http://stackoverflow.com/q/50973691
downvote count: 3
upvote count: 1
type: Question
score: -2
has comment: http://stackoverflow.com/comment/88944126
has comment: http://stackoverflow.com/comment/88943754
has title: Python code inside HTML file not working (Django)
has comment: http://stackoverflow.com/comment/88944518
answer count: 2
has answer: http://stackoverflow.com/a/50973832
tagged with: http://stackoverflow.com/tag/html
has body: I have two templates one is called index.html and the other cart.html. The index.html file accepts python code but if I put exactly the same code in cart.html Python is not recognised. I am working with Django. How can I fix this? index.html where python code works Title List of car parts available: {% for product in products_list %} {{ product.name }} {{ product.price }} {% if product.in_cart == False %} {{ product.ordered }} {% endfor %} cart.html where python code doesn't work Title List of car parts available: {% for product in products_list %} {{ product.name }} {{ product.price }} {% if product.in_cart == False %} {{ product.ordered }} {% endfor %} views.py from django.http import HttpResponse from django.template import loader from .models import Product # from django.shortcuts import render def index(request): products_list = Product.objects.all() template = loader.get_template('products/index.html') context = {'products_list': products_list} return HttpResponse(template.render(context, request)) def cart(request): cart_list = Product.objects.filter(in_cart == True) template = loader.get_template('products/cart.html') context = {'cart_list': cart_list} return HttpResponse(template.render(context, request))
favorite count: 0
type: UnansweredQuestion
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/50974565
has comment: http://stackoverflow.com/comment/88943750

http://stackoverflow.com/comment/88949182
has text: Using that sample data, I don't get the results you talk about. I get `([0.0029, 0.0029, 0.661, 0.0723, 0.0721, 0.0450, 0.0303, 0.0014, 0.0705], [0, 0, 2, 3, 4, 5, 6, 7, 8])`. Likely, my KDTree is coming out differently because of the smaller training data, but that indicates that it's probably some aspect of your trained tree that is causing these issues, not necessarily the code
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50975833
score: 0

http://stackoverflow.com/a/50988867
has body: This should do the trick .reset_index(drop=True)
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/89026261
answers question: http://stackoverflow.com/q/50988858

linux
tags question: http://stackoverflow.com/q/50871789
tags question: http://stackoverflow.com/q/50996419
tags question: http://stackoverflow.com/q/50873525
tags question: http://stackoverflow.com/q/50907383
tags question: http://stackoverflow.com/q/50860417
tags question: http://stackoverflow.com/q/50984100
tags question: http://stackoverflow.com/q/50923084
tags question: http://stackoverflow.com/q/51000284
tags question: http://stackoverflow.com/q/50904160
tags question: http://stackoverflow.com/q/50928989
type: Tag
tags question: http://stackoverflow.com/q/50920990
tags question: http://stackoverflow.com/q/50948054
tags question: http://stackoverflow.com/q/50883814
tags question: http://stackoverflow.com/q/50860785
tags question: http://stackoverflow.com/q/50897789
tags question: http://stackoverflow.com/q/50948656
tag name: linux
tags question: http://stackoverflow.com/q/50896965
tags question: http://stackoverflow.com/q/50985105
tags question: http://stackoverflow.com/q/51001773
tags question: http://stackoverflow.com/q/50997096
tags question: http://stackoverflow.com/q/50882971
tags question: http://stackoverflow.com/q/51000911
tags question: http://stackoverflow.com/q/50992705
tags question: http://stackoverflow.com/q/50949405
tags question: http://stackoverflow.com/q/50942365
tags question: http://stackoverflow.com/q/50912073
tags question: http://stackoverflow.com/q/50962527
tags question: http://stackoverflow.com/q/50892346
tags question: http://stackoverflow.com/q/51006884
tags question: http://stackoverflow.com/q/50915224
tags question: http://stackoverflow.com/q/50960344
tags question: http://stackoverflow.com/q/50957541
tags question: http://stackoverflow.com/q/50989913
tags question: http://stackoverflow.com/q/51007632

http://stackoverflow.com/q/51000056
favorite count: 0
type: Question
answer count: 2
tagged with: python
upvote count: 3
has body: I have a code to draw contour of object in a image and then draw a rectangle around them. i need to find widest diameter in my shape (two point) witch is straight horizontal line Now I need to find the points(coordinates of the pixels) that are inside the boundary of the object. heres my code: class App: def __init__(self, window, window_title, image_path="ex.jpg"): self.window = window self.window.title(window_title) # Load an image using OpenCV self.cv_img = cv2.cvtColor(cv2.imread(image_path), cv2.COLOR_BGR2RGB) # Get the image dimensions (OpenCV stores image data as NumPy ndarray) self.height, self.width, no_channels = self.cv_img.shape # Create a canvas that can fit the above image self.canvas = tkinter.Canvas(window, width = self.width, height = self.height) self.canvas.pack() # Use PIL (Pillow) to convert the NumPy ndarray to a PhotoImage self.photo = PIL.ImageTk.PhotoImage(image = PIL.Image.fromarray(self.cv_img)) # Add a PhotoImage to the Canvas self.canvas.create_image(0, 0, image=self.photo, anchor=tkinter.NW) # Button that lets the user blur the image self.btn_blur=tkinter.Button(window, text="Blur", width=25, command=self.blur_image) self.btn_blur.pack(anchor=tkinter.CENTER, expand=True) # Button that lets the user edeged the image self.btn_blur=tkinter.Button(window, text="edged", width=25, command=self.edged_image) self.btn_blur.pack(anchor=tkinter.CENTER, expand=True) # Button that lets the user edeged the image self.btn_blur=tkinter.Button(window, text="draw box", width=25, command=self.draw_box) self.btn_blur.pack(anchor=tkinter.CENTER, expand=True) self.window.mainloop() # Callback for the "Blur" button def blur_image(self): self.cv_img = cv2.blur(self.cv_img, (3, 3)) self.photo = PIL.ImageTk.PhotoImage(image = PIL.Image.fromarray(self.cv_img)) self.canvas.create_image(0, 0, image=self.photo, anchor=tkinter.NW) # Callback for the "edged" button def edged_image(self): #edeged image self.cv_img=cv2.Canny(self.cv_img,50,180) self.cv_img = cv2.dilate(…
tagged with: image-processing
possible better answer: http://stackoverflow.com/a/51001658
has answer: http://stackoverflow.com/a/51001658
has comment: http://stackoverflow.com/comment/88997091
has answer: http://stackoverflow.com/a/51001823
type: AnsweredQuestion
score: 3
has title: Find contour and boundary to obtain points inside image OpenCV Python
downvote count: 0
accepted answer: http://stackoverflow.com/a/51001823

http://stackoverflow.com/comment/88737545
type: QuestionComment
has text: But the example from the other question does correction first followed by prediction. Please check it out. Also my x and y positions are given by center and my initial state is not zero.
comment on: http://stackoverflow.com/q/50863397
score: 0
type: Comment

http://stackoverflow.com/comment/88835715
comment on: http://stackoverflow.com/a/50914972
has text: I noticed that the OTSU thresholding is great (I tried with a standard thresholding, non OTSU, it's a lot worse!), `cv2.threshold(gray, 0, 255, cv2.THRESH_OTSU+cv2.THRESH_BINARY)` is very important! Thanks for this important concept!
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/50879725
upvote count: 4
has comment: http://stackoverflow.com/comment/88762708
has body: The exact thing that you want is not possible. However, you can do the following: from sklearn.datasets import load_iris data = load_iris() print(data.DESCR) And read the description The data set contains 3 classes of 50 instances each, where each class refers to a type of iris plant.
answers question: http://stackoverflow.com/q/50877785
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50877785
has comment: http://stackoverflow.com/comment/88763437
has comment: http://stackoverflow.com/comment/131918719
score: 4
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/q/50968543
has answer: http://stackoverflow.com/a/50970044
tagged with: python
tagged with: kivy
type: AnsweredQuestion
has title: How to change the background color of a kivy Graph?
has comment: http://stackoverflow.com/comment/88974167
accepted answer: http://stackoverflow.com/a/50970044
score: 1
upvote count: 1
type: Question
downvote count: 0
answer count: 1
has body: Does it exist a property similar to the one below to change the background color of a Graph in Kivy? test.kv Graph: id: my_graph_id border_color = (0,0,0,0) # this is valid background_color = (0,0,0,0) # ?? this does not exist
favorite count: 0
tagged with: kivy-language

http://stackoverflow.com/q/50862925
type: Question
has title: How To Create a Local Web-based Anaconda Channel?
has body: How does one create a local conda channel that is web based instead of file based? There is an existing question on custom channels but the solution is file based, e.g. conda -c file://... Similarly, the documentation covers file channels pretty well. However, I am looking for an artifact repository or other http solution. Thank you in advance for your consideration and response.
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/52168037
tagged with: python
type: AnsweredQuestion
tagged with: anaconda
linked to: http://stackoverflow.com/q/35359147
accepted answer: http://stackoverflow.com/a/52168037

http://stackoverflow.com/comment/89008304
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51007631
has text: What have you attempted so far? What have you researched? Post some code. Maybe read the question guidelines? https://stackoverflow.com/help/how-to-ask

http://stackoverflow.com/comment/88836621
has text: Just tried the `malebutton = WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.ID, 'd2a4a28a-cdb5-47ed-8723-df28df2c0f06')))` but no luck sadly
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50918093
type: QuestionComment

http://stackoverflow.com/q/51001483
tagged with: network-programming
has answer: http://stackoverflow.com/a/51002314
has title: Python List all devices on local network, along with ip address
has comment: http://stackoverflow.com/comment/88996764
score: 0
answer count: 1
favorite count: 0
tagged with: python-3.x
linked to: http://stackoverflow.com/q/207234
type: UnansweredQuestion
tagged with: nmap
upvote count: 1
tagged with: python
duplicate of: http://stackoverflow.com/q/207234
has body: I'm trying to somehow get a list of all connected devices on a network, and then show their ip with it. I want it to show something like this: computername - 192.168.0.0 computer2 - 192.168.100.43 I have tried nmap and after a long time I was able to use it but it wont work. I'm using Python 3.6.5, Windows 8.1. If anyone could answer, it would help a lot. Edit: I did go here before, but I'm not sure how to list the names and ip using that method.
downvote count: 1
type: Question

http://stackoverflow.com/q/50873652
has body: i have several 16bit binary files, that i need to convert into 32bit binary files in python. i have tried the following: data16 = np.fromfile(data_dir+fn, dtype=np.uint16) print("16bit " + str(data16)) convert = np.array(data16 * 256) print("32bit " + str(convert) + "\n") Im new to dealing with datafiles and bytes etc. but from what i have read in the past few hours, this should work, shouldnt it? based on the output that i have read, it seems to work in some parts but not in others... quite confusing.. Here is the output: 16bit [41238 273 257 ... 65456 65472 65482] 32bit [ 5632 4352 256 ... 45056 49152 51712] 16bit [41238 273 769 ... 4 1 65521] 32bit [ 5632 4352 256 ... 1024 256 61696] 16bit [41238 273 513 ... 52 75 67] 32bit [ 5632 4352 256 ... 13312 19200 17152] Here a portion of the bits (files are huge, pycharm only prints some out). In the last row the last 3 bits are correctly converted but not all of the bits, why is that?
type: Question
tagged with: numpy
tagged with: data-conversion
possible better answer: http://stackoverflow.com/a/50874031
tagged with: 32-bit
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/50873917
tagged with: python
type: AnsweredQuestion
tagged with: 16-bit
has title: How to convert 16bit binary file to 32bit file?
has answer: http://stackoverflow.com/a/50874031
has answer: http://stackoverflow.com/a/50873917

fonts
tags question: http://stackoverflow.com/q/50875637
type: Tag
tag name: fonts

http://stackoverflow.com/comment/88837272
comment on: http://stackoverflow.com/q/50918538
score: 0
has text: In your 2nd snippet, you never create Amp. In your 3rd one, you never assign anything to Amp. Are you used to using matlab? Unlike Matlab, variables don't 'stick around' from one run to the next. If you execute the 1st snippet of code, all those variables disappear at the end of the execution.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88725908
score: 0
type: AnswerComment
type: Comment
has text: I figured it out, I had to drop columns where all the values were np.nan - then it works like a charm! Thank you very much!
comment on: http://stackoverflow.com/a/50861266

http://stackoverflow.com/a/51005595
accepted answer of: http://stackoverflow.com/q/51004076
answers question: http://stackoverflow.com/q/51004076
type: Answer
has body: As you can see in the below description at this example URL from your scraping, null is a main feature of the data which is being entered in your data frame as "None". You can change your None type using "fillna" from Pandas. I used 0 in this example which could work with your groupby, or you could do "nan" since "NA groups in GroupBy are automatically excluded," per their docs. from numpy import nan comtrade = comtrade.fillna(value=0, inplace=True)
score: 0
type: AcceptedAnswer

http://stackoverflow.com/q/50855654
answer count: 1
has comment: http://stackoverflow.com/comment/88715981
upvote count: 3
has comment: http://stackoverflow.com/comment/88715739
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/88713969
has comment: http://stackoverflow.com/comment/88716266
has answer: http://stackoverflow.com/a/50860278
accepted answer: http://stackoverflow.com/a/50860278
has comment: http://stackoverflow.com/comment/88715947
has title: Add to list if string not present in cell value, break and start new list if present?
tagged with: openpyxl
has comment: http://stackoverflow.com/comment/88715785
has body: I am trying to iterate over a column in Excel and check if a string is present. If the string is present, I want to reset the list to [] and repeat the process. Spent too many hours on this and I can't seem to figure out what I am doing wrong. Example data: Open Ended Schemes(Balanced) Aditya Birla Sun Life Mutual Fund 120518 Aditya Birla Sun Life Equity Hybrid'95 Fund - Direct Plan-Dividend 120517 Aditya Birla Sun Life Equity Hybrid'95 Fund - Direct Plan-Growth Open Ended Schemes(Debt Scheme - Banking and PSU Fund) Axis Mutual Fund 128953 Axis Banking &amp; PSU Debt Fund - Bonus Option 117447 Axis Banking &amp; PSU Debt Fund - Daily Dividend Option Code: from openpyxl import load_workbook import os wb = load_workbook('m.xlsx') ws = wb.active keys = ['1', '2'] m_dict = {} scheme_codes = [] for g in groups[0:2]: for row in ws.iter_rows('A{}:A{}'.format(ws.min_row +1, ws.max_row)): # scheme_codes = [] for cell in row: if cell.value != None: if 'Schemes' in cell.value: print('Found Schemes' + str(cell.value)) scheme_codes=[] break else: scheme = cell.value scheme_codes.append(scheme) m_dict[g] = scheme_codes I only get 1 item per scheme, I have tried various ways of doing this and either it just goes all the way through the rows. The file has 18000 rows. Expected output {1:[All items before first repeat of 'schemes' in 'A' column], 2:[All items before 2nd repeat of 'schemes' in 'A' column] Right now when I run the code, I get a len(scheme_codes) = 8069 which is wrong as far as I can see. The first list should be near 80 items.
type: AnsweredQuestion
score: 3
downvote count: 0
type: Question
has comment: http://stackoverflow.com/comment/88715725
has comment: http://stackoverflow.com/comment/88714259

http://stackoverflow.com/a/50885568
has comment: http://stackoverflow.com/comment/88830314
has comment: http://stackoverflow.com/comment/88773392
has comment: http://stackoverflow.com/comment/88773513
score: 0
has comment: http://stackoverflow.com/comment/88773605
type: Answer
answers question: http://stackoverflow.com/q/50885421
has body: By assigning a function to a variable: y = x the reference of object of x() is stored in variable y when you call the assigned variable as a function by: y() this calls the function x by using the stored reference
has comment: http://stackoverflow.com/comment/88794004
has comment: http://stackoverflow.com/comment/88773359

http://stackoverflow.com/q/51003146
has body: While trying to update my code to be PEP-484 compliant (I'm using mypy 0.610) I've ran into the following report: $ mypy mymodule --strict-optional --ignore-missing-imports --disallow-untyped-calls --python-version 3.6 myfile.py:154: error: Signature of "deliver" incompatible with supertype "MyClass" MyClass: from abc import abstractmethod from typing import Any class MyClass(object): @abstractmethod def deliver(self, *args: Any, **kwargs: Any) -> bool: raise NotImplementedError myfile.py: class MyImplementation(MyClass): [...] def deliver(self, source_path: str, dest_branches: list, commit_msg: str = None, exclude_files: list = None) -> bool: [...] return True I'm definitely doing something wrong here, but I can't quite understand what Any pointers would be much appreciated.
has answer: http://stackoverflow.com/a/51003172
has comment: http://stackoverflow.com/comment/137344924
tagged with: python
upvote count: 23
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/56374739
has answer: http://stackoverflow.com/a/56374739
has answer: http://stackoverflow.com/a/70231676
type: Question
tagged with: mypy
accepted answer: http://stackoverflow.com/a/51003172
has comment: http://stackoverflow.com/comment/137344932
answer count: 3
downvote count: 0
has title: Signature of {method} incompatible with super type {Class}
tagged with: python-typing
score: 23
favorite count: 0

http://stackoverflow.com/a/50999226
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89017290
type: Answer
accepted answer of: http://stackoverflow.com/q/50998718
has comment: http://stackoverflow.com/comment/89020051
has comment: http://stackoverflow.com/comment/89017577
answers question: http://stackoverflow.com/q/50998718
has comment: http://stackoverflow.com/comment/89023902
upvote count: 1
score: 1
has body: Using ElementTree. XML = """&lt;root&gt; &lt;way id="11005330" version="2" timestamp="2013-02-05T20:56:45Z" changeset="14926577" uid="451693" user="bot-mode"&gt; &lt;nd ref="98006629"/&gt; &lt;nd ref="98006630"/&gt; &lt;nd ref="98006631"/&gt; &lt;tag k="highway" v="residential"/&gt; &lt;tag k="name" v="Kiwi Court"/&gt; &lt;tag k="tiger:cfcc" v="A41"/&gt; &lt;tag k="tiger:county" v="Lake, FL"/&gt; &lt;tag k="tiger:name_base" v="Kiwi"/&gt; &lt;tag k="tiger:name_type" v="Ct"/&gt; &lt;tag k="tiger:reviewed" v="no"/&gt; &lt;tag k="tiger:zip_left" v="34714"/&gt; &lt;tag k="tiger:zip_right" v="34714"/&gt; &lt;/way&gt; &lt;/root&gt;""" Demo: import xml.etree.ElementTree as ET tree = ET.parse(filename) doc = tree.getroot() for way in doc.findall(".//way"): #Find all way tags name_base = way.find('.//tag[@k="tiger:name_base"]').get("v") #Get tiger:name_base attr way.remove(way.find('.//tag[@k="tiger:name_base"]')) #Remove Tag name_type = way.find('.//tag[@k="tiger:name_type"]').get("v") #Get tiger:name_type attr way.remove(way.find('.//tag[@k="tiger:name_type"]')) #Remove Tag newNode = ET.SubElement(way, '''tag k="addr:street" v="{} {}"'''.format(name_base, name_type)) #Add New Tag tree.write(r"C:\Users\Rakesh\Desktop\testFiles\A2.xml") #Write to file Output: &lt;root&gt; &lt;way changeset="14926577" id="11005330" timestamp="2013-02-05T20:56:45Z" uid="451693" user="bot-mode" version="2"&gt; &lt;nd ref="98006629" /&gt; &lt;nd ref="98006630" /&gt; &lt;nd ref="98006631" /&gt; &lt;tag k="highway" v="residential" /&gt; &lt;tag k="name" v="Kiwi Court" /&gt; &lt;tag k="tiger:cfcc" v="A41" /&gt; &lt;tag k="tiger:county" v="Lake, FL" /&gt; &lt;tag k="tiger:reviewed" v="no" /&gt; &lt;tag k="tiger:zip_left" v="34714" /&gt; &lt;tag k="tiger:zip_right" v="34714" /&gt; &lt;tag k="addr:street" v="Kiwi Ct" /&gt;&lt;/way&gt; &lt;/root&gt;
has comment: http://stackoverflow.com/comment/89038764

http://stackoverflow.com/comment/88880738
comment on: http://stackoverflow.com/q/50941570
score: 7
has text: You never called `split()`. You called `strip()`
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50954882
score: 1
answers question: http://stackoverflow.com/q/50954794
upvote count: 1
has comment: http://stackoverflow.com/comment/88907759
has body: You get the result you see because builtin_print() calls PyFile_Write*() twice, once in order to print the argument, and again to print the EOL. They are out of order because by default stderr is unbuffered and stdout is line-buffered.
downvote count: 0
type: Answer

http://stackoverflow.com/comment/88910550
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50956456
score: 1
has text: Please explain the output logic. "B-I-L belong to each other" is not sufficient to detail the logic of your number prefixes. I strongly suspect that your logic and `regex` are overkill for what you need to do.

http://stackoverflow.com/comment/89013923
comment on: http://stackoverflow.com/a/51010447
score: 0
type: Comment
has text: Your suggested portion makes it even worse. This is the error I'm having now `Traceback (most recent call last): File "some address", line 2552, in open fp.seek(0) AttributeError: 'PageObject' object has no attribute 'seek' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "some address", line 8, in <module> img = Image.open(pdfReader.getPage(0), 'r').convert('L') File "some address", line 2554, in open fp = io.BytesIO(fp.read()) AttributeError: 'PageObject' object has no attribute 'read'`.
type: AnswerComment

http://stackoverflow.com/q/50892153
tagged with: python
tagged with: opencv
score: 3
has title: redirect from another module (Flask)
has comment: http://stackoverflow.com/comment/88796391
type: Question
has comment: http://stackoverflow.com/comment/88786290
downvote count: 0
tagged with: flask
has body: So I have a opencv flask camera streaming code. The function generating the frame to be streamed is outside app.py. I want to be able to automatically stop the stream and redirect to page2 when an event happens. I tried to do it in @app.route('/video_feed') as the code below shows. I spent two days with no results. app.py from flask import Flask, render_template, Response, redirect, url_for, import cv2 from applogic import AppLogic app = Flask(__name__) vc = cv2.VideoCapture(0) applogic = AppLogic() @app.route('/') def index(): """Video streaming home page.""" return render_template('index.html') @app.route('/page2') def page2(): """the page to be redirected to when event happens.""" return render_template('page2.html') @app.route('/video_feed') def video_feed(): """Video streaming route. Put this in the src attribute of an img tag.""" temp = applogic.gen() if temp != 1 return Response(applogic.gen(), mimetype='multipart/x-mixed-replace; boundary=frame') else: return redirect(url_for('page2')) if __name__ == '__main__': app.run(host='127.0.0.1]', debug=True, threaded=True) applogic.py (please mind the indentation): import cv2 class AppLogic: def __init__(self): self.checkx = True self.vc = cv2.VideoCapture(0) def gen(self): while True: if self.foo(): rval, frame = self.vc.read() cv2.imwrite('t.jpg', frame) yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + open('t.jpg', 'rb').read() + b'\r\n') else: return 1 def foo(self): # some logic that returns True or False return True index.html: Video Streaming Demonstration Video Streaming Demonstration page2.html: has a normal html "hello world" code; nothing special Thank you.
favorite count: 0
answer count: 0
type: UnansweredQuestion
upvote count: 3
has comment: http://stackoverflow.com/comment/88787795

http://stackoverflow.com/comment/88913722
type: Comment
type: QuestionComment
score: 0
has text: `--find-links` makes `pip` to look into either a directory with tars/eggs/wheels or an HTML file with links to packages in downloadable forms. You cannot just point it to a local project.
comment on: http://stackoverflow.com/q/50957833

http://stackoverflow.com/comment/88859938
type: Comment
score: 1
comment on: http://stackoverflow.com/a/50930250
type: AnswerComment
has text: Oh theres a space in middle too. Din't notice. As always cool answer :)

http://stackoverflow.com/comment/88899143
has text: try running the code again ( I just made an edit ), Well I don't have an account on the website so I can't really check :)
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50950369
type: Comment

http://stackoverflow.com/q/50969421
type: Question
has body: I am trying to establish a mqtt client on my pc, So I start writing a script in python. When I run the script from Python IDLE it works fine and stable. I downloaded AlwaysUp and created a service. When I run the service it stops after 5s. import paho.mqtt.client as mqtt #import the client1 import time import os strshtdwn=0 def on_log(clint, userdata,level, buf): print("log: "+buf) def on_connect(client,userdata, flags ,rc): if rc==0: print("Connected OK") else: print("Bad connection Returned code=",rc) def on_disconnect(client, userdata, flags, rc=9): print("DisConnected result code "+str(rc)) def on_message(clinet, userdata, msg): topic=msg.topic m_decode=str(msg.payload.decode("utf-8","ignore")) if m_decode=="SHUTDOWN": os.system("shutdown /p") client.publish("stat/hwa_rang_pc/POWER","Shuting Down") elif m_decode=="RESTART": os.system("shutdown /r") client.publish("stat/hwa_rang_pc/POWER","Restarting") elif m_decode=="LOGOFF": os.system("shutdown /l") client.publish("stat/hwa_rang_pc/POWER","Logging OFF") print("message received: ",m_decode) print("strshtdwn",strshtdwn) broker="192.168.1.3" client = mqtt.Client("Hwa_Rang_PC") #create new instance client.on_connect=on_connect client.on_disconnect=on_disconnect #client.on_log=on_log client.on_message=on_message print("Connecting to broker ",broker) client.connect(broker) #connect to broker client.loop_start() client.subscribe("cmnd/hwa_rang_pc/power") client.publish("stat/hwa_rang_pc/POWER","OFF") #client.loop_stop() #client.disconnect() #disconnect Error by event viewer are 3 at a try . Two with ID "2" and one with ID "7023". help plz!!!
score: -1
has answer: http://stackoverflow.com/a/50969712
answer count: 1
favorite count: 0
tagged with: python
has title: win10 Service STOP after start (python script created by AlwaysUp)
tagged with: service
type: UnansweredQuestion
downvote count: 2
upvote count: 1

http://stackoverflow.com/comment/129404961
has text: I think the NeXT system crashed because I clicked the mouse between window changes and it didn't find a proper target. That was my best guess.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51004832
type: Comment

http://stackoverflow.com/comment/89125194
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51010315
has text: I'm using windows 7 @Tarun Lalwani. Your solution hardly fails so I'm very much hopeful now. Btw, do I need to install anything else other than `pdf2image` in order for your suggested script work? Plus one in advance..
score: 0

http://stackoverflow.com/tag/json
tags question: http://stackoverflow.com/q/50990123
tags question: http://stackoverflow.com/q/50959819
tags question: http://stackoverflow.com/q/50874265
tags question: http://stackoverflow.com/q/51008968
tags question: http://stackoverflow.com/q/50893458
tags question: http://stackoverflow.com/q/51001914
tags question: http://stackoverflow.com/q/50951681
tags question: http://stackoverflow.com/q/50892429
tags question: http://stackoverflow.com/q/50858303
tags question: http://stackoverflow.com/q/50865953
tags question: http://stackoverflow.com/q/50966114
tags question: http://stackoverflow.com/q/50867539
tags question: http://stackoverflow.com/q/50983959
tags question: http://stackoverflow.com/q/50920960
tags question: http://stackoverflow.com/q/50916834
tags question: http://stackoverflow.com/q/50899413
tags question: http://stackoverflow.com/q/50883008
tags question: http://stackoverflow.com/q/50951803
tags question: http://stackoverflow.com/q/50926412
tags question: http://stackoverflow.com/q/50935272
tags question: http://stackoverflow.com/q/50966434
tags question: http://stackoverflow.com/q/50924824
tags question: http://stackoverflow.com/q/50859101
tags question: http://stackoverflow.com/q/50881690
tags question: http://stackoverflow.com/q/50872681
tags question: http://stackoverflow.com/q/50909876
tags question: http://stackoverflow.com/q/50978456
tags question: http://stackoverflow.com/q/50946258
tags question: http://stackoverflow.com/q/50880647
tags question: http://stackoverflow.com/q/50910638
tags question: http://stackoverflow.com/q/50873610
tags question: http://stackoverflow.com/q/50947760
tags question: http://stackoverflow.com/q/50932087
tags question: http://stackoverflow.com/q/50937891
tags question: http://stackoverflow.com/q/50900340
type: Tag
tags question: http://stackoverflow.com/q/50939977
tags question: http://stackoverflow.com/q/50968008
tags question: http://stackoverflow.com/q/50893515
tags question: http://stackoverflow.com/q/50907023
tags question: http://stackoverflow.com/q/50917856
tags question: http://stackoverflow.com/q/50866870
tags question: http://stackoverflow.com/q/50908869
tags question: http://stackoverflow.com/q/50949010
tags question: http://stackoverflow.com/q/51010647
tags question: http://stackoverflow.com/q/50925137
tags question: http://stackoverflow.com/q/50924752
tags question: http://stackoverflow.com/q/50942411
tags question: http://stackoverflow.com/q/50933694
tags question: http://stackoverflow.com/q/50981821
tags question: http://stackoverflow.com/q/50954397
tags question: http://stackoverflow.com/q/50893045
tags question: http://stackoverflow.com/q/50909786
tags question: http://stackoverflow.com/q/50939068
tags question: http://stackoverflow.com/q/50896807
tags question: http://stackoverflow.com/q/50891215
tags question: http://stackoverflow.com/q/50861016
tags question: http://stackoverflow.com/q/50918185
tags question: http://stackoverflow.com/q/50947689
tags question: http://stackoverflow.com/q/50890686
tags question: http://stackoverflow.com/q/50947008
tags question: http://stackoverflow.com/q/50898607
tags question: http://stackoverflow.com/q/50964737
tags question: http://stackoverflow.com/q/50907015
tags question: http://stackoverflow.com/q/50984642
tags question: http://stackoverflow.com/q/50871767
tags question: http://stackoverflow.com/q/50975224
tags question: http://stackoverflow.com/q/50917052
tags question: http://stackoverflow.com/q/50914127
tags question: http://stackoverflow.com/q/50876655
tags question: http://stackoverflow.com/q/50949476
tags question: http://stackoverflow.com/q/50925562
tag name: json
tags question: http://stackoverflow.com/q/50913515
tags question: http://stackoverflow.com/q/50897891
tags question: http://stackoverflow.com/q/50974493
tags question: http://stackoverflow.com/q/50920051
tags question: http://stackoverflow.com/q/50903697
tags question: http://stackoverflow.com/q/50987650
tags question: http://stackoverflow.com/q/50966390

http://stackoverflow.com/comment/88828902
has text: @abarnert sure that's working too. But I think its better use `.txt` as OP is specific about .txt files.
type: Comment
comment on: http://stackoverflow.com/a/50913984
type: AnswerComment
score: 0

http://stackoverflow.com/comment/88912854
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50957675
type: Comment
has text: Does the variable `self` in the class `Outside` refer to the class `Outside`, or it refers to an *instance* of `Outside`?

http://stackoverflow.com/a/50878088
answers question: http://stackoverflow.com/q/50877893
has comment: http://stackoverflow.com/comment/88759620
has comment: http://stackoverflow.com/comment/88758243
has comment: http://stackoverflow.com/comment/88758319
score: 0
has body: You can use numpy.vectorize in the following way import numpy as np def custom_print(n, f): print("n = {}, function = {}".format(n, f)) vprint = np.vectorize(custom_print) n = np.array([1, 2, 3]) f = np.array([1, 4, 9]) vprint(n, f) Output n = 1, function = 1 n = 2, function = 4 n = 3, function = 9 Note: As FHTMitchell stated in the comments The vectorize function is provided primarily for convenience, not for performance. The implementation is essentially a for loop. (from the docpage: https://docs.scipy.org/doc/numpy/reference/generated/numpy.vectorize.html)
type: Answer
has comment: http://stackoverflow.com/comment/88758587

http://stackoverflow.com/a/51004116
accepted answer of: http://stackoverflow.com/q/50977894
has body: The solution of the equation Ly=b can be found by inverting the matrix L and left multiplying on both sides so you get: y=L'b, where L' is the inverse matrix of L. Inverting this matrix can be done with e.g. np.linalg.inv. To do an inversion of the matrix without using numpy, would be tedious. However, I suspect you might be able to do this quite nicely since you have a lower triangular unit matrix. The inverse of the lower triangular unit matrix L, (with 1s also on the diagonal) can be shown to be def Linv(i,j): if i==j: return 1 elif j==i-1: return -1 There might be better ways to calculate it, but here is one way: import numpy as np from scipy.linalg import circulant L=np.tril(np.ones((4,4))) dim=L.shape[0] Linv=[np.concatenate([np.array([1,-1]), np.zeros(dim-2)])] Linv=np.tril(circulant(Linv)) print(Linv) Here is more info on the circulant matrix function. Now, getting it all together: import numpy as np from scipy.linalg import circulant def L_inv(l_dim): Linv=[np.concatenate([np.array([1,-1]), np.zeros(l_dim-2)])] Linv=tril(circulant(Linv)) def solve_forward(L, b): y = L_inv(L.shape[0]) @ b return y Which should work as expected. Edit: The previous toeplitz would not work in this case. Switched it with the more appropriate circulant. Edit 2: Only the lower triangular part of the circulant should be used.
answers question: http://stackoverflow.com/q/50977894
score: 1
downvote count: 1
type: AcceptedAnswer
upvote count: 2
type: Answer

http://stackoverflow.com/q/50963612
tagged with: python
has comment: http://stackoverflow.com/comment/88927209
has comment: http://stackoverflow.com/comment/88923863
tagged with: c++
has answer: http://stackoverflow.com/a/51127258
type: UnansweredQuestion
type: Question
tagged with: ctypes
tagged with: dll
has body: I am struggeling with the following problem, which is, I guess, not that complicated for people with more advanced C skills. My intention is to access C++ funtions stored in an DLL from Python. I managed to get this running for simple functions as ADD and MULT. As the funtions I'd like to access (later) will return multiple float values I need tu use pointers. I'd like to do the following basic steps: -Create a variable in python, -Transfer the pointer to the dll (ctypes --> c_pointer(...)), -Update the value the pointer is referring to; -go back to python and use the modified value. My C++ funtion I used for dll creation is: #include &lt;stdio.h&gt; #include &lt;wchar.h&gt; #include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;math.h&gt; #include &lt;fstream&gt; using namespace::std; extern "C" { __declspec(dllexport) int Kappel(double a, double *f){ *f = 25.5; return 0; } } // extern "C" My python code to call the function in the dll looks like: import os import os.path import ctypes from ctypes import pointer,c_long,c_int,c_double lib_path=os.path.dirname(os.path.abspath(__file__))+os.path.sep+'test.dll' lib = ctypes.CDLL(lib_path) lib.Kappel.resttype = pointer(c_double()) p = 1.5 Cp = c_double(1.5) Cp_ = pointer(c_double(p)) def test3(wert, zeiger): func = lib.Kappel Res = func(wert, zeiger) return Res #Output after modification print('Returnvalue: ', test3(Cp,Cp_)) print(p) print(Cp) print(Cp_) Thanks for any help Erik
score: 0
answer count: 2
tagged with: pointers
has title: Transferring Pointers from Python to dll and get modified values back
has answer: http://stackoverflow.com/a/50965554

http://stackoverflow.com/a/50909905
score: 0
has body: I just tested the code below works for me: import sys import numpy as np import pyqtgraph as pg from pyqtgraph.Qt import QtCore, QtGui, uic uifilename = 'test.ui' form_class = uic.loadUiType(uifilename)[0] #dirty reading of the ui file. better to convert it to a '.py' class MyWindowClass(QtGui.QMainWindow, form_class): def __init__(self): QtGui.QMainWindow.__init__(self) self.setupUi(self) self.onInit() def onInit(self): #usually a lot of connections here self.x_fit = np.linspace(1,10000, 10000) self.y_fit = [f(_x) for _x in self.x_fit] self.plotwidget.plot(self.x_fit,self.y_fit,symbol='o',pen=None) self.plotwidget.setLabel('left',text='toto',units='') self.plotwidget.setLabel('top',text='tata',units='') def f(x): return x**2+1 if __name__ == '__main__': if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'): app = QtGui.QApplication([]) pg.setConfigOption('background', 'w') win = MyWindowClass() win.show() app.exec_() with this test.ui : https://github.com/steph2016/profiles/blob/master/test.ui. Note the plotwidget is encapsulated inside a layout. I thought it works with just the Main Window, but I'm not sure anymore...
downvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/50905170
upvote count: 1

http://stackoverflow.com/q/50911444
has answer: http://stackoverflow.com/a/50932583
type: Question
has comment: http://stackoverflow.com/comment/88863241
score: 3
linked to: http://stackoverflow.com/q/1112343
tagged with: python-3.6
has title: How to stop background thread in Python
accepted answer: http://stackoverflow.com/a/50932583
has body: Here is the code snippet for illustration purpose. C1.infinite_loop() method is running as background thread. I want to make sure if somebody presses Ctrl+C then terminate the program gracefully. What method do i need to override and where to handle Ctrl+C signal ? I am thinking to set a flag when Ctrl+C is generated and periodically check inside C1.infinite_loop. If flag is true then come out of the loop ? Is this right approach or do you suggest something else ? import time import random from threading import Thread class C1: def __init__(self): self.list = list() def infinite_loop(self): while True: self.list.append(random.randint(1,10)) time.sleep(2) class C2: def __init__(self): print('inside C2 init') self.c1 = C1() def main(self): self.bg_th = Thread(target=self.c1.infinite_loop) self.bg_th.start() def disp(self): print(self.c1.list) c2 = C2() c2.main() time.sleep(2) c2.disp() c2.bg_th.join() One more question. List is shared between two threads here. C2 is reading and C1 is writing. Do i still need to use lock in such a case ?
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python-3.x
tagged with: python-multithreading
has comment: http://stackoverflow.com/comment/88863200
tagged with: python
has comment: http://stackoverflow.com/comment/88863257
type: AnsweredQuestion
upvote count: 3

http://stackoverflow.com/q/50862793
tagged with: dataframe
score: 0
answer count: 2
tagged with: pandas
upvote count: 1
downvote count: 1
has body: I have a column with numbers. I want to add another column, which shows the percentage to the max value. amount percentage 10 - 100% 3 - 30% 3 - 30% 4 - 40%
has answer: http://stackoverflow.com/a/50862848
favorite count: 0
tagged with: python
type: AnsweredQuestion
has title: Python Pandas values from another column
possible better answer: http://stackoverflow.com/a/50862848
type: Question
has answer: http://stackoverflow.com/a/50862816
accepted answer: http://stackoverflow.com/a/50862816

http://stackoverflow.com/q/50857927
duplicate of: http://stackoverflow.com/q/36526035
has comment: http://stackoverflow.com/comment/88718867
has comment: http://stackoverflow.com/comment/88718447
tagged with: numpy
has comment: http://stackoverflow.com/comment/88720361
answer count: 2
has comment: http://stackoverflow.com/comment/88718837
has comment: http://stackoverflow.com/comment/88721098
has comment: http://stackoverflow.com/comment/88719019
favorite count: 0
has comment: http://stackoverflow.com/comment/88718861
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50858536
linked to: http://stackoverflow.com/q/39983695
has answer: http://stackoverflow.com/a/50858419
score: 2
has title: Why is (3.3==np.asarray([3.3])) equal to [True] instead of False?
upvote count: 3
has comment: http://stackoverflow.com/comment/88719813
has comment: http://stackoverflow.com/comment/88719992
duplicate of: http://stackoverflow.com/q/35397801
downvote count: 1
tagged with: unit-testing
has comment: http://stackoverflow.com/comment/88720540
type: Question
has body: Following statement passes in my tests. self.assertEqual(3.3, np.asarray([3.3])) One type is numpy.float64 other is numpy.ndarray and my assumption was that this test will fail but it passes. Following statement prints [ True] print(3.3 == np.asarray([3.3])) Debugging further shows that assertEquals ends up invoking unittest.case.TestCase#_baseAssertEqual which checks equality using ==: if not first == second: standardMsg = '%s != %s' % _common_shorten_repr(first, second) msg = self._formatMessage(msg, standardMsg) raise self.failureException(msg) Can someone explain why and how test self.assertEqual(3.3, np.asarray([3.3])) passes? Edit: How == works in case you compare an array of one value with a variable and where is this behaviour documented?
tagged with: testing

http://stackoverflow.com/a/50871264
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/88744629
has body: You can iterate through the keys of your dict and retrieve the values to add them to a variable. So you would start by declaring the sum variables where you will store the sums, and iterate through every key in your dict to add the corresponding values to the sum variables. You could also easily add more values in the future by adding val3 and sum3, val4 and sum4, etc. Here is an example: my_dict = {'A':{'val1':3,'val2':5},'B':{'val1':2,'val2':6}} # initiate variables to store the sums sum1, sum2 = (0,) * 2 # iterate through the keys of your dict and increment the sum variables for key in my_dict: sum1 += my_dict[key]['val1'] sum2 += my_dict[key]['val2'] print(sum1) print(sum2) This prints: 5 11 Also, as @jpp mentioned, never name a variable after a class, so don't name your dictionnary dict e.g. you can name it my_dict
type: Answer
upvote count: 2
answers question: http://stackoverflow.com/q/50871095
has comment: http://stackoverflow.com/comment/88744676

http://stackoverflow.com/comment/88913068
has text: Just to end this post. I sent Avira Labs my file and they passed it as "clean" https://s22.postimg.cc/8h95grbxt/clean.png
comment on: http://stackoverflow.com/q/50949254
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88735800
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50866754
score: 0
has text: Command prompt may require more than one blank line to declare the end of loops, functions, etc.

http://stackoverflow.com/q/50956968
tagged with: bash
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/88919765
favorite count: 0
has comment: http://stackoverflow.com/comment/88911452
has answer: http://stackoverflow.com/a/50957535
tagged with: python
tagged with: design-patterns
type: AnsweredQuestion
score: 1
upvote count: 1
has title: Python or bash script: if pattern in lines between two identical markers, remove lines and first marker
type: Question
accepted answer: http://stackoverflow.com/a/50957535
tagged with: lines
tagged with: marker
has body: As a beginner, I'm trying to solve the following problem (bash or python script): the file (~50G!): marker xxx xxx xxx pattern marker xxx xxx xxx marker xxx xxx xxx pattern I would like to find a way to remove the lines between two markers + the first marker, but not the last occurrence of the marker IF no pattern can be found throughout the lines. Wanted result: marker xxx xxx xxx pattern [empty!] marker xxx xxx xxx pattern I tried to solve it with regex or awk (that's a very shy beginning) awk '/marker/{f=1} f; /marker/{f=1}' file but I'm having a hardtime understanding how to implement that in a function that would solve the entire problem. It would make me very happy if someone could help me with that! Cheers

http://stackoverflow.com/a/50880324
has comment: http://stackoverflow.com/comment/88763161
has body: Although highly frowned upon, some Python 2 code reloads sys to restore the sys.setdefaultencoding() function. This is almost always the cause of this problem. So you could detect that sys was reloaded by checking for the setdefaultencoding attribute: if hasattr(sys, 'setdefaultencoding'): # sys was reloaded! This would only work on Python 2. Or you could augment the sys.flags struct sequence with an extra field: from collections import namedtuple import sys, re _sys_flags_fields = re.findall('(\w+)=\d', repr(sys.flags)) _sys_flags_augmented = namedtuple('flags', _sys_flags_fields + ['sys_not_reloaded']) sys.flags = _sys_flags_augmented(*sys.flags + (1,)) after which you can test with: if not getattr(sys.flags, 'sys_not_reloaded', 0): Augmenting sys.flags is safer than most other sys manipulations, as third-party code might be relying on the documented sys attributes and methods to be untampered with, and it also works on Python 3. You could prevent sys from being reloaded by wrapping __builtin__.reload / importlib.reload / imp.reload: try: # Python 2 import __builtin__ as targetmodule except ImportError: # Python 3.4 and up try: import importlib as targetmodule targetmodule.reload # NameError for older Python 3 releases except (ImportError, AttributeError): # Python 3.0 - 3.3 import imp as targetmodule from functools import wraps def reload_wrapper(f): @wraps(f) def wrapper(module): if getattr(module, '__name__', None) == 'sys': raise ValueError('sys should never be reloaded!') return f(module) return wrapper targetmodule.reload = reload_wrapper(targetmodule.reload) Instead of raising an exception, you could just use the warnings module or some other mechanism to record or make noise about the fact that sys is being reloaded; you probably want to include the caller into such warnings. Execute the above module as early as possible to ensure that you can catch out the code that is doing this, possibly by inserting it into the sitecustomize module, or by triggering it…
has comment: http://stackoverflow.com/comment/88763049
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50880121
answers question: http://stackoverflow.com/q/50880121
type: Answer
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/88763194
has comment: http://stackoverflow.com/comment/88763843
has comment: http://stackoverflow.com/comment/88763075
has comment: http://stackoverflow.com/comment/88763471
upvote count: 2

http://stackoverflow.com/comment/88835423
comment on: http://stackoverflow.com/a/50917409
type: AnswerComment
has text: @emsimpson92: [Here it is](https://docs.python.org/2/reference/expressions.html?highlight=negative#slicings): "If either bound is negative, the sequence’s length is added to it."
score: 0
type: Comment

http://stackoverflow.com/a/50882868
downvote count: 0
has body: I work at Reelgood. Please note that the class names on https://reelgood.com change every-time we release a update to our web app. We are more than happy to lend a hand with whatever you're trying to accomplish here, feel free to shoot me an email at luigi@reelgood.com.
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/50882622
score: 1

http://stackoverflow.com/comment/88811318
comment on: http://stackoverflow.com/a/50876967
type: Comment
has text: Glad I could help! And you are right of course. I fixed it.
score: 1
type: AnswerComment

http://stackoverflow.com/comment/88845537
type: QuestionComment
has text: Whatever how you create that CSV file, you can just save it into a `BytesIO`, it is almost the same as save to a file. And then you can upload it as stream or bytes.
comment on: http://stackoverflow.com/q/50923055
score: 0
type: Comment

http://stackoverflow.com/a/50919948
downvote count: 0
answers question: http://stackoverflow.com/q/50919887
type: Answer
has body: You need to recreate list each time through the loop. On the first time through the loop, list and l_list are both empty: you get name and scores, append them to list and append that to l_list. All is good. But then you go through the loop a second time for your next skater. You append their name and scores to list which already has the previous skater's name and scored. Then you append that whole thing to l_list again. Now l_list has two copies of list, and list has both skaters and their scores. Adding list = [] before you call list.append() should resolve the issue.
upvote count: 2
score: 2

http://stackoverflow.com/comment/88987290
type: Comment
has text: `sort_values` takes tons of parameters, some of which are required. While your suggestion makes sense, technically it is incorrect.
type: AnswerComment
score: 4
comment on: http://stackoverflow.com/a/50996442

http://stackoverflow.com/q/50964115
has answer: http://stackoverflow.com/a/50964309
type: Question
score: 3
has comment: http://stackoverflow.com/comment/88924967
has title: BeautifulSoup webpage have protection and prettify() return no data
answer count: 1
downvote count: 0
favorite count: 0
tagged with: beautifulsoup
has body: I am trying to get some data from a wine website. But I can not assess the data and there have a usage violation message. The url : https://www.wine-searcher.com/find/drc/2013 The prettify() result something like that: Usage Violation Blocked The IP Address [xx.xxx.xxx.xx] you are using has been used in violation of Wine-Searcher's usage guidelines. If you think you have received this message in error restart your web browser and retry accessing wine-searcher.com. To re-gain access to Wine-Searcher please Contact Us . Is there any possible ways to get the data from the url? Thank you so much. My coding here : # -*- coding: utf-8 -*- import bs4 import re import requests import sys from bs4 import BeautifulSoup name = "Wine.txt" k = open(name, "w", encoding='utf-8') Stat_url = "https://www.wine-searcher.com/find/drc/2012" page = requests.get(Stat_url) soup = bs4.BeautifulSoup(page.text,'lxml') k.write(soup.prettify())
tagged with: python
upvote count: 3
type: UnansweredQuestion

http://stackoverflow.com/q/50996623
downvote count: 1
favorite count: 0
score: 8
upvote count: 9
has comment: http://stackoverflow.com/comment/88987635
tagged with: machine-learning
tagged with: python
has title: Could not convert string to float error from the Titanic competition
has comment: http://stackoverflow.com/comment/88987614
type: AnsweredQuestion
has body: I'm trying to solve the Titanic survival program from Kaggle. It's my first step in actually learning Machine Learning. I have a problem where the gender column causes an error. The stacktrace says could not convert string to float: 'female'. How did you guys come across this issue? I don't want solutions. I just want a practical approach to this problem because I do need the gender column to build my model. This is my code: import pandas as pd from sklearn.tree import DecisionTreeRegressor from sklearn.model_selection import train_test_split from sklearn.metrics import mean_absolute_error train_path = "C:\\Users\\Omar\\Downloads\\Titanic Data\\train.csv" train_data = pd.read_csv(train_path) columns_of_interest = ['Survived','Pclass', 'Sex', 'Age'] filtered_titanic_data = train_data.dropna(axis=0) x = filtered_titanic_data[columns_of_interest] y = filtered_titanic_data.Survived train_x, val_x, train_y, val_y = train_test_split(x, y, random_state=0) titanic_model = DecisionTreeRegressor() titanic_model.fit(train_x, train_y) val_predictions = titanic_model.predict(val_x) print(filtered_titanic_data)
type: Question
tagged with: numpy
tagged with: scikit-learn
has answer: http://stackoverflow.com/a/50996644
tagged with: pandas
accepted answer: http://stackoverflow.com/a/50996644
answer count: 1

http://stackoverflow.com/comment/88871436
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50932519
type: Comment
has text: Oops, `author`, not `user`

http://stackoverflow.com/q/50914245
has body: I'm in the process of creating an obfuscation neural network using Keras that will distort an image before being fed into a trained classification neural network. In order to do so, I need to generate a loss based on the value produced by the classification network. I have created a loss function that feeds the distorted image as y_pred, and the classification labels as y_true. class_model = load_model(model_path) def classfication_error(self, y_true, y_pred): y_pred = class_model.predict(y_pred) return keras.losses.categorical_crossentropy(y_true, y_pred) When compiling the model, I receive the following error due to the shape of y_pred = (?, 32, 32, 3) ValueError: When feeding symbolic tensors to a model, we expect thetensors to have a static batch size. Got tensor with shape: (None, 32, 32, 3) What would be another way to accomplish the prediction within the loss function as to avoid the error?
answer count: 0
type: UnansweredQuestion
tagged with: machine-learning
tagged with: python
tagged with: tensorflow
type: Question
upvote count: 4
downvote count: 0
has title: Custom Keras Loss Function with Internal Prediction
tagged with: keras
score: 4
favorite count: 0

http://stackoverflow.com/comment/88903139
score: 0
type: Comment
has text: Thank you! This works perfectly and helps me understand how to use basemap.
type: AnswerComment
comment on: http://stackoverflow.com/a/50952419

http://stackoverflow.com/a/50929337
score: 1
accepted answer of: http://stackoverflow.com/q/50929110
upvote count: 1
has comment: http://stackoverflow.com/comment/88858021
answers question: http://stackoverflow.com/q/50929110
downvote count: 0
has comment: http://stackoverflow.com/comment/88857944
has body: You've connected your signal handler to all post-save signals. So when you call instance.profile.save(), it's called again on the profile itself, which it then tries to assign as the user attribute in another newly-created Profile. You should restrict it to only be called on post-save for User: post_save.connect(updateUserProfile, sender=User, ...) (Not sure why you've specified the dispatch_uid; you normally don't need that.)
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88858338
type: Answer
has comment: http://stackoverflow.com/comment/88858193

http://stackoverflow.com/q/50868156
type: UnansweredQuestion
has title: Storing a hard copy of data in a binary search tree format
upvote count: 1
tagged with: python
has body: I got to thinking that if we store data in a text file, it is stored in a linear fashion. While you can store things in sorted order, there’s always the chance that the thing you’re looking for is last in the file. In my algorithms course, there was a lot of talk about efficient ways to organize data within a Java/python/C program. You can create a binary search tree object, and all is well. But nothing was mentioned about storing a hard copy of said data in an efficient manner. My question is this: Is there a way to store a hard copy of some data in a binary search tree format? So that when you go to read from the file in Java, for example, Java can quickly “jump” left or right, and process the data in an efficient manner?
downvote count: 1
has comment: http://stackoverflow.com/comment/88739027
has comment: http://stackoverflow.com/comment/88738401
has comment: http://stackoverflow.com/comment/88739860
has answer: http://stackoverflow.com/a/50869325
tagged with: java
tagged with: http://stackoverflow.com/tag/c
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/88738366
favorite count: 0
has comment: http://stackoverflow.com/comment/88738360
score: 0
tagged with: text-files
tagged with: binary-search-tree

http://stackoverflow.com/q/50966453
accepted answer: http://stackoverflow.com/a/51020842
favorite count: 0
tagged with: python-3.x
has body: I have spent few recent days to learn how to structure data science project to keep it simple, reusable and pythonic. Sticking to this guideline I have created my_project. You can see it's structure below. ├── README.md ├── data │ ├── processed &lt;-- data files │ └── raw ├── notebooks | └── notebook_1 ├── setup.py | ├── settings.py &lt;-- settings file └── src ├── __init__.py │ └── data └── get_data.py &lt;-- script I defined a function that loads data from .data/processed. I want to use this function in other scripts and also in jupyter notebooks located in .notebooks. def data_sample(code=None): df = pd.read_parquet('../../data/processed/my_data') if not code: code = random.choice(df.code.unique()) df = df[df.code == code].sort_values('Date') return df Obviously this function won't work anywhere unless I run it directly in the script where it is defined. My idea was to create settings.py where I'd declare: from os.path import join, dirname DATA_DIR = join(dirname(__file__), 'data', 'processed') So now I can write: from my_project import settings import os def data_sample(code=None): file_path = os.path.join(settings.DATA_DIR, 'my_data') df = pd.read_parquet(file_path) if not code: code = random.choice(df.code.unique()) df = df[df.code == code].sort_values('Date') return df Questions: Is this common practice to refer to files in this way? settings.DATA_DIR looks kinda ugly. Is this at all how settings.py should be used? And should it be placed in this directory? I have seen it in different spot in this repo under .samr/settings.py I understand that there might not be 'one right answer', I just try to find logical, elegant way of handling these things.
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/89391158
tagged with: setuptools
tagged with: directory-structure
has title: Elegant way to refer to files in data science project
downvote count: 1
has answer: http://stackoverflow.com/a/51020842
has answer: http://stackoverflow.com/a/62088100
upvote count: 12
possible better answer: http://stackoverflow.com/a/51008842
has answer: http://stackoverflow.com/a/51007447
score: 11
has answer: http://stackoverflow.com/a/51008842
has comment: http://stackoverflow.com/comment/89202262
answer count: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89240005

http://stackoverflow.com/comment/88753185
score: 0
type: QuestionComment
type: Comment
has text: Well, I am not sure exactly what happens there, but I think there are some compatibility issues between certain conda packages and their pip counterparts. If you are using conda, it is always recommended to get pip packages only when unavoidable, but this is a very tricky situation you have here.
comment on: http://stackoverflow.com/q/50875378

http://stackoverflow.com/comment/89003080
type: QuestionComment
has text: My original idea was to add a numpy array index and use np.roll, but that was found to be very slow rather than using deque. Open to other ideas.
type: Comment
comment on: http://stackoverflow.com/q/51004753
score: 0

http://stackoverflow.com/a/50980110
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50979965
accepted answer of: http://stackoverflow.com/q/50979965
type: Answer
has body: There is a problem in the else block under main() because it calls main() again and gets stuck in a loop. Take out the main() part there. Another problem: Comeback.get_random_comeback() is never called. And another problem is that you never set comeback_text. With this block it achieves your goal: mr_t = Comeback(mr_t_comebacks).get_random_comeback() chuck_norris = Comeback(chuck_norris_comebacks).get_random_comeback() answer = who.get().lower() if "mr t" in answer: print(mr_t) comeback_text.set(mr_t) elif "chuck norris" in answer: print(chuck_norris) comeback_text.set(chuck_norris) elif "give up" in answer: print("I win") exit() else: print("Put something relevant in or Chuck Norris will team up with Mr. T and they will come for you")

http://stackoverflow.com/comment/88898090
type: QuestionComment
has text: String in C++ use double quotes, have you tried changing your simple quotes to those?
score: 2
comment on: http://stackoverflow.com/q/50950220
type: Comment

unix
tags question: http://stackoverflow.com/q/51002511
tags question: http://stackoverflow.com/q/50870719
tags question: http://stackoverflow.com/q/51007558
tags question: http://stackoverflow.com/q/50893067
tags question: http://stackoverflow.com/q/50931375
tags question: http://stackoverflow.com/q/50887182
type: Tag
tags question: http://stackoverflow.com/q/50867806
tag name: unix

http://stackoverflow.com/comment/88820304
score: 0
comment on: http://stackoverflow.com/q/50901800
type: QuestionComment
type: Comment
has text: The error in your code is coming from the fact that [servers are no longer created with a default channel](https://stackoverflow.com/a/48078278/6779307). So `server.default_channel` is set to `None` for these new servers.

http://stackoverflow.com/q/50970188
has comment: http://stackoverflow.com/comment/88936620
has comment: http://stackoverflow.com/comment/88941811
has title: Did you install mysqlclient?
type: Question
upvote count: 9
has answer: http://stackoverflow.com/a/60540604
answer count: 6
has answer: http://stackoverflow.com/a/70331548
has comment: http://stackoverflow.com/comment/88936764
tagged with: mysql-python
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/88938854
has answer: http://stackoverflow.com/a/54200666
has answer: http://stackoverflow.com/a/72848208
score: 9
has answer: http://stackoverflow.com/a/64215267
type: UnansweredQuestion
tagged with: django
has answer: http://stackoverflow.com/a/63902312
tagged with: python
has body: I have read every single post and googled for the last 4 hours to try to find a solution to this error. I am not running virtual environment, this server is just for django. Server: Ubuntu 16.04 python: 3.5.2 I am getting this error django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? trying to install mysqlclient sudo -H pip3 install mysqlclient Requirement already satisfied: mysqlclient in /usr/local/lib/python3.5/dist-packages (1.3.12) using ubuntu sudo apt-get install -y python3-mysqldb Reading package lists... Done Building dependency tree Reading state information... Done python3-mysqldb is already the newest version (1.3.7-1build2). 0 upgraded, 0 newly installed, 0 to remove and 3 not upgraded. Any help is greatly appreciated
has comment: http://stackoverflow.com/comment/88936815

http://stackoverflow.com/comment/88839503
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50892325
has text: @TommyLees whose answer did you end up using?
score: 0

http://stackoverflow.com/comment/88931154
type: AnswerComment
has text: `ForeignKey` relation can be used in both direction. Maybe the filed in Offer is `item_set` and not `item`. Anyway, good that it worked!
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50964892

http://stackoverflow.com/q/50857102
type: AnsweredQuestion
tagged with: pygobject
has body: Important note: I'm using PyGObject to get access to the GTK widgets, not PyGTK. That's what makes this question different from similar ones: PyGTK: How do I make an image automatically scale to fit it's parent widget? Scale an image in GTK I want to make a very simple app that displays a label, an image and a button, all stacked on top of each other. The app should be running in fullscreen mode. When I attempted it, I've run into a problem. My image is of very high resolution, so when I simply create it from file and add it, I can barely see 20% of it. What I want is for this image to be scaled by width according to the size of the window (which is equal to the screen size as the app runs in fullscreen). I've tried using Pixbufs, but calling scale_simple on them didn't seem to change much. Here's my current code: import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk, GdkPixbuf class Window(Gtk.Window): def __init__(self): super().__init__(title='My app') layout = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) dimensions = layout.get_allocation() pixbuf = GdkPixbuf.Pixbuf.new_from_file('path/to/image') pixbuf.scale_simple(dimensions.width, dimensions.height, GdkPixbuf.InterpType.BILINEAR) image = Gtk.Image.new_from_pixbuf(pixbuf) dismiss_btn = Gtk.Button(label='Button') dismiss_btn.connect('clicked', Gtk.main_quit) layout.add(image) layout.add(dismiss_btn) self.add(layout) win = Window() win.connect("destroy", Gtk.main_quit) win.show_all() Gtk.main()
linked to: http://stackoverflow.com/q/1269320
type: Question
linked to: http://stackoverflow.com/q/5067310
tagged with: image-scaling
score: 4
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/50858681
tagged with: python
upvote count: 4
tagged with: gtk
has title: Python GTK resizing large image to fit inside a window
has answer: http://stackoverflow.com/a/50858681

http://stackoverflow.com/a/51008654
has comment: http://stackoverflow.com/comment/89011327
has body: I was able to solve this. Took me a while but understood what is the arrangement of widgets within the layouts. I assumed removing the layout will cascade delete the widgets itself. I used the below function to remove the layout and its widgets corresponding to it. def SearchTab(self): self.layout = QVBoxLayout() button_layout = QHBoxLayout() radio_button_1 = QRadioButton("Search") radio_button_2 = QRadioButton("Update") button_layout.addWidget(radio_button_1) button_layout.addWidget(radio_button_2) self.layout.addItem(button_layout) #createDB() radio_button_1.toggled.connect(lambda :self.SelectButtonCheck(radio_button_1,self.layout)) radio_button_1.toggled.connect(lambda :self.UpdateButtonCheck(radio_button_2,self.layout)) #layout.addRow("Address",QLineEdit()) self.setTabText(0,"Search") update_layout = QHBoxLayout() #update_layout.set #update_btn = QDialogButtonBox(QDialogButtonBox) #update_btn.setAlignment(Qt.AlignBottom) update_layout.setAlignment(QtCore.Qt.AlignTop) update_btn = QPushButton('Update') reset_btn = QPushButton('Reset') #self.layout.addRow(update_layout) update_layout.addWidget(update_btn) update_layout.addWidget(reset_btn) update_btn.clicked.connect(self.createDB) self.tab1.setLayout(self.layout) def SelectButtonCheck(self,b,stacklayout): if b.text() == "Search": if b.isChecked(): print(b.text()+ "is selected") self.pg_details = pgd.PGDetails() layout = self.pg_details.returnLayout() self.layout.addLayout(layout) def removeLayout(self,layout): for i in range(layout.count()): temp_layout = layout.itemAt(i) if temp_layout is not None: widget = temp_layout.widget() if widget is not None: widget.deleteLater() else: return if temp_layout.layout() is not None: self.removeLayout(temp_layout.layout()) def removeFormLayout(self,layout): if layout is not None: for i in range(layout.count()): temp_layout = layout.itemAt(i) if isinstance(temp_layout.layout(),type(QFormLayout())): self.removeLayout(temp_layout.layout()) else: next else: return def UpdateButton…
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/51000507
has comment: http://stackoverflow.com/comment/89010323
accepted answer of: http://stackoverflow.com/q/51000507
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/50860670
type: AnsweredQuestion
tagged with: io
tagged with: python
linked to: http://stackoverflow.com/q/50822856
type: Question
has comment: http://stackoverflow.com/comment/88729164
score: 0
answer count: 1
has body: I've been working with some huge files that I have to convert to UTF-8, as the files ar enormous traditional tools like iconv won't work. So I decided to write my own tool in Go, however I noticed that this encoding conversion is quite slow in Go. here is my code: package main import ( "fmt" "io" "log" "os" "golang.org/x/text/encoding/charmap" ) func main() { if len(os.Args) != 3 { fmt.Fprintf(os.Stderr, "usage:\n\t%s [input] [output]\n", os.Args[0]) os.Exit(1) } f, err := os.Open(os.Args[1]) if err != nil { log.Fatal(err) } out, err := os.Create(os.Args[2]) if err != nil { log.Fatal(err) } r := charmap.ISO8859_1.NewDecoder().Reader(f) buf := make([]byte, 1048576) io.CopyBuffer(out, r, buf) out.Close() f.Close() } Similar code in Python is much more performant: import codecs BLOCKSIZE = 1048576 # or some other, desired size in bytes with codecs.open("FRWAC-01.xml", "r", "latin_1") as sourceFile: with codecs.open("FRWAC-01-utf8.xml", "w", "utf-8") as targetFile: while True: contents = sourceFile.read(BLOCKSIZE) if not contents: break targetFile.write(contents) I was sure my Go code would be much quicker because in general I/O in Go is fast, but it turns out is much slower than the Python code. Is there a way to improve the Go program?
has answer: http://stackoverflow.com/a/50863535
tagged with: character-encoding
tagged with: encoding
has title: How to improve file encoding conversion in Go
has comment: http://stackoverflow.com/comment/88725069
accepted answer: http://stackoverflow.com/a/50863535
tagged with: go
has comment: http://stackoverflow.com/comment/88724466

http://stackoverflow.com/q/50875983
tagged with: python
has body: I have a list of numpy arrays, and each one of them has a dtype=object in the first dimension (3 objects), where there are arrays of different shapes e.g. (200, 10), (100, 10), (50, 10). Although this works well, when it happens that the three objects get the same first dimension (e.g. (200, 10), (200,10), (200,10)), the array automatically goes from dtype=object to dtype=float). So, i end up with one of these arrays, being (3,200,10), instead of (3,) object type. That ends up with an error when i try to make the list a numpy array, since one of the arrays has different shape. Is there any solution to that?
has comment: http://stackoverflow.com/comment/88760995
has comment: http://stackoverflow.com/comment/88753905
score: 0
has title: Change shape and dtype of numpy array
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88753578
tagged with: numpy
has comment: http://stackoverflow.com/comment/88754074
tagged with: arrays
has comment: http://stackoverflow.com/comment/88753950
answer count: 0
type: Question
tagged with: shapes

http://stackoverflow.com/a/50924117
score: 0
has body: You can do something like this: import cx_Oracle connection = cx_Oracle.connect("username", "password", "ip of your server"/"database name") cursor = connection.cursor() cursor.execute("select * from table_name") for row in cursor: print(row) connection.close()
answers question: http://stackoverflow.com/q/50923848
type: Answer

http://stackoverflow.com/a/51007958
has body: Update: sudo rm /usr/local/bin/pip It could be one of the following cases or just a broken symlink. My guess: /usr/local/bin/pip is probably using Python 3 which is not installed on your system (assuming Ubuntu or Debian). This can be verified by checking the first line of the file: head /usr/local/bin/pip If it shows something like #!/usr/bin/python3, and Python 3 is not installed, it could cause the error "No such file or directory". I asked you to run "which -a pip" is also another way to check this. Since apt only installs pip in /usr/bin but not /usr/local/bin, it probably that you never called the pip command installed through apt. However, I can not tell if it's the case until you tried these commands. After that thing becomes really simple: just delete /usr/local/bin/pip will fix the problem.
has comment: http://stackoverflow.com/comment/89009038
answers question: http://stackoverflow.com/q/51007854
type: Answer
has comment: http://stackoverflow.com/comment/89009023
has comment: http://stackoverflow.com/comment/89054973
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/89008995
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51007854

http://stackoverflow.com/q/50878867
duplicate of: http://stackoverflow.com/q/3931541
has answer: http://stackoverflow.com/a/50878920
type: Question
tagged with: if-statement
has body: I'm trying to find out whether a specific column exists in my DataFrame columns or not, but I have some problems. What I do: Using boolean operation "not in" (I've tried any(), all(), "in") to find the specific column header and it seems it's not working properly! let's say my DataFrame column headers are: df.columns = ['El-array', 'a', 'b', 'm', 'n', 'Rho', 'dev', 'ip', 'sp', 'vp', 'i', 'M1', 'M2', 'M3', 'M4', 'M5', 'M6', 'M7', 'M8', 'M9', 'M10', 'M11', 'M12', 'M13', 'M14', 'M15', 'M16', 'M17', 'M18', 'M19', 'M20', 'TM1', 'TM2', 'resist', 'DC_slope'] and I'm trying to see if all of 'M1', 'M2', ... 'M20' and 'TM1' are there. If one or more is missing code will not work. So I say: if any(['M1','M2','M3','M4','M5','M6','M7','M8','M9','M10','M11', 'M12','M13','M14','M15','M16','M17','M18','M19','M20', 'TM1']) not in df.columns: print('Incomplete dataset') Now, let's say df has all the asked columns headers, the if statement still shows the "Incomplete dataset' message!! I have tried "all() not in" too but same result!! I also have tried: if 'M1' and 'M2' and ... and 'M20' and 'TM1' in df.columns: "Do this" elif: print('Incomplete dataset') or if 'M1' or 'M2' or ... or 'M20' and 'TM1' not in df.columns: print('Incomplete dataset') elif: "Do this" Still prints incomplete dataset!! Now for a truly incomplete dataset I get the same results too!!
tagged with: boolean
linked to: http://stackoverflow.com/q/10149747
score: 0
answer count: 1
tagged with: boolean-logic
has comment: http://stackoverflow.com/comment/128723166
has comment: http://stackoverflow.com/comment/88759896
linked to: http://stackoverflow.com/q/3931541
tagged with: python
has title: Boolean operation in pandas DataFrame columns
accepted answer: http://stackoverflow.com/a/50878920
type: AnsweredQuestion

http://stackoverflow.com/q/51006315
has answer: http://stackoverflow.com/a/51006545
has body: The exact button I am trying to click is this: https://www.bungol.ca/map/location/toronto/? close the property slider on the left click tool -> open list click on any of the listing and you get to something like this: Image for close button Here's what I tried to do: time.sleep(5) #wait for page to fully load driver.find_element_by_xpath("""/html/body/div[17]/div/div/div/button""").click() and time.sleep(5) #wait for page to load driver.find_element_by_css_selector("""html body#body.modal-open div#listingInfoModal.modal.fade.show div.modal-dialog.modal-xl div.modal-content div.modal-body button.close""").click()
downvote count: 0
has title: Python Selenium: I can't click this exit button
type: AnsweredQuestion
score: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/51006545
tagged with: python-3.x
type: Question
tagged with: buttonclick
tagged with: selenium
upvote count: 1
tagged with: python
answer count: 1
tagged with: selenium-webdriver

http://stackoverflow.com/comment/89062239
type: AnswerComment
type: Comment
has text: [aravind@aravind05 ~]$ nmcli general status STATE CONNECTIVITY WIFI-HW WIFI WWAN-HW WWAN connected full enabled enabled enabled disabled
comment on: http://stackoverflow.com/a/51007255
score: 0

http://stackoverflow.com/a/67709325
answers question: http://stackoverflow.com/q/50946003
type: Answer
has body: try this in Anaconda prompt: conda install -c conda-forge pyLDAvis then type y in the following section: The following packages will be UPDATED: Proceed ([y]/n)? y
score: 0
has comment: http://stackoverflow.com/comment/119680655

flask
tags question: http://stackoverflow.com/q/50875213
tags question: http://stackoverflow.com/q/50974066
tags question: http://stackoverflow.com/q/50916187
tags question: http://stackoverflow.com/q/50924750
tags question: http://stackoverflow.com/q/51003611
tags question: http://stackoverflow.com/q/50999447
tags question: http://stackoverflow.com/q/50978218
tags question: http://stackoverflow.com/q/50924141
tags question: http://stackoverflow.com/q/50967548
tags question: http://stackoverflow.com/q/50858658
tags question: http://stackoverflow.com/q/50979354
tags question: http://stackoverflow.com/q/50964737
tags question: http://stackoverflow.com/q/50933174
tags question: http://stackoverflow.com/q/50910967
tags question: http://stackoverflow.com/q/50898432
tags question: http://stackoverflow.com/q/50896928
tags question: http://stackoverflow.com/q/50891560
tags question: http://stackoverflow.com/q/50991551
tags question: http://stackoverflow.com/q/50863534
tags question: http://stackoverflow.com/q/50915593
tags question: http://stackoverflow.com/q/50891073
tags question: http://stackoverflow.com/q/50895751
tags question: http://stackoverflow.com/q/50868137
tags question: http://stackoverflow.com/q/50889452
tags question: http://stackoverflow.com/q/50984899
tags question: http://stackoverflow.com/q/50999833
tags question: http://stackoverflow.com/q/50916480
tags question: http://stackoverflow.com/q/50963130
tags question: http://stackoverflow.com/q/50892489
tags question: http://stackoverflow.com/q/51001877
tags question: http://stackoverflow.com/q/50872479
tags question: http://stackoverflow.com/q/50918939
tags question: http://stackoverflow.com/q/50905636
tags question: http://stackoverflow.com/q/50932527
tags question: http://stackoverflow.com/q/50918276
tags question: http://stackoverflow.com/q/50884127
tags question: http://stackoverflow.com/q/50878513
tags question: http://stackoverflow.com/q/50877819
tags question: http://stackoverflow.com/q/50902696
tags question: http://stackoverflow.com/q/50935514
tags question: http://stackoverflow.com/q/50989648
tags question: http://stackoverflow.com/q/50957084
tags question: http://stackoverflow.com/q/50920528
tags question: http://stackoverflow.com/q/50864230
tags question: http://stackoverflow.com/q/50857326
tags question: http://stackoverflow.com/q/50904866
tags question: http://stackoverflow.com/q/50974904
tags question: http://stackoverflow.com/q/50895447
tags question: http://stackoverflow.com/q/50944047
tags question: http://stackoverflow.com/q/50866804
tags question: http://stackoverflow.com/q/50918819
type: Tag
tags question: http://stackoverflow.com/q/50950013
tags question: http://stackoverflow.com/q/50875335
tags question: http://stackoverflow.com/q/50907956
tags question: http://stackoverflow.com/q/50948777
tags question: http://stackoverflow.com/q/50933079
tags question: http://stackoverflow.com/q/50876332
tags question: http://stackoverflow.com/q/50973182
tags question: http://stackoverflow.com/q/50863556
tags question: http://stackoverflow.com/q/50892153
tags question: http://stackoverflow.com/q/50991261
tags question: http://stackoverflow.com/q/50937058
tags question: http://stackoverflow.com/q/50956377
tags question: http://stackoverflow.com/q/51001680
tags question: http://stackoverflow.com/q/50956922
tags question: http://stackoverflow.com/q/50952938
tags question: http://stackoverflow.com/q/51006521
tags question: http://stackoverflow.com/q/50997532
tags question: http://stackoverflow.com/q/50878862
tags question: http://stackoverflow.com/q/50899601
tags question: http://stackoverflow.com/q/50963616
tags question: http://stackoverflow.com/q/50892823
tags question: http://stackoverflow.com/q/50883716
tags question: http://stackoverflow.com/q/50990612
tags question: http://stackoverflow.com/q/50981084
tags question: http://stackoverflow.com/q/50988099
tags question: http://stackoverflow.com/q/50944992
tags question: http://stackoverflow.com/q/51005915
tags question: http://stackoverflow.com/q/50961659

http://stackoverflow.com/q/50886636
possible better answer: http://stackoverflow.com/a/50887361
score: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50887154
tagged with: powershell
type: Question
tagged with: shell
has title: Using powershell as Admin in python
has body: So I have a project I'm working on, and one thing I need to do is to run in the background the "netstat -nb" command at the PowerShell as admin and recive the results to the python program. I've been searching the web for a solution but never found one efficient out there. I'd be glad for some help. "netstat -nb"
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50887361
tagged with: subprocess
accepted answer: http://stackoverflow.com/a/50887154
answer count: 2
tagged with: python

feature-detection
type: Tag
tag name: feature-detection
tags question: http://stackoverflow.com/q/50937304

http://stackoverflow.com/comment/88736217
type: Comment
type: QuestionComment
has text: Can you elaborate Mike? If I comment out just the scrollbar section, the code works just fine with the same imports.
comment on: http://stackoverflow.com/q/50866373
score: 0

http://stackoverflow.com/q/50997339
has answer: http://stackoverflow.com/a/50997626
has comment: http://stackoverflow.com/comment/88989004
tagged with: pandas
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/88988985
has comment: http://stackoverflow.com/comment/88989246
score: 6
accepted answer: http://stackoverflow.com/a/50997626
upvote count: 7
downvote count: 1
has comment: http://stackoverflow.com/comment/88988982
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88989358
has body: My dataframe has daily stock data in it: Date AAPL NFLX INTC 0 2008-01-02 27.834286 3.764286 25.350000 1 2008-01-03 27.847143 3.724286 24.670000 2 2008-01-04 25.721428 3.515714 22.670000 3 2008-01-07 25.377142 3.554286 22.879999 4 2008-01-08 24.464285 3.328571 22.260000 I'd like to calculate monthly returns using the last day of each month in my df above. I'm guessing (after googling) that resample is the best way to select the last trading day of the month. But this doesn't seem to work: df.set_index('Date') m1= df.resample('M') print(m1) get this error: TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'Index' So I think that means the set_index isn't working? I've also tried: df= df.reset_index().set_index('Date') m1= df.resample('M') print(m1) But I get the same error message as above. Thanks much for your help.
has comment: http://stackoverflow.com/comment/88989258
type: Question
has comment: http://stackoverflow.com/comment/88989172
has comment: http://stackoverflow.com/comment/88988910
has comment: http://stackoverflow.com/comment/88989226
answer count: 1
has title: Convert daily data in pandas dataframe to monthly data
has comment: http://stackoverflow.com/comment/88988889
has comment: http://stackoverflow.com/comment/88989297

http://stackoverflow.com/comment/88998939
type: AnswerComment
comment on: http://stackoverflow.com/a/51002141
has text: I read the linked article and changed the path to an executable so my code looks like this: `d = webdriver.Chrome(executable_path=r'/anaconda2/lib/python2.7/site-packages/selenium/webdriver/chrome/chromedriver.exe')`Yet I still get the PATH error. Is this something because the chrome driver isn't in the correct folder or something?
type: Comment
score: 0

http://stackoverflow.com/a/51006407
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51006382
upvote count: 2
has comment: http://stackoverflow.com/comment/89006607
score: 2
has body: As reported in the documentation, it should be more likely like: import google.auth.transport.requests import requests request = google.auth.transport.requests.Request() credentials.refresh(request) But for your purpose I'll suggest: from google.auth.transport.requests import Request then change the following from: idinfo = id_token.verify_oauth2_token(token, requests.Request(), app.config["GOOGLE_LOGIN_CLIENT_ID"]) to: idinfo = id_token.verify_oauth2_token(token, Request(), app.config["GOOGLE_LOGIN_CLIENT_ID"]) It was an error because inside the path google.auth.transport.requests there is no function or class which is named requests. My suggestion is based on the line idinfo = id_token.verify_oauth2_token(token, requests.Request(), app.config["GOOGLE_LOGIN_CLIENT_ID"]) which show us that you use a class named Requests() which is present into google.auth.transport.requests as you can see in the documentation.

http://stackoverflow.com/q/50932144
has comment: http://stackoverflow.com/comment/88863025
has comment: http://stackoverflow.com/comment/88863319
tagged with: python
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/775296
has comment: http://stackoverflow.com/comment/88863238
has title: How to Import Big JSON file to MYSQL
has comment: http://stackoverflow.com/comment/88870409
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/88863110
tagged with: mysql
type: Question
linked to: http://stackoverflow.com/q/775296
has body: I have to Read and import data into MYSQL from given JSON file (50 MB size). I have tried using Python and failed (getting error). I can't figure out how to import JSON file to MYSQL in most efficient way. PLEASE help me out. What I have done so far is : import os import json import MySQLdb # read JSON file which is in the next parent folder file = 'vehicle.json' json_data = open(file).read() json_obj = json.loads(json_data) #print(json_obj) # do validation and checks before insert def validate_string(val): if val is not None: if type(val) is int: # for x in val: # print(x) return str(val).encode('utf-8') else: return val # connect to MySQL con = MySQLdb.connect(host="127.0.0.1", user="root", passwd="PASSWORD", db="vehicle", port=3306) cursor = con.cursor() cursor.execute("DROP TABLE IF EXISTS vehicle") sql1 = """ CREATE TABLE vehicle ( CarYear int(4) , make varchar(15), model varchar(30), cylinders varchar(2), VClass varchar(30), drive varchar(30), trany varchar(30), displ varchar(20), eng_dscr varchar(20), trans_dscr varchar(30), mpgData varchar(5), evMotor varchar(10), youSaveSpend varchar(20), fuleType varchar(20), fuleType1 varchar(30), barrelsA08 varchar(2), charge120 varchar(2), charge240 varchar(2), city08 varchar(4), city08U varchar(2), cityA08 varchar(2), cityA08U varchar(2), cityCD varchar(2), cityE varchar(2), cityUF varchar(2), co2 varchar(2), coA2 varchar(2), co2TailpipeAGpm varchar(2), co2TailpipeGpm varchar(20), comb08 varchar(3), comb08U varchar(2), combA08 varchar(2), combA08U varchar(2), combE varchar(2), combinedCD varchar(2), combinedUF varchar(2), engld varchar(8), feScore varchar(3), fuelCost08 varchar(5), fuelCostA08 varchar(2), ghgScore varchar(2), ghgScoreA varchar(2), highway08 varchar(4), highway08U varchar(2), highwayA08 varchar(2), highwayA08U varchar(2), highwayCD varchar(2), highwayE varchar(2), highwayUF varchar(2), hlv varchar(2), hpv varchar(2), id varchar(8), lv2 varchar(2), lv4 varchar(2), phevBlended varchar(10), pv2 varchar(5),…
score: 0
has comment: http://stackoverflow.com/comment/88863677
has comment: http://stackoverflow.com/comment/88863242

http://stackoverflow.com/comment/89109758
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50887311
type: AnswerComment
has text: @BPL Oh, Okay. How can I tag you when I right a new question?

http://stackoverflow.com/q/50974075
favorite count: 0
has answer: http://stackoverflow.com/a/50974389
upvote count: 2
type: UnansweredQuestion
score: -4
tagged with: python
has body: def factorial(number): product = 1 for i in range(number): product = product * (i + 1) return product user_input = input("enter a non negative number:") factorial_of_the_number = factorial(user_input) print(factorial_of_user_input) I have just started programming. Please state the simplest explanation. My question being, since the user input is assigned to the variable user_input and not the variable number. how does factorial function recognizes the user input? Also what does it mean by return product function??
answer count: 4
downvote count: 6
has answer: http://stackoverflow.com/a/50974150
has answer: http://stackoverflow.com/a/50974276
has comment: http://stackoverflow.com/comment/88944646
tagged with: loops
has answer: http://stackoverflow.com/a/50974169
type: Question
has comment: http://stackoverflow.com/comment/88944464
tagged with: variables
has title: How can the following program from Khan Academy even work?

http://stackoverflow.com/q/50901465
has comment: http://stackoverflow.com/comment/88808871
possible better answer: http://stackoverflow.com/a/50901487
has answer: http://stackoverflow.com/a/50901631
has answer: http://stackoverflow.com/a/50901487
answer count: 3
has body: I've been following the Django documentation "Write your app tutorial" and I keep running into the above error. It seems to be coming from this line selected_choice = question.choice_set.get(pk=request.POST['choice']) This is my Questions and Choices object: class Questions(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date Published') def __str__(self): return self.question_text class Choices(models.Model): questions = models.ForeignKey(Questions, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text The code is exactly as it is on the official documentation, so I can't tell exactly where the error is coming from
favorite count: 0
tagged with: django
tagged with: python
has title: 'Questions' object has no attribute 'choice_set'
accepted answer: http://stackoverflow.com/a/50901631
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/88802841
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/60794541
downvote count: 0

http://stackoverflow.com/q/51000788
favorite count: 0
has comment: http://stackoverflow.com/comment/88995773
has comment: http://stackoverflow.com/comment/88995612
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88995663
has comment: http://stackoverflow.com/comment/88995890
has comment: http://stackoverflow.com/comment/88995751
has comment: http://stackoverflow.com/comment/88995836
tagged with: python
has comment: http://stackoverflow.com/comment/88995734
has comment: http://stackoverflow.com/comment/88995639
has comment: http://stackoverflow.com/comment/88995778
has comment: http://stackoverflow.com/comment/88995789
score: 1
has answer: http://stackoverflow.com/a/51000977
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88995873
has comment: http://stackoverflow.com/comment/88995767
tagged with: python-2.7
has title: Find a match in line of file, then move on to next file
answer count: 1
downvote count: 0
has body: I'm new in python and I'm try to write a script to loop through all the .txt files in my /home directory and iterate lines in each .txt file and see if I can find a match, if it does, it should move on to next file. If it doesn't find the match in entire file, then report it. Code that I have: strname = "ntpq -p" for file in glob.glob("/home/xxx/*.txt"): with open(file, 'rb') as f: iFoundTheLine = 0 for line in f: line = line.rstrip() id = line.split(b"|")[0] if strname in line: iFoundTheLine = 1 print ("%s is ok" % id) break if iFoundTheLine == 0: print ("Problem with NTP%s" % id) The result that I got: srv29393 is ok Problem with NTP srv29494 is ok Problem with NTP srv29399 is ok srv29493 is ok The expect result I'm looking for: srv29393 is ok Problem with NTP srv1234 srv29494 is ok Problem with NTP srv2345 srv29399 is ok srv29493 is ok sample lines: srv29393|06/23/18|05:32:02|ps -eo user,pid,ppid,start,etimes,cmd | egrep -v [\w&lt;|>nobody 22972 21597 03:06:12 8767 (dnsserver) srv29393|06/23/18|05:32:02|1529746322|ps -eo user,pid,ppid,start,etimes,cmd | egrep -v [\w&lt;|>nobody 22973 21597 03:06:12 8767 (dnsserver) srv29393|06/23/18|05:32:02|ps -eo user,pid,ppid,start,etimes,cmd | egrep -v [\w&lt;|>nobody 22974 21597 03:06:12 8767 (dnsserver) srv29393|06/23/18|05:32:02|1529746322|/usr/sbin/ntpq -p&lt;|>*1.1.1.11 11.11.11.11 3 u 1055 1024 377 719.042 -0.625 0.016 srv29393|06/23/18|05:32:02|1529746322|/usr/sbin/ntpq -p&lt;|>+2.2.2.11 12.12.12.11 3 u 1049 1024 377 824.784 0.707 0.121 It is missed the "id" for those having issue for the NTP. Could someone please help/advise?
has comment: http://stackoverflow.com/comment/88995412

http://stackoverflow.com/q/50910638
answer count: 1
has comment: http://stackoverflow.com/comment/88826722
favorite count: 0
tagged with: python
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50919222
upvote count: 3
has body: I need to pass data in a python back-end to a front end through an api call, using a json format. In the python back end, the data is in a dictionary structure, which I can easily and directly convert to a json. But should I? My front-end developer believes the answer is no, for reasons related to best practice. But I challenge that: Is the best to structure a json as it is in python, or should it rather be converted to some other form, such as several arrays (as would be necessary in my example case below)? Or, differently put: What should be the governing principles related to collections/dicts/maps/arrays for interfacing information through jsons? I've done some googling for an answer, but I've not come across much that addresses this directly. Links would be appreciated. (Note about the example below: of course if the data is written to a database, it would probably make most sense for the front-end to access the database directly, but let's assume this is not the case) Example: In the back end there is a collection of objects called pets: each item in the collection has a unique pet_id, some non-optional properties, e.g. name and date_of_birth, some optional properties registration_certificate_nr, adopted_from_kennel, some lists like siblings and children and some objects like medication. Assuming that the front end needs all of this info at some point, it could be { "pets": { "17-01-24-01": { "name": "Buster", "date_of_birth": "04/01/2017", "registration_certificate_nr": "AAD-1123-1432" }, "17-03-04-01": { "name": "Hooch", "date_of_birth": "05/02/2015", "adopted_from_kennel": "Pretoria Shire", "children": [ "17-05-01-01", "17-05-01-02", "17-05-01-03" ] }, "17-05-01-01": { "name": "Snappy", "date_of_birth": "17-05-01", "siblings": [ "17-05-01-02", "17-05-01-03" ] }, "17-05-01-02": { "name": "Gizmo", "date_of_birth": "17-05-01", "siblings": [ "17-05-01-01", "17-05-01-03" ] }, "17-05-01-03": { "name": "Toothless", "date_of_birth": "17-05-01", "siblings": [ "17-05…
has comment: http://stackoverflow.com/comment/88821471
has comment: http://stackoverflow.com/comment/88821714
downvote count: 1
type: Question
tagged with: http://stackoverflow.com/tag/json
accepted answer: http://stackoverflow.com/a/50919222
has title: Best practice for collections in jsons: array vs dict/map

http://stackoverflow.com/a/50956056
answers question: http://stackoverflow.com/q/50955501
score: 0
has body: Generally mixing OpenGL renders and OS renders (used for buttons or other controls) is not a good idea. One solution is draw first the controls (better in memory) and get a "screen shot" of it. Then do OpenGL rendering. Then pass the image to OpenGL and render it on top of the previous renders. The drawback is that you loose all control reaction, they become just images. The other way may work better. First render OpenGL. Then get that image (by for example glReadPixels). Then blit the image as a background. Then draw the controls.
has comment: http://stackoverflow.com/comment/88910020
type: Answer

http://stackoverflow.com/a/78687364
has body: It's work for me from discord import File @bot.command async def sender(ctx): image = "file_name.png" file = File(image) link=f"attachment://{image}" await ctx.send(link, file=file) 100% working
type: Answer
answers question: http://stackoverflow.com/q/50860397
score: 0

http://stackoverflow.com/q/50941195
tagged with: python
has comment: http://stackoverflow.com/comment/88888052
has body: I am trying to load images using opencv in wiki dataset in which the images are organized into 99 folders. I have this code. def load_images(self,dataframe): if dataframe is None: return None else: assert type(dataframe) == pd.core.frame.DataFrame, "argument to load image should be dataframe" assert "file_location" in dataframe.columns, "dataframe should contain file_location column" output_images = np.zeros((len(dataframe),self.config.image_shape[0],self.config.image_shape[1],self.config.image_shape[2])) for index,row in dataframe.iterrows(): img = cv2.imread(os.path.join(self.config.dataset_dir,row["file_location"][0])) if img is None: Log.WARNING("Unable to read images from "+os.path.join(self.config.dataset_dir,row["file_location"][0])) continue face_location = row["face_location"][0].astype(int) face_image = img[face_location[1]:face_location[3],face_location[0]:face_location[2]] face_image = cv2.cvtColor(face_image,cv2.COLOR_BGR2GRAY) face_image = cv2.resize(face_image,(self.config.image_shape[0],self.config.image_shape[1])) output_images[index] = face_image.reshape(self.config.image_shape) return output_images I wanted to remove errors like this when I run the code libpng warning: iCCP: profile 'icc': 'RGB ': RGB color space not permitted on grayscale PNG
answer count: 0
type: UnansweredQuestion
type: Question
tagged with: opencv
has comment: http://stackoverflow.com/comment/88919248
tagged with: libpng
tagged with: loadimage
has title: How do I run a mogrify script for all images in subfolders in python?
score: 0

http://stackoverflow.com/comment/88980092
comment on: http://stackoverflow.com/q/50992042
has text: definition_list = browser.find_elements_by_css_selector('ol.lst_defin>li span.cn')
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/50953757
has comment: http://stackoverflow.com/comment/88905651
type: Answer
accepted answer of: http://stackoverflow.com/q/50953637
downvote count: 0
score: 6
has comment: http://stackoverflow.com/comment/88905358
upvote count: 6
has comment: http://stackoverflow.com/comment/88905585
has comment: http://stackoverflow.com/comment/88905810
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88905430
has body: super() looks at the MRO of the current instance. It doesn't matter here that the current class inherits only from object. The MRO of ReportingPage puts Report between Page and object: &gt;&gt;&gt; ReportingPage.__mro__ (&lt;class '__main__.ReportingPage'&gt;, &lt;class '__main__.Page'&gt;, &lt;class '__main__.Report'&gt;, &lt;class 'object'&gt;) So when you call super() in Page.__init__(), the next class in the MRO is Report, and you end up calling the Report.__init__ method. You need to make your classes more cooperative; you could use keyword arguments and a catch-all **kwargs argument to do so: class Page(object): def __init__(self, pagenum, **kwargs): self.pagenum = pagenum super().__init__(**kwargs) class Report(object): def __init__(self, title, **kwargs): self.title = title super().__init__(**kwargs) class ReportingPage(Page, Report): def __init__(self, footer=None, **kwargs): self.footer = footer super().__init__(**kwargs) Each method passes along the remaining keyword arguments here, to the next __init__ in the MRO, and in the end you'll have an empty dictionary to pass to object.__init__(). If you add in a print(kwargs) wrapper to each __init__ method, you can see that kwargs becomes smaller as fewer values are passed on to the next call. &gt;&gt;&gt; def print_wrapper(name, f): ... def wrapper(*args, **kwargs): ... print(name, '-&gt;', kwargs) ... return f(*args, **kwargs) ... return wrapper ... &gt;&gt;&gt; for cls in ReportingPage.__mro__[:-1]: # all except object ... cls.__init__ = print_wrapper(cls.__name__, cls.__init__) ... &gt;&gt;&gt; ReportingPage(title='Watching Paint Dry II: The Second Coat', pagenum=42) ReportingPage -&gt; {'title': 'Watching Paint Dry II: The Second Coat', 'pagenum': 42} Page -&gt; {'title': 'Watching Paint Dry II: The Second Coat', 'pagenum': 42} Report -&gt; {'title': 'Watching Paint Dry II: The Second Coat'} &lt;__main__.ReportingPage object at 0x109e3c1d0&gt; Only title remains, which Report.__init__() consumes, so an em…
has comment: http://stackoverflow.com/comment/88905551
answers question: http://stackoverflow.com/q/50953637

http://stackoverflow.com/comment/88845594
type: AnswerComment
comment on: http://stackoverflow.com/a/50922946
type: Comment
has text: @coldspeed Sure, if Pandas is already in the toolkit, I suppose. :) Nevertheless, I added a stdlib answer for completeness' sake too.
score: 0

http://stackoverflow.com/a/50948419
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50948075
answers question: http://stackoverflow.com/q/50948075
type: Answer
score: 1
upvote count: 1
has body: You can create a wrapper object that tracks how much data has been written, and opens a new file if you reached a limit: class MaxSizeFileWriter(object): def __init__(self, filenamepattern, maxdata=2**20, # default 1Mb start=0, mode='w', *args, **kwargs): self._pattern = filenamepattern self._counter = start self._mode = mode self._args, self._kwargs = args, kwargs self._max = maxdata self._openfile = None self._written = 0 def _open(self): if self._openfile is not None: filename = self._pattern.format(self._counter) self._counter += 1 self._openfile = open(filename, mode=self._mode, *self._args, **self._kwargs) def _close(self): if self._openfile is not None: self._openfile.close() def __enter__(self): return self def __exit__(self, *args, **kwargs): if self._openfile is not None: self._openfile.close() def write(self, data): if self._written + len(data) &gt; self._max: # current file too full to fit data too, close it # This will trigger a new file to be opened. self._close() self._open() # noop if already open self._openfile.write(data) self._written += len(data) The above is a context manager, and can be used just like a regular file. Pass in a filename with a {} placeholder for the number to be inserted into: folder_name = "out{}.txt" with MaxSizeFileWriter(folder_name, maxdata=100 * 2**10) as f: for domain in millions_of_domains: response_json = send_whois_query(domain) f.write(response_json)

http://stackoverflow.com/comment/88769314
score: 0
type: Comment
type: QuestionComment
has text: Did you check the permissions of that directory?
comment on: http://stackoverflow.com/q/50883524

http://stackoverflow.com/comment/88801995
has text: You need someone who understands both the `dplyr`-variant of R and Python. Code appears to just be using regex to extract numbers with commas. Why the "?" is inside a character class is bit of a puzzle though. And why passing digit strings with commas to `as.numeric` should work in R is also a bit of a puzzle. I'm skeptical that this is solidly tested R code. My advice: Edit your question to capitalize all the "I"'s, since many of us fiund that to be sign of laziness and lack of respect for your readers, and remove the request to translate from sketchy R code.
score: 1
comment on: http://stackoverflow.com/q/50901045
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50956087
has comment: http://stackoverflow.com/comment/88909624
has comment: http://stackoverflow.com/comment/88909846
upvote count: 3
has body: You are looking for np.dstack Stack arrays in sequence depth wise (along third axis). np.dstack([arr1, arr2]) array([[[1, 5], [2, 6], [3, 7], [4, 8]]])
has comment: http://stackoverflow.com/comment/88909684
answers question: http://stackoverflow.com/q/50955960
has comment: http://stackoverflow.com/comment/88909630
has comment: http://stackoverflow.com/comment/88909857
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50955960
has comment: http://stackoverflow.com/comment/88909721
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88909728
type: Answer
score: 3

http://stackoverflow.com/comment/88942342
type: Comment
score: 0
has text: Is that how it works? Either way, Id need to switch modes on my calculator and cant have sin(radians(x)) show up because that is a bit awkward to the user.
type: QuestionComment
comment on: http://stackoverflow.com/q/50971878

http://stackoverflow.com/q/50986472
type: UnansweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/88968925
has title: sep = '|' not functioning properly in pandas dataframe
favorite count: 0
type: Question
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/50986618
has comment: http://stackoverflow.com/comment/88967912
tagged with: python-3.x
upvote count: 3
downvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/88967919
has body: I'm using python 3.6 and pandas version 0.20.3 . I have a file with text as - 17727425 - 1|TM000002|38|cow|country|crow 17727425 - 1|TM000002|64|international|NAME|international ltd 17727425 - 1|TM000002|66|^ference|country|^ference 17727425 - 1|TM000002|80|"|gulf "|DRWENAME|"|gulf " my code for making a dataframe is- df = pd.read_csv(filepath, sep="|", error_bad_lines=False, encoding="ISO-8859-1") Since I'm using sep = '|', it should separate the text by '|' but in the last line of the text, it is separating using " the output I'm getting is - 17727425 - 1 TM000002 38 cow country crow 0 17727425 - 1 TM000002 64 international NAME international ltd 1 17727425 - 1 TM000002 66 ^ference country ^ference 2 17727425 - 1 TM000002 80 |gulf DRWENAME |gulf I want to know that for the last line why sep = '|' not working correctly and what should be done to eradicate this problem.
tagged with: dataframe

http://stackoverflow.com/a/50874946
upvote count: 2
type: Answer
score: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50874343
answers question: http://stackoverflow.com/q/50874343
has body: The answer is 1: no exceptions, in Python 2 and in Python 3. exceptions = () try: a = 1 / 0 except exceptions as e: print ("the answer is 2") Traceback (most recent call last): File "&lt;pyshell#38&gt;", line 2, in &lt;module&gt; a = 1 / 0 ZeroDivisionError: integer division or modulo by zero If you want to the behaviour of answer 2 when the list of exceptions is empty, you can do except exceptions or (Exception,) as e:

http://stackoverflow.com/comment/88982706
type: AnswerComment
score: 0
type: Comment
has text: Great! Glad to help. Happy coding!
comment on: http://stackoverflow.com/a/50977393

http://stackoverflow.com/a/77182290
has comment: http://stackoverflow.com/comment/139015456
score: 23
has comment: http://stackoverflow.com/comment/138223120
downvote count: 0
answers question: http://stackoverflow.com/q/50927740
type: Answer
has body: Since version 2.0 of SQLAlchemy there's available if_not_exists parameter for the CreateSchema class. from sqlalchemy import create_engine from sqlalchemy.schema import CreateSchema connectable = create_engine("postgresql+psycopg2://postgres@localhost/postgres") with connectable.connect() as connection: connection.execute(CreateSchema("new_schema", if_not_exists=True)) connection.commit() Also there is available has_schema method for Inspector objects (created with inspect method) which can be used as a dialect-agnostic interface for database metadata to check existence of schema. Maybe you can find it usable in some situations. from sqlalchemy import create_engine, inspect from sqlalchemy.schema import CreateSchema schema = "new_schema" connectable = create_engine("postgresql+psycopg2://postgres@localhost/postgres") with connectable.connect() as connection: if not inspect(connection).has_schema(schema): connection.execute(CreateSchema(schema)) connection.commit()
upvote count: 23

http://stackoverflow.com/a/50935931
upvote count: 7
score: 7
has comment: http://stackoverflow.com/comment/88870475
type: AcceptedAnswer
downvote count: 0
has body: The property function does not have to be used as a decorator:decorator can be used as a function: class My_Class: def _set_x(self, value): self._x = value x = property(fset=_set_x) # now value has only a setter del _set_x # optional: delete the unneeded setter function instance = My_Class() instance.x= 8 # the setter works print(instance._x) # the "private" value print(instance.x) # raises: AttributeError: unreadable attribute
answers question: http://stackoverflow.com/q/50935795
type: Answer
has comment: http://stackoverflow.com/comment/88870556
accepted answer of: http://stackoverflow.com/q/50935795

http://stackoverflow.com/a/56411443
score: 1
answers question: http://stackoverflow.com/q/50957833
has body: Let me try and restate the problem: You work on two python packages, package A and package B. A depends on B. You have chosen to develop these two packages in separate virtual environments. You would like to make some local changes to package B and have package A use the modified version of package B. I apologize if I'm missing something here, but why not simply install both packages in the same virtual environment, which will make this problem go away? I.e. after creating your environment, you install package B in editable mode, followed by installing package A. Any changes in B will be picked up by A, no changes needed.
downvote count: 0
type: Answer
upvote count: 1

http://stackoverflow.com/q/50956747
tagged with: python
tagged with: matlab
type: AnsweredQuestion
has body: For a given matrix, I'm subtracting the maximum of each row from the row. In MATLAB, I'd do something like Xm = X - repmat(max(X,[],2), 1, size(X,2)); For Python, I've been toying with variations of Xm = X - np.matlib.repmat(np.max(X,axis = 1), 1, len(X[0])) but to no avail! Where exactly am I missing out? Thanks a lot.
downvote count: 0
has title: Repmat in Python v/s MATLAB
type: Question
score: 1
has comment: http://stackoverflow.com/comment/88912650
accepted answer: http://stackoverflow.com/a/50957709
has comment: http://stackoverflow.com/comment/88911054
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/88912797
favorite count: 0
has answer: http://stackoverflow.com/a/50957709

http://stackoverflow.com/comment/129891305
comment on: http://stackoverflow.com/a/73473320
score: 0
type: Comment
has text: While the stated advice is generally good, this post is **in no way** an answer to the question. Also, you are just ignoring the inputs and the overall intent of the OP. Moreover, it is very much debatable, if you **actually improved** the code with all your comments. In a language such as Python, choosing descriptive names often makes individual code passages self-explanatory, since they read like pseudo-code anyway. Your comments just re-state every line of code in English. **That is not good coding style.** What's the benefit of e.g. `# Type of wood.` above the line `woodType = "oak"`?
type: AnswerComment

http://stackoverflow.com/a/67484021
has body: For Anaconda/Jupyter Notebook: This solved my problem. Firstly go to your Anaconda Prompt. Then activate your environment (or skip this if you want to do it in base) pip3 install ipykernel --upgrade Then put this code. python -m ipykernel install --user --name torch --display-name "PyTorch (base)" Here, torch = name of your virtual env (put anaconda-base for the base environment) PyTorch (base) = display name you want to show in the kernel; replace it with your wish. Then you will see the option to change the kernel (From Kernel Option) to your virtual environment you are looking for. Before: Not Working State After: Working State And if it is in VS Code, please check this answer. This solves it perfectly. https://stackoverflow.com/a/64730974/9848043
downvote count: 0
type: Answer
upvote count: 3
answers question: http://stackoverflow.com/q/50914761
score: 3

http://stackoverflow.com/comment/88861936
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50931448
score: 0
has text: yes, class based view

http://stackoverflow.com/q/50881992
favorite count: 0
has title: How to pause and resume gradient taping in eager execution?
tagged with: python
accepted answer: http://stackoverflow.com/a/50882601
type: AnsweredQuestion
score: 1
upvote count: 1
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/50882601
answer count: 1
downvote count: 0
has body: I have a task which looks like this: # compute estimates from input net_estimate = my_model(inputs) # use this estimate to compute a target target_estimate = lots_of_computations(net_estimate) # compute loss loss = compute_loss(net_estimate, target_estimate) (For some context, this is for a reinforcement learning task, for which the resulting state — and the reward — depends on the action taken by the network.) The problem is that I do not want (indeed cannot) to compute the gradient of lots_of_computations. Ideally I would like to pause and resume gradient taping with tf.GradientTape() as tape: net_estimate = my_model(inputs) # target_estimate should be considered a constant target_estimate = lots_of_computations(net_estimate) with tape.resume(): loss = compute_loss(net_estimate, target_estimate) tape.gradient(loss, my_model.params) But GradientTape does not seem to offer something similar to that. Is there a way to achieve this in eager mode? My current workaround is to compute net_estimate twice, but that is clearly suboptimal.

http://stackoverflow.com/comment/88790256
type: Comment
type: QuestionComment
has text: Or to put it simple, just tell how to add *.txt files in a folder to combobox list and display them.
comment on: http://stackoverflow.com/q/50893792
score: 0

http://stackoverflow.com/comment/88818498
has text: You are absolutely right. Thanks so much!
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50908520
type: QuestionComment

http://stackoverflow.com/q/50937505
has title: Error with try and except and thread
tagged with: python
favorite count: 0
type: Question
tagged with: multithreading
upvote count: 1
answer count: 1
has body: I've written a program using thread. Here's an example of the code I've written: from time import sleep, time from threading import Thread def UserInfo(): global gamesummary Thread(target = CheckTime).start() gamesummary=open("gamesummary.txt","w+") AskQuestions() def CheckTime(): global gamesummary sleep(5) print("Time's up!") gamesummary.close() raise ValueError def AskQuestions(): global gamesummary try: while True: input("Program asks questions correctly here: ") gamesummary.write("Program correctly records information here") except ValueError: EndProgram() def EndProgram(): end=input("Would you like to play again?: ") if(end.lower()=="yes"): UserInfo() elif(end.lower()=="no"): print("Thank you for playing.") sleep(1) raise SystemExit else: print("Please enter either 'yes' or 'no'.\n") EndProgram() Everything in the program is done correctly and continues normally but this error shows up before EndProgram(): Exception in thread Thread-2: Traceback (most recent call last): File "C:\Users\akeri\AppData\Local\Programs\Python\Python36-32\lib\threading.py", line 916, in _bootstrap_inner self.run() File "C:\Users\akeri\AppData\Local\Programs\Python\Python36-32\lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "x-wingide-python-shell://105807224/2", line 15, in CheckTime ValueError This error doesn't stop the program from functioning. I don't understand why the try and except statement isn't catching this exception. I think it is because I'm creating two errors? I'm new to using python, and I'd really appreciate any help I can get with this.
has answer: http://stackoverflow.com/a/50937547
tagged with: try-catch
downvote count: 0
score: 1
accepted answer: http://stackoverflow.com/a/50937547
type: AnsweredQuestion

http://stackoverflow.com/q/50996122
answer count: 1
downvote count: 0
has title: Scraper keeps on crawling identical links
favorite count: 0
tagged with: python-3.x
tagged with: python
has body: I've written a script in python in combination with BeautifulSoup to go on to the next page of a website using it's pagination button (there is a link connected to this button) until there is no new page to crawl. My script can crawl next pages using the pagination link. However, the problem is that the paginated links never end as the button (connected to next page link) doesn't gray out so I fall into an infinite loop. How can I get rid of that in such a way so that the script will check if I'm scraping two identical links cosecutively and as soon as it finds one it will break. This is my script so far: import requests from bs4 import BeautifulSoup def get_content(link): while True: res = requests.get(link) soup = BeautifulSoup(res.text, 'lxml') #some code here to do the rest of the activity nextpage = soup.select_one(".roundright a") if not nextpage:break #The loop doesn't break because the next page button never grayes out link = nextpage.get("href") print(link) if __name__ == '__main__': url = "http://www.viprealestateug.com/action/rentals/" get_content(url) The results it produces: http://www.viprealestateug.com/action/rentals/page/2/ http://www.viprealestateug.com/action/rentals/page/3/ http://www.viprealestateug.com/action/rentals/page/4/ http://www.viprealestateug.com/action/rentals/page/4/ http://www.viprealestateug.com/action/rentals/page/4/ and so on I could have avoided such issues if I wished to go for any hardcoded approach but that is not what my intention is.
accepted answer: http://stackoverflow.com/a/50996274
type: AnsweredQuestion
score: 1
tagged with: web-scraping
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/50996274

http://stackoverflow.com/q/50858265
has comment: http://stackoverflow.com/comment/88726414
accepted answer: http://stackoverflow.com/a/50874818
linked to: http://stackoverflow.com/q/50873615
downvote count: 0
answer count: 1
tagged with: keras
favorite count: 0
has title: Using noise_shape of the Dropout layer. Batch_size does not fit into provided samples. What to do?
tagged with: python
has body: I am using a dropout layer in my model. As I use temporal data, I want the noise_shape to be the same per timestep -> (batch_size, 1, features). The problem is if I use a batch size that does not fit into the provided samples, I get an error message. Example: batch_size= 2, samples= 7. In the last iteration, the batch_size (2) is larger than the rest of the samples (1) The other layers (my case: Masking, Dense, and LSTM) apparently don`t have a problem with that and just use a smaller batch for the last, not fitting, samples. ConcreteError: Training data shape is:[23, 300, 34] batchsize=3 InvalidArgumentError (see above for traceback): Incompatible shapes: [2,300,34] vs. [3,1,34] [[Node: dropout_18/cond/dropout/mul = Mul[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"](dropout_18/cond/dropout/div, dropout_18/cond/dropout/Floor)]] Meaning that for the last batch [2,300,34], the batch_size cannot split up into [3,1,34] As I am still in the parameter tuning phase (does that ever stop :-) ), Lookback(using LSTMs), split-percentage of train/val/test, and batchsize will still constantly change. All of the mentioned influence the actual length and shape of the Training data. I could try to always find the next fitting int for batch_size by some calculations. Example, if batch_size=4 and samples=21, I could reduce batch_size to 3. But if the number of training samples are e.g. primes this again would not work. Also If I choose 4, I probably would like to have 4. Do I think to complex? Is there a simple solution without a lot of exception programming? Thank you
tagged with: dropout
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/50874818
has comment: http://stackoverflow.com/comment/88725866
upvote count: 1
tagged with: tensorflow
type: Question

http://stackoverflow.com/q/50908455
has comment: http://stackoverflow.com/comment/88816983
possible better answer: http://stackoverflow.com/a/50908826
downvote count: 0
has answer: http://stackoverflow.com/a/50908493
has body: I need help on regex that filters out 'N' followed by any combination of digits. import re exp = "1+2+N32.23" variable_refs = re.compile(r"([0-9]+)") exp_template = re.sub(variable_refs, r'{key_\1}', exp) Current output: {key_1}+{key_2}+N{key_32} Expected output: {key_1}+{key_2}+N32.23
type: AnsweredQuestion
score: 1
has title: regex that filters out 'N' followed by any combination of digits
type: Question
answer count: 3
has answer: http://stackoverflow.com/a/50908826
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50908512
accepted answer: http://stackoverflow.com/a/50908512
tagged with: python
tagged with: regex
tagged with: python-3.x

http://stackoverflow.com/q/50877693
tagged with: python
has comment: http://stackoverflow.com/comment/88758202
answer count: 0
type: Question
tagged with: numpy
has title: numpy mean and sum not permutable
linked to: http://stackoverflow.com/q/588004
has comment: http://stackoverflow.com/comment/88757535
score: 0
has comment: http://stackoverflow.com/comment/88758534
has comment: http://stackoverflow.com/comment/88758572
has body: I'm concerned about the fact that computing np.mean(np.sum(x, axis=1)) does not give the same result as np.sum(np.mean(x, axis=0)). For instance: import numpy as np np.random.seed(123) x = np.random.randint(1000, 100) sm = np.sum(np.mean(x, axis=0)) ms = np.mean(np.sum(x, axis=1)) print('sm {}'.format(sm)) print('ms {}'.format(ms)) print('sm == ms {}'.format(sm == ms)) prints sm 0.1314820175147663 ms 0.13148201751476632 sm == ms False Is this a numpy issue or am I missing something? (obviously all types are equal in this calculation, np.float64; casting x to np.float64 does not change anything) Python 3.6.4, numpy 1.14.5
has comment: http://stackoverflow.com/comment/88759594
has comment: http://stackoverflow.com/comment/88757567
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88759419

http://stackoverflow.com/q/50941529
has comment: http://stackoverflow.com/comment/88883224
has body: Consider the following data frame, cols = ['Id', 'col1', 'col2', 'col3'] vals = [('1A','Not his side|:|This side', 'This side', 'Not this either|:|but this'), ('1B','Keep this', 'This one|:|keep this', 'remove|:|keep that')] dd1 = sqlContext.createDataFrame(vals, cols) #+---+------------------------+--------------------+--------------------------+ #|Id |col1 |col2 |col3 | #+---+------------------------+--------------------+--------------------------+ #|1A |Not his side|:|This side|This side |Not this either|:|but this| #|1B |Keep this |This one|:|keep this|remove|:|keep that | #+---+------------------------+--------------------+--------------------------+ What I need to do is to split the strings at |:| and keep the second word. However, If the string does not contain the delimiter (|:|), then I get null, i.e.: users1 = [F.split(F.col(x), "\\|:\\|").alias(x) for x in cols] dd1.select(*users1).show() #+---------+---------+---------+ #| col1| col2| col3| #+---------+---------+---------+ #|This side| null| but this| #| null|keep this|keep that| #+---------+---------+---------+ The result I'm looking for is: +---+---------+---------+---------+ |Id |col1 |col2 |col3 | +---+---------+---------+---------+ |1A |This side|This side|but this | |1B |Keep this|keep this|keep that| +---+---------+---------+---------+
has answer: http://stackoverflow.com/a/50941908
type: AnsweredQuestion
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/88882101
accepted answer: http://stackoverflow.com/a/50941948
type: Question
tagged with: apache-spark-sql
has title: Split string IF delimiter is found
tagged with: pyspark
tagged with: apache-spark
answer count: 3
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/50941948
has comment: http://stackoverflow.com/comment/88881978
tagged with: python
possible better answer: http://stackoverflow.com/a/50941908
has answer: http://stackoverflow.com/a/50942024

http://stackoverflow.com/comment/88939149
has text: What you want to do?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50971279
score: 0

code-coverage
tags question: http://stackoverflow.com/q/50895525
type: Tag
tag name: code-coverage
tags question: http://stackoverflow.com/q/50858550

http://stackoverflow.com/comment/88758251
score: 0
has text: This is the correct answer. In context, the example code would be `locals()[co]()`
type: Comment
comment on: http://stackoverflow.com/a/50877818
type: AnswerComment

punctuation
tags question: http://stackoverflow.com/q/50875037
tag name: punctuation
type: Tag

http://stackoverflow.com/comment/88832474
has text: What's `options.q`?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50916206

http://stackoverflow.com/q/50953507
score: 0
has body: i have a file that is formatted as shown below: 2017-09-02 14:51:13,959 this is a sentence 2017-09-02 14:51:13,959 this is another sentence 2017-09-02 14:51:13,959 this is yet another a sentence My end goal is to have an excel sheet with columns for date/time/sentence. to get there i am attempting to import the file as a list and then split each list item at the first two spaces. and then add each item to the end of a new list ex: 2017-09-02 14:51:13,959 this is a sentence this is the code i have been trying to get to work, but i cant get the split function to work. file = input("drag log file here. ") list1 = open(file).readlines() for i in list1: s = list1[i] list2.append(s.split(" ",2)[2]) print(list2) i keep getting all sorts of errors depending on what i try but currently its showing Traceback (most recent call last): s = str(list1[i]) TypeError: list indices must be integers or slices, not str so i guess my question are: what does this error mean and how do i attempt to fix it? is there a better way to get to my end goal of the excel sheet? would it be easier to modify the list into a csv file?
answer count: 1
has answer: http://stackoverflow.com/a/50953541
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50953541
type: Question
tagged with: split
has title: how can i split each list entry at the first two spaces and add them all into a new list

http://stackoverflow.com/comment/88906200
type: QuestionComment
has text: @Kevin thanks, I will change that since what I'm doing is redundant. For the sake of this question lets assume I am not replacing text and doing some other operation based on if something is in a string, is it possible to create a dictionary switcher?
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50954147

http://stackoverflow.com/a/50896749
score: 3
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50896266
has body: The Numpy unique function can do this, you just have to tell it to return the indices of the unique array that can be used to reconstruct the original array. Here's a short demo, based on the example in the docs. import numpy as np np.random.seed(42) # Create an array of repeated "large" values a = np.random.randint(0, 5, size=20) * 11 print(a) # Extract the sorted unique values, and the indices of the unique # array which can be used to reconstruct the original array u, inv = np.unique(a, return_inverse=True) print(inv) new = u[inv] print(new) output [33 44 22 44 44 11 22 22 22 44 33 22 44 11 33 11 33 44 0 33] [3 4 2 4 4 1 2 2 2 4 3 2 4 1 3 1 3 4 0 3] [33 44 22 44 44 11 22 22 22 44 33 22 44 11 33 11 33 44 0 33]
upvote count: 3
answers question: http://stackoverflow.com/q/50896266
type: Answer
has comment: http://stackoverflow.com/comment/139032118

http://stackoverflow.com/a/66942432
has comment: http://stackoverflow.com/comment/132191804
answers question: http://stackoverflow.com/q/50951955
has body: For Windows in simple steps: Download Windows version from https://github.com/UB-Mannheim/tesseract/wiki Install Write following in your .py file (check installed location) pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe" img_text = pytesseract.image_to_string(Image.open(filename))
downvote count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/131429063
type: Answer
score: 2

http://stackoverflow.com/q/50912312
answer count: 1
has title: scikit-learn error: libquadmath.so.0: cannot open shared object file: No such file or directory
has answer: http://stackoverflow.com/a/50914171
type: AnsweredQuestion
tagged with: scikit-learn
accepted answer: http://stackoverflow.com/a/50914171
type: Question
has body: I got this erreur when I've tried to import scikit learn to my python 3.5 (jupyter notebook): from sklearn.model_selection import train_test_split --------------------------------------------------------------------------- ImportError Traceback (most recent call last) &lt;ipython-input-5-139cc3505715&gt; in &lt;module&gt;() ----&gt; 1 from sklearn.model_selection import train_test_split /opt/Anaconda/Anaconda3-4.2.0/lib/python3.5/site-packages/sklearn/__init__.py in &lt;module&gt;() 55 else: 56 from . import __check_build ---&gt; 57 from .base import clone 58 __check_build # avoid flakes unused variable error 59 /opt/Anaconda/Anaconda3-4.2.0/lib/python3.5/site-packages/sklearn/base.py in &lt;module&gt;() 10 from scipy import sparse 11 from .externals import six ---&gt; 12 from .utils.fixes import signature 13 from .utils.deprecation import deprecated 14 from .exceptions import ChangedBehaviorWarning as _ChangedBehaviorWarning /opt/Anaconda/Anaconda3-4.2.0/lib/python3.5/site-packages/sklearn/utils/__init__.py in &lt;module&gt;() 9 10 from .murmurhash import murmurhash3_32 ---&gt; 11 from .validation import (as_float_array, 12 assert_all_finite, 13 check_random_state, column_or_1d, check_array, /opt/Anaconda/Anaconda3-4.2.0/lib/python3.5/site-packages/sklearn/utils/validation.py in &lt;module&gt;() 16 17 from ..externals import six ---&gt; 18 from ..utils.fixes import signature 19 from .deprecation import deprecated 20 from ..exceptions import DataConversionWarning as _DataConversionWarning /opt/Anaconda/Anaconda3-4.2.0/lib/python3.5/site-packages/sklearn/utils/fixes.py in &lt;module&gt;() 289 from ._scipy_sparse_lsqr_backport import lsqr as sparse_lsqr 290 else: --&gt; 291 from scipy.sparse.linalg import lsqr as sparse_lsqr 292 293 /opt/Anaconda/Anaconda3-4.2.0/lib/python3.5/site-packages/scipy/sparse/linalg/__init__.py in &lt;module&gt;() 110 from __future__ import division, print_function, absolute_import 111 --&gt; 112 from .isolve import * 113 from .dsolve import…
score: 0
tagged with: python

http://stackoverflow.com/q/50979069
upvote count: 2
tagged with: pandas
has body: I have been looking for the most efficient way to find the first value in all columns of a pandas df, from left to right (0,1,2,3), for each row, that is greater than another column (t), and put the corresponding column label in a new column (val). If no column value is greater, then I want 0 instead. For some reason I could not find anything simple and efficient (as the real table is really big). E.g: Initial table: t 0 1 2 3 JAN 3 1.9 2.1 2.6 2.9 FEB 6 2.0 4.0 5.0 9.0 MAR 2 1.0 3.0 4.0 4.0 APR 4 1.5 3.0 6.0 2.0 Final table: t 0 1 2 3 val JAN 3 1.9 2.1 2.6 2.9 0 FEB 6 2.0 4.0 5.0 9.0 3 MAR 2 1.0 3.0 4.0 4.0 1 APR 4 1.5 3.0 6.0 2.0 2
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50980050
accepted answer: http://stackoverflow.com/a/50980050
tagged with: python
linked to: http://stackoverflow.com/q/45935143
score: 2
type: AnsweredQuestion
downvote count: 0
type: Question
has title: Find first value in dataframe's columns greater than another

http://stackoverflow.com/comment/88840575
type: Comment
type: QuestionComment
has text: Where is your tf.placeholder? Where is keras.compile? Essentially you only need to pass the output tensor name.
score: 0
comment on: http://stackoverflow.com/q/50919824

http://stackoverflow.com/a/50876860
has comment: http://stackoverflow.com/comment/88756160
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88756247
type: Answer
has comment: http://stackoverflow.com/comment/88756755
upvote count: 0
accepted answer of: http://stackoverflow.com/q/50876768
answers question: http://stackoverflow.com/q/50876768
has comment: http://stackoverflow.com/comment/88770625
has body: Do you want this? def nSum(num): #calculating values for the variable (num) to the p power: p = 0 newValue = 0 total_value=0 #new variable for i in range(num): currentVal = num * 10**p p = p+1 #running total of the curent values: newValue = currentVal + newValue print(newValue) total_value+=newValue #new line return total_value print(nSum(3)) #Want nSum to be total of all the newValues from the loop Or you can do it without using p variable.You can do it only using i variable.Like : def nSum(num): #calculating values for the variable (num) to the p power: newValue = 0 total_value=0 for i in range(num): currentVal = num * 10**i #running total of the curent values: newValue = currentVal + newValue print(newValue) total_value+=newValue return total_value print(nSum(3)) #Want nSum to be total of all the newValues from the loop
score: -2
has comment: http://stackoverflow.com/comment/88771110
downvote count: 2

http://stackoverflow.com/a/50956283
accepted answer of: http://stackoverflow.com/q/50955371
type: Answer
answers question: http://stackoverflow.com/q/50955371
has body: It's possible because a list (like other containers) store references, and why not a reference of itself? The __str__ / __repr__ functions have been protected against this to avoid infinite recursion, and show an ellipsis instead (...). Why is it possible? Because it's not impossible. If Python were to prevent that, it would mean checking for self-referencing every time an object is added in the list. This would either be an additional O(n) storage overhead for maintaining a reference cache, or an O(n) time overhead for performing a reference search.
score: 3
upvote count: 3
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/50950902
tagged with: python
score: 4
has answer: http://stackoverflow.com/a/72063082
has body: When creating conda virtual environment with YAML file for the first time, I unknowingly ran: conda env update -f environment.yml call activate process_name which successfully created a venv in: C:\Users\userName\AppData\Local\Continuum\anaconda3\envs. Should I have ran the following instead? conda env create -f environment.yml call activate process_name Does conda env update create a new venv if no existing venv is found in the anaconda envs directory? How stable is conda env update in defaulting to creating a new venv if no existing venv is found?
type: Question
tagged with: anaconda
has answer: http://stackoverflow.com/a/54167487
tagged with: conda
upvote count: 4
answer count: 2
has title: creating conda venv: conda env create VS conda env update
downvote count: 0
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/50977255
upvote count: 3
has comment: http://stackoverflow.com/comment/88951828
answer count: 2
favorite count: 0
has answer: http://stackoverflow.com/a/50977382
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88959292
has answer: http://stackoverflow.com/a/50978039
tagged with: xpath
tagged with: selenium-chromedriver
downvote count: 0
tagged with: selenium
has comment: http://stackoverflow.com/comment/88951799
type: Question
has title: Selenium find by xpath inside Webelement
score: 3
has body: I have this page: Document Example Section 1 Section 2 Section 3 I want group links by sections: driver.get("mypage.com") sections = driver.find_elements_by_xpath("//div[@class='section']") for section in sections: section_name = section.find_element_by_xpath("//h1[@class='name']").get_attribute('innerHTML') #This fails links = section.find_elements_by_xpath("//ul/a") #This find all links in page, not only links in section The problem, I find a list of elements (WebElement) in all page by xpath, and now I want find by xpath all specific elements inside a element section, not in all page. What's wrong? Edit 1 This resolve the problem (now the xpath start whit dot . ): driver.get("mypage.com") sections = driver.find_elements_by_xpath("//div[@class='section']") for section in sections: section_name = section.find_element_by_xpath(".//h1[@class='name']").get_attribute('innerHTML') #This fails links = section.find_elements_by_xpath(".//ul/a") #This find all links in page, not only links in section Here the explanation y found after: http://selenium-python.readthedocs.io/api.html#selenium.webdriver.remote.webelement.WebElement.find_element_by_xpath

http://stackoverflow.com/comment/88721947
score: 0
comment on: http://stackoverflow.com/a/50859395
type: AnswerComment
has text: Your solution makes sense, and also works. Thanks @kazemakase.
type: Comment

http://stackoverflow.com/comment/88859982
comment on: http://stackoverflow.com/a/50930308
has text: You can change the way you are applying the decorator, fancy `@` syntax does exactly this, only on local functions: `my_lib.my_func = interceptor(my_lib.my_func)`
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50934784
upvote count: 1
has answer: http://stackoverflow.com/a/51046560
type: Question
answer count: 2
downvote count: 0
favorite count: 0
has title: Bad pixel removal using dask array
tagged with: dask
has body: I have a very large 4 dimensional dataset, where the two last dimensions are images taken on an image detector. Some of the pixels on this detector does not work, and these dead pixels gives a value of 0. I'd like to set the value of these pixels to the median of their neighbors in post processing. The datasets range from 8 GB to possibly TB size, so I'd like to use dask array, since I can chain the dead pixel removal together with other processing steps. Finding the dead pixels is easy, but I'm not certain how to best get the median of the neighbors. Minimal example: import numpy as np import dask.array as da data = np.random.randint(10, 50, size=(10, 10, 20, 20)) data[:, :, 2, 7] = 0 data[:, :, 9, 3] = 0 dask_array = da.from_array(data, chunks=(5, 5, 5, 5)) dask_array_mean = dask_array.mean(axis=(0, 1)) dead_pixels = dask_array_mean == 0 # Some kind of processing dask_array_without_dead_pixels = dask_array + dead_pixel_values_array So my question is: how do I get dead_pixel_values_array? Or some other clever way of removing the dead pixels?
type: UnansweredQuestion
tagged with: python
score: 1
has answer: http://stackoverflow.com/a/50936569

http://stackoverflow.com/q/50983372
accepted answer: http://stackoverflow.com/a/50983432
score: 1
tagged with: selenium
upvote count: 1
type: Question
has body: I am using Selenium and python to extract table from HTML but I am able to extract only first table. I want to extract second table also I am new t selenium. Html code &lt;div class="fondo-top"&gt; &lt;h3&gt;Flood Forecasted Site&lt;/h3&gt; &lt;div class="editorwys"&gt; &lt;h4&gt;Site Name : Araria&lt;/h4&gt; &lt;table style="width: 100%"&gt; &lt;tbody&gt;&lt;tr&gt; &lt;th style="width: 25%"&gt;&lt;strong&gt;District Name:&lt;/strong&gt;&lt;/th&gt; &lt;td style="width: 25%"&gt;&lt;strong&gt;Araria&lt;/strong&gt;&lt;/td&gt; &lt;th style="width: 25%"&gt;&lt;strong&gt;Warning Level (WL):&lt;/strong&gt;&lt;/th&gt; &lt;td style="width: 25%"&gt;&lt;strong&gt; Meters (m)&lt;/strong&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th&gt;&lt;strong&gt;River Name:&lt;/strong&gt;&lt;/th&gt; &lt;td&gt;&lt;strong&gt;Mahananda&lt;/strong&gt;&lt;/td&gt; &lt;th&gt;&lt;strong&gt;Danger Level (DL):&lt;/strong&gt;&lt;/th&gt; &lt;td&gt;&lt;strong&gt; Meters (m)&lt;/strong&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th&gt;&lt;strong&gt;Basin Name:&lt;/strong&gt;&lt;/th&gt; &lt;td&gt;&lt;strong&gt;GANGA&lt;strong&gt;&lt;/strong&gt;&lt;/strong&gt;&lt;/td&gt; &lt;th&gt;&lt;strong&gt;Highest Flood Level (HFL):&lt;/strong&gt;&lt;/th&gt; &lt;td&gt;&lt;strong&gt;49.4 Meters (m)&lt;strong&gt;&lt;/strong&gt;&lt;/strong&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th&gt;&lt;strong&gt;Division Name:&lt;/strong&gt;&lt;/th&gt; &lt;td&gt;&lt;a target="_blank" href="/opencms/opencms/ffs/Detail?code=029-mgd4ptn " onclick="window.open(this.href, this.target, 'width=1000, height=600, toolbar=no, resizable=no'); return false;"&gt;Lower Ganga Division-I(LGD-I), Patna&lt;/a&gt;&lt;/td&gt; &lt;th&gt;&lt;strong&gt;HFL Attained date:&lt;/strong&gt;&lt;/th&gt; &lt;td&gt;14-08-2017&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt;&lt;/table&gt; &lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;table&gt; &lt;tbody&gt;&lt;tr&gt; &lt;th colspan="3" style="text-align: center;"&gt;&lt;strong&gt;PRESENT WATER LEVEL&lt;/strong&gt;&lt;/th&gt; &lt;/tr&gt; &lt;…
has answer: http://stackoverflow.com/a/50983432
downvote count: 0
answer count: 1
favorite count: 0
has title: extracting second table from HTML using Selenium na python
tagged with: python
tagged with: selenium-webdriver
type: AnsweredQuestion

http://stackoverflow.com/a/50903462
answers question: http://stackoverflow.com/q/50903253
has comment: http://stackoverflow.com/comment/88807016
has body: The to_sql method has an if_exists parameter: if_exists : {‘fail’, ‘replace’, ‘append’}, default ‘fail’ How to behave if the table already exists. fail: Raise a ValueError. replace: Drop the table before inserting new values. append: Insert new values to the existing table. Also notice that it says: Raises: ValueError When the table already exists and if_exists is ‘fail’ (the default). Since you haven't passed anything, you get the default, fail. So, after the table gets created for the first DataFrame, every subsequent DataFrame raises a ValueError, just as the docs say it will. And the ValueError tells you exactly what's wrong: Table 'Trainstat' already exists. Since you want to append to the table rather than failing, just add if_exists='append' to your call.
type: Answer
score: 2
downvote count: 0
upvote count: 2

http://stackoverflow.com/comment/88878026
type: Comment
has text: I found diagflat does the job too!
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/50931965

http://stackoverflow.com/q/50960165
upvote count: 1
answer count: 1
tagged with: python
has body: In python we use optparse to format our CLI parameters. However, I don't know how to apply add_option() on supporting combined or a groups of arguments. For example: 1) How can my CLI support combined paramters: eg: python test.py -ah actually, this command can expand to: python test.py -a -h 2) How can my CLI support groups parameters: eg: python test.py -f f1.txt f2.txt f3.txt in this example: space is the separator, we can also define comma also as the separator. I don't know whether optparse can support.
favorite count: 0
accepted answer: http://stackoverflow.com/a/50960243
has comment: http://stackoverflow.com/comment/88917260
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50960243
downvote count: 0
tagged with: optparse
score: 1
has comment: http://stackoverflow.com/comment/88955413
type: Question
has title: How to apply optparse to parse a group of parameters

http://stackoverflow.com/comment/88732145
type: QuestionComment
comment on: http://stackoverflow.com/q/50863162
score: 0
has text: Well `psutil.cpu_percent(interval=1,percpu=True)` does return a list, but I understand calling the print function translated it in someway. I would have avoided it had I know how to, but without this `print` I only get an empty string-byte `b''` from my `subprocess.check_output`.
type: Comment

http://stackoverflow.com/comment/91127977
has text: This what I get when I run the last command: (Canopy 64bit) Zacharys-MacBook-Pro:~ zacharystow$ pip install --upgrade pyqt5>=5.10 Could not find a version that satisfies the requirement pyqt5 (from versions: ) No matching distribution found for pyqt5
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50893317

http://stackoverflow.com/q/50927972
linked to: http://stackoverflow.com/q/38627870
answer count: 1
favorite count: 0
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88856255
downvote count: 0
has title: PIL: pasting an image onto another image, calculate position
type: Question
score: 3
tagged with: python-imaging-library
has body: I'm trying to paste one image onto antoher but can't calculate positions other than left top corner. How to calculate position for right top/bottom corner and left bottom corner? from io import BytesIO from PIL import Image def add_watermark(): original_image = Image.open('test1.jpg') watermark = Image.open('watermark.png') watermark_width, watermark_height = watermark.size x, y = original_image.size margin = 40 # left top position = ((0 + margin, 0 + margin)) image_with_watermark = Image.new('RGBA', (x, y), (0, 0, 0, 0)) image_with_watermark.paste(original_image, (0, 0)) image_with_watermark.paste(watermark, position, mask=watermark) image_with_watermark.show() buffer = BytesIO() image_with_watermark.save(fp=buffer, format='jpeg') add_watermark()
has answer: http://stackoverflow.com/a/50928231
accepted answer: http://stackoverflow.com/a/50928231
upvote count: 3

http://stackoverflow.com/a/51000203
answers question: http://stackoverflow.com/q/51000132
has body: To get this behaviour without polluting namespace with global variables or turning c* functions into classes I would implement it like this: conditions = [c1, c2, c3] for index, cond in enumerate(conditions): if cond(): foo1() foo2() print(f"foo1() and foo2() have been executed because condition {index} is true") break this basically hardcodes or behaviour, but other than that is fine.
has comment: http://stackoverflow.com/comment/88994650
has comment: http://stackoverflow.com/comment/88995103
score: 0
type: Answer

http://stackoverflow.com/q/50939778
type: AnsweredQuestion
score: 1
tagged with: matplotlib
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/50939792
has title: 2D Histogram normalized for probabilities
answer count: 1
tagged with: histogram
accepted answer: http://stackoverflow.com/a/50939792
favorite count: 0
has body: I have a 2D data set and I would like to plot a 2D histogram, with each cell on the histogram representing the probability of the data point. Hence to obtain the probability, I need to normalize the histogram data so they sum to 1. Here is what I have for an example, from the 2Dhistogram documentation: xedges = [0,1,3,5] yedges = [0,2,3,4,6] #create edges of bins #create random data points x=np.random.normal(2,1,100) y=np.random.normal(1,1,100) H,xedges,yedges = np.histogram2d(x,y,bins=(xedges,yedges)) #setting normed=True in histogram2d doesn't seem to do what I need H=H.T #weirdly histogram2d swaps the x,y axis, so transpose to restore it. fig = plt.figure(figsize=(7,3)) plt.imshow(H,interpolation='nearest',origin='low',extent=[xedges[0], xedges[-1],yedges[0],yedges[-1]]) plt.show() Resulting plot Firstly, a np.sum(H) gives something like 86. I would like each cell to represent the probability of the data lying on that binned cell, so they should all sum to 1. Additionally, how do you plot a legend mapping the color intensity to its value with imshow? Thank you!
upvote count: 2
tagged with: python

http://stackoverflow.com/comment/88767350
type: Comment
type: QuestionComment
has text: Has the documentation not been updated as of 3.6? Based on [this](https://docs.python.org/3/reference/datamodel.html#object.__del__), it still seems like an implementation detail as to if `__del__` can be called twice.
comment on: http://stackoverflow.com/q/50882416
score: 0

http://stackoverflow.com/q/51002272
tagged with: z3py
has comment: http://stackoverflow.com/comment/88998352
has comment: http://stackoverflow.com/comment/88998401
possible better answer: http://stackoverflow.com/a/51004225
has answer: http://stackoverflow.com/a/51004225
has comment: http://stackoverflow.com/comment/88998375
tagged with: smt
has body: Suppose I have a z3py integer variable x = Int('x'), and an integer array a = [1, 2, 3]. Then I add a constraint through s.add(x in a). I think this is satisfiable because x can be 1 or 2 or 3. But it's unsitisfiable actually. Can anyone tell me how can I add a constraint to make sure x in a? Thanks! Here is the python code I used. I thought the output answer would be s is satisfiable, because x can be equal to 1 or 2 or 3, then the constraint x in a is satisfied. But the answer is actually unsat. Maybe this is not the right method to specify this constraint. So my question is how to specify such a constraint to make sure a variable can only be instantiated with the value in a specific array. from z3 import * x = Int('x') a = [1, 2, 3] s = Solver() s.add(x in a) print(s.check())
has comment: http://stackoverflow.com/comment/88998693
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51002516
downvote count: 0
has answer: http://stackoverflow.com/a/63972226
has comment: http://stackoverflow.com/comment/88998454
favorite count: 0
has comment: http://stackoverflow.com/comment/88998598
has title: How to add a constraint which requires an integer variable belongs to an array?
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/88998434
has comment: http://stackoverflow.com/comment/88998443
has comment: http://stackoverflow.com/comment/88998404
tagged with: python
has comment: http://stackoverflow.com/comment/88998778
has comment: http://stackoverflow.com/comment/88998429
tagged with: z3
has comment: http://stackoverflow.com/comment/88998634
answer count: 3
has comment: http://stackoverflow.com/comment/88998385
has answer: http://stackoverflow.com/a/51002516

http://stackoverflow.com/q/50892254
score: 0
answer count: 1
tagged with: stripe-payments
tagged with: stripe-connect
tagged with: django
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50894536
accepted answer: http://stackoverflow.com/a/50894536
has body: I am trying to create an account on Stripe Connect, using the code provided by Stripe. Everything is working fine, I submit the create, and I record the stripe_id to my database. However, if I want to get the keys also, how can I retrieve them? What is the proper syntax to do so? Here is my code in the view: if form.is_valid(): mail = form.cleaned_data['email'] name = form.cleaned_data['first_name'] lastName = form.cleaned_data['last_name'] country = form.cleaned_data['country'] stripeId = stripe.Account.create(type="custom", country=country, email=mail, ) p = UserStripe.objects.create( user=request.user, stripe_id=stripeId['id']) print(p) print(stripeId['id']) The keys are returned by the API as: &lt;Account account id=... at 0x00000a&gt; JSON: { "id": "acct_1033zf2gFw4ArzaQ", . . . "keys": { "secret": "sk_test_AdveEkmolYxHOzV4K4qLWoJt", "publishable": "pk_test_Gt3Bk3C07gz2wnrI3hQWJQIi" } } So to get the id I am using stripeId['id'], but how can I get the info inside the keys and pass it to my database? Thank you.
type: Question
has title: Django Stripe Connect account creation

http://stackoverflow.com/comment/88795021
type: QuestionComment
comment on: http://stackoverflow.com/q/50897444
has text: ..which is a 4 dimensional tensor, just as the error is telling you. Your layers are obviously not resulting in your desired prediction shape.
score: 0
type: Comment

http://stackoverflow.com/comment/88908167
comment on: http://stackoverflow.com/q/50955219
score: 0
has text: Without knowing anything about what's in those files or what their format is like, we can't tell you how to put the data into a different format.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50963534
has title: Mapping values based on 'from' and 'to' columns in a dataframe
tagged with: dataframe
has comment: http://stackoverflow.com/comment/88923843
has answer: http://stackoverflow.com/a/50968643
has comment: http://stackoverflow.com/comment/88966123
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88923736
type: Question
tagged with: pandas
has comment: http://stackoverflow.com/comment/88924070
has comment: http://stackoverflow.com/comment/88923803
has body: I have a pandas dataframe example below. From|to 01|03 05|09 03|02 02|06 The final_value should be updated with the latest data i.e., 01 is changed to 03 later 03 is changed to 02 and so on 02 is changed to 06. So 01 should be replaced with latest value 06 and 03 should be be replaced with latest value 06 and so on I need to map these like below based on 'from' and 'to' columns. Please let me know how i can make use of operations on dataframe? From|to|final_value 01|03|06 05|09|09 03|02|06 02|06|06
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/88967101
score: 0

http://stackoverflow.com/q/50901296
has comment: http://stackoverflow.com/comment/88802449
accepted answer: http://stackoverflow.com/a/50901342
has comment: http://stackoverflow.com/comment/88802471
tagged with: loops
type: AnsweredQuestion
tagged with: math
type: Question
score: 0
has answer: http://stackoverflow.com/a/50901342
has body: question answerers and python wizards, I am a weary apprentice seeking some help from a fellow traveller. inventory = { 'gold' : [500, 600, 700, 800], 'pouch' : ['flint', 'twine', 'gemstone'], 'backpack' : ['xylophone','dagger', 'bedroll','bread loaf'] } I essentially want to iterate through the 'gold' key and add 50 to each value and have that stored [permanently in the original dictionary]. Now, I know how to do it individually... inventory['gold'][0] += 50 inventory['gold'][1] += 50 inventory['gold'][n] += n... but, I'm guessing there must be an easier way to do this task?!!!! Right??! Any help would be appreciated. Thank y'all in advance!
answer count: 1
has title: Python: Iterate through list contained within dictionary and perform mathematical operation
has comment: http://stackoverflow.com/comment/88802442
linked to: http://stackoverflow.com/q/9304408
duplicate of: http://stackoverflow.com/q/9304408
tagged with: python
tagged with: dictionary

http://stackoverflow.com/q/50979757
type: Question
has comment: http://stackoverflow.com/comment/88956231
has body: I am trying to flatten out a pandas df. For the df below I'm trying to move the names up in Column E and shift the other columns to the right. import pandas as pd d = ({ 'D' : ['08:00:00','X','08:10:00','X'], 'H' : ['1','','1',''], 'B' : ['Stop','X','Res','X'], 'A' : ['X','','X',''], 'C' : ['En','X','Se','X'], 'E' : ['M','John','M','Gary'], 'F' : ['Place','','Place',''], }) df = pd.DataFrame(data=d) Output: A B C D E F H 0 X Stop En 08:00:00 M Place 1 1 X X X John 2 X Res Se 08:10:00 M Place 1 3 X X X Gary Whereas my intended output is: A B C D E F G 0 X Stop En 08:00:00 John Place 1 1 X Res Se 08:10:00 Gary Place 1 I've have tried df = pd.DataFrame(np.column_stack((df.iloc[::2], df.iloc[1::2, [0]])), columns=['A','B','C','D','E','F','G','H']) But this drops the Names: A B C D E F G H 0 X Stop En 08:00:00 M Place 1 1 X Res Se 08:10:00 M Place 1
has title: Flatten pandas df
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/88956259
has answer: http://stackoverflow.com/a/50980521
has comment: http://stackoverflow.com/comment/88956371
possible better answer: http://stackoverflow.com/a/50980229
has answer: http://stackoverflow.com/a/50980229
has answer: http://stackoverflow.com/a/50980455
tagged with: python
tagged with: flatten
answer count: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88956194
accepted answer: http://stackoverflow.com/a/50980455
has answer: http://stackoverflow.com/a/50980304

http://stackoverflow.com/comment/112353747
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50920990
has text: This solucion works very nice: https://stackoverflow.com/a/63537265/4702399
score: 0

http://stackoverflow.com/comment/88990574
type: QuestionComment
has text: And use `WebDriverWait` to wait n time
comment on: http://stackoverflow.com/q/50998203
score: 0
type: Comment

http://stackoverflow.com/q/50882356
tagged with: variables
has body: hello I am new to scrapy, I need to load 2 dates on a web. How do I put variables in items? fecha_today = datetime.date.today().strftime("%d-%m-%y") fecha_yesterday = (datetime.date.today()- timedelta(1)).strftime("%d-%m-%y") This is my spider def parse_date(self, response): self.log("\n\n\n ponemos las fechas \n\n\n") hxs = HtmlXPathSelector(response) link_fecha = hxs.select('/html/body/table/tbody/tr[3]/td/a') date_item= ItemLoader ( FechaItem ()) date_item.add_path('fecha_today','/html/body/table[1]/tbody/tr[2]/td/form/table/tbody/tr[3]/td[1]/span/input') date_item.add_path('fecha_yesterday','/html/body/table[1]/tbody/tr[2]/td/form/table/tbody/tr[4]/td[1]/span/input') return date_item.load_item() What do I have to put in item.py so that the variables take me? item.py class FechaLoader(scrapy.loader.ItemLoader): I need to put these variables to then access a table enter image description here
has answer: http://stackoverflow.com/a/73581439
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50886660
tagged with: python
tagged with: scrapy
type: Question
score: 0
answer count: 2
has title: scrapy: load item with variables
tagged with: load

http://stackoverflow.com/a/51041529
score: 0
has body: I thank you very much for the proposed solutions. Unfortunately, neither work (I can not enable anything extra on the Linux box), and they are both outside the desired Python environment. I think it's a kludge, but i'll have to ask for a cat logfile as a text string, and attempt to catch the prompt at the end. Thank you for your time and effort.
type: Answer
answers question: http://stackoverflow.com/q/50960887

http://stackoverflow.com/q/50923192
has comment: http://stackoverflow.com/comment/88845916
has body: I get this error when trying to open chrome with selenium. I have already updated my chrome driver. Any ideas? WebDriverException: Message: unknown error: Devtools port number file contents &lt;50957> were in an unexpected format I do not understand how this is a duplicate, looking at the other forum I see all the solutions to the problem written in a different programming language, and the 1 python solution doesn't work. Also that error is caused when he tries to load a URL, my error is caused when I try to define my browser.
has comment: http://stackoverflow.com/comment/88845731
type: Question
downvote count: 0
linked to: http://stackoverflow.com/q/50642308
has comment: http://stackoverflow.com/comment/89600894
tagged with: python
favorite count: 0
score: 2
answer count: 0
upvote count: 2
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/50642308
tagged with: selenium
has title: Selenium chrome error
has comment: http://stackoverflow.com/comment/88845872
tagged with: screen-scraping

http://stackoverflow.com/comment/88938017
comment on: http://stackoverflow.com/q/50863516
type: Comment
type: QuestionComment
score: 0
has text: please test and verify the provided answer so that this question can be marked as answered instead of forgotten.

http://stackoverflow.com/comment/88858110
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50864225
has text: @stephen, I got it running, thank you.
type: Comment

http://stackoverflow.com/q/50877247
has comment: http://stackoverflow.com/comment/88756483
has answer: http://stackoverflow.com/a/50877508
tagged with: pandas
tagged with: python
tagged with: na
has answer: http://stackoverflow.com/a/50877468
has title: Why doesn't dropna seem to work on this column?
type: UnansweredQuestion
upvote count: 1
type: Question
score: 1
has body: I try to drop all na values in one column Filmname, but the values don't get dropped. Why? (screenshot of my result) Here is my code: import pandas as pd df = read.csv.... df.dropna(subset=['Filmname'], inplace=True) df.head()
answer count: 2
has comment: http://stackoverflow.com/comment/88756653
downvote count: 0
favorite count: 0

http://stackoverflow.com/a/50972779
answers question: http://stackoverflow.com/q/50970937
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88943755
downvote count: 0
has body: In your Oracle query, you're generating multiple random byte strings. Try this to demonstrate: select RAND, RAND, RAND, DBMS_CRYPTO.HASH(RAND, 6 /*SHA512*/) as sha512 from (select DBMS_CRYPTO.RANDOMBYTES(5) as RAND from DUAL); Note the three different values for RAND. So the hash you are generating is actually for a different byte sequence than you think it is. To fix it, you can use this bit of trickery courtesy of AskTom select RAND,DBMS_CRYPTO.HASH(RAND, 6 /*SHA512*/) as sha512 from (select rownum, DBMS_CRYPTO.RANDOMBYTES(5) as RAND from DUAL); including rownum in the subquery makes RAND consistent each time you use it as a field in the top level SELECT. AskTom Question on the subject
type: Answer
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/50970937

http://stackoverflow.com/a/50970861
type: Answer
has comment: http://stackoverflow.com/comment/88972595
has comment: http://stackoverflow.com/comment/88971202
has comment: http://stackoverflow.com/comment/88952430
has comment: http://stackoverflow.com/comment/88972080
has comment: http://stackoverflow.com/comment/88942586
has comment: http://stackoverflow.com/comment/88942195
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/88972564
has comment: http://stackoverflow.com/comment/88954492
has comment: http://stackoverflow.com/comment/88973152
has comment: http://stackoverflow.com/comment/88973163
has comment: http://stackoverflow.com/comment/88972371
has comment: http://stackoverflow.com/comment/88941513
has body: You should modify your discriminator model, either to have two outputs, or to have a "n_classes + 1" output. Warning: I don't see in the definition of your discriminator it outputting 'true/false', I see it outputting an image... Somewhere it should contain a GlobalMaxPooling2D or an GlobalAveragePooling2D. At the end and one or more Dense layers for classification. If telling true/false, the last Dense should have 1 unit. Otherwise n_classes + 1 units. So, the ending of your discriminator should be something like ...GlobalMaxPooling2D()... ...Dense(someHidden,...)... ...Dense(n_classes+1,...)... The discriminator will now output n_classes plus either a "true/fake" sign (you will not be able to use "categorical" there) or even a "fake class" (then you zero the other classes and use categorical) Your generates sketches should be passes to the discriminator along with a target that will be the concatenation of the fake class with the other class. Option 1 - Using the "true/fake" sign. (Don't use "categorical_crossentropy") #true sketches into discriminator: fakeClass = np.zeros((total_samples,)) sketchClass = originalClasses targetClassTrue = np.concatenate([fakeClass,sketchClass], axis=-1) #fake sketches into discriminator: fakeClass = np.ones((total_fake_sketches)) sketchClass = originalClasses targetClassFake = np.concatenate([fakeClass,sketchClass], axis=-1) Option 2 - Using the "fake class" (can use "categorical_crossentropy"): #true sketches into discriminator: fakeClass = np.zeros((total_samples,)) sketchClass = originalClasses targetClassTrue = np.concatenate([fakeClass,sketchClass], axis=-1) #fake sketches into discriminator: fakeClass = np.ones((total_fake_sketches)) sketchClass = np.zeros((total_fake_sketches, n_classes)) targetClassFake = np.concatenate([fakeClass,sketchClass], axis=-1) Now concatenate everything into a single target array (respective to the input sketches) Updated training method For this training method, your loss function should be one …
has comment: http://stackoverflow.com/comment/88942559
downvote count: 0
has comment: http://stackoverflow.com/comment/88970280
has comment: http://stackoverflow.com/comment/88972127
has comment: http://stackoverflow.com/comment/88971741
has comment: http://stackoverflow.com/comment/88970780
has comment: http://stackoverflow.com/comment/88970907
has comment: http://stackoverflow.com/comment/88940713
answers question: http://stackoverflow.com/q/50909007
has comment: http://stackoverflow.com/comment/88970868

http://stackoverflow.com/q/50978109
has title: Pulling data from Sheets API via Python and Django issue
has body: I'm trying to run python manage.py runserver on the local host (using virtualenv) but it kept giving me the message below and I kept hearing that it might be because of the Oauth2 Error? Performing system checks... usage: manage.py [--auth_host_name AUTH_HOST_NAME] [--noauth_local_webserver] [--auth_host_port [AUTH_HOST_PORT [AUTH_HOST_PORT ...]]] [--logging_level {DEBUG,INFO,WARNING,ERROR,CRITICAL}] manage.py: error: unrecognized arguments: runserver I'm adding my the Python code that I'm using (it's some what an example code from Google Sheets API V4) from __future__ import print_function from apiclient.discovery import build from httplib2 import Http from oauth2client import file, client, tools # Setup the Sheets API SCOPES = 'https://www.googleapis.com/auth/spreadsheets.readonly' store = file.Storage('credentials.json') creds = store.get() if not creds or creds.invalid: flow = client.flow_from_clientsecrets('client_secret.json', SCOPES) creds = tools.run_flow(flow, store) service = build('sheets', 'v4', http=creds.authorize(Http())) def get_form_data(): SPREADSHEET_ID = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms' RANGE_NAME = 'Class Data!A2:E' result = service.spreadsheets().values().get(spreadsheetId=SPREADSHEET_ID, range=RANGE_NAME).execute() values = result.get('values', []) data = [] if not values: return data else: for row in values: data.append([]) for each in row: data[len(data)-1].append(each.encode("utf-8")) return data Has anyone ever run into this problem before and solve the issue? Any help is appreciated
has comment: http://stackoverflow.com/comment/88952341
linked to: http://stackoverflow.com/q/34758516
tagged with: django
tagged with: python
upvote count: 3
has comment: http://stackoverflow.com/comment/88980200
has comment: http://stackoverflow.com/comment/107928397
tagged with: google-oauth
tagged with: google-sheets-api
has comment: http://stackoverflow.com/comment/88959036
has comment: http://stackoverflow.com/comment/88952252
answer count: 0
downvote count: 0
type: UnansweredQuestion
score: 3
tagged with: google-api-python-client
favorite count: 0
type: Question

http://stackoverflow.com/q/50936166
tagged with: quickfixj
favorite count: 0
has answer: http://stackoverflow.com/a/50972974
tagged with: quickfix
tagged with: python
has title: Instant logout message received when trying to connect on Quickfix
accepted answer: http://stackoverflow.com/a/50972974
type: AnsweredQuestion
tagged with: quickfixn
score: 0
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88872120
has body: I have been trying to deal with this problem for sometime now and I believe it may have something to do with MsgSeqNum being out of sync between the client and the server but as it had began as a random thing and now makes it impossible to connect I am not so sure anymore. Sometimes after activating the flag to reset MsgSeqNum client-side it will return a message that the server was expecting a higher MsgSeqNum and received "1" (as I had reset mine) but even if I repeatedly try to connect to increase my client-side MsgSeqNum to match the server's I arrive at this same error I show below in my log. In the log messages like "onCreate" are just debugging messages I added to track what methods do end up getting executed. If anyone can offer insight into this issue and anything new to try I'd appreciate it and thank you for reading! Note: I cannot reset the server's MsgSeqNum because you can only send that flag after logging in, which I never get the chance to do. onCreate &lt;20180619-19:51:30.000000000, FIX.4.4:SENDER-&gt;TARGET, event&gt; (Created session) &lt;20180619-19:51:30.000000000, FIX.4.4:SENDER-&gt;TARGET, event&gt; (Connecting to BROKERADDRESS on port 8101 (Source :0)) toAdmin &lt;20180619-19:51:30.000000000, FIX.4.4:SENDER-&gt;TARGET, outgoing&gt; (8=FIX.4.4 9=112 35=A 34=52 49=SENDER 52=20180619-19:51:30.000 56=TARGET 554=PASSWORD 98=0 108=5 10=220 ) &lt;20180619-19:51:30.000000000, FIX.4.4:SENDER-&gt;TARGET, event&gt; (Initiated logon request) &lt;20180619-19:51:31.000000000, FIX.4.4:SENDER-&gt;TARGET, incoming&gt; (8=FIX.4.4 9=77 35=5 34=40 49=TARGET 52=20180619-19:51:31.691 56=SENDER 10=228 ) fromAdmin &lt;20180619-19:51:31.000000000, FIX.4.4:SENDER-&gt;TARGET, event&gt; (Received logout request) toAdmin &lt;20180619-19:51:31.000000000, FIX.4.4:SENDER-&gt;TARGET, outgoing&gt; (8=FIX.4.4 9=77 35=5 34=53 49=SENDER 52=20180619-19:51:31.000 56=TARGET 10=216 ) &lt;20180619-19:51:31.000000000, FIX.4.4:SENDER-&gt;TARGET, event&gt; (Sending logout response) &lt…
has comment: http://stackoverflow.com/comment/88872572
tagged with: python-3.5
has comment: http://stackoverflow.com/comment/88871049
answer count: 1

http://stackoverflow.com/comment/88945306
has text: Updated to add a new possible solution using GraphML
type: AnswerComment
comment on: http://stackoverflow.com/a/50972468
type: Comment
score: 0

http://stackoverflow.com/q/50948180
accepted answer: http://stackoverflow.com/a/50948455
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/55063546
tagged with: gremlinpython
type: Question
has answer: http://stackoverflow.com/a/50948455
answer count: 2
has title: Use python with orientDB and gremlin-server
tagged with: gremlin-server
upvote count: 1
possible better answer: http://stackoverflow.com/a/55063546
has body: I want to deploy orientDB graph using gremlin-server, and connect it with python using gremlin_python library. I downloaded orientDB with gremlin server - zip community edition I am able to deploy orientDB by running bin\server.bat , but there is no gremlin-server.bat (or .sh) available to deploy orientDB with gremlin-server. I had previously downloaded tinkerpop gremlin-server, and tried running that with gremlin-server.yaml file available in orientDB. Some version info : OrientDB : orientdb-tp3-3.0.2 Tinkerpop : apache-tinkerpop-gremlin-server-3.3.1 Gremlin_python : gremlinpython==3.3.2 The versioning may be an issue. But I also want to know how to set this up. Was my good enough, and I just need to correct the versions?
favorite count: 0
tagged with: python
tagged with: orientdb
type: AnsweredQuestion

http://stackoverflow.com/a/50936063
type: Answer
accepted answer of: http://stackoverflow.com/q/50935910
answers question: http://stackoverflow.com/q/50935910
downvote count: 0
has body: To combine the two solutions, just replace Counter(v) from your first solution with the second solution. from collections import Counter d = {'a': [['I', 'said', 'that'], ['said', 'I']], 'b': [['she', 'is'], ['he', 'was']]} counts = {k: Counter(word for sublist in lst for word in sublist) for k, lst in d.items()} print(counts) Output: {'a': Counter({'I': 2, 'said': 2, 'that': 1}), 'b': Counter({'she': 1, 'is': 1, 'he': 1, 'was': 1})}
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/88870823
type: AcceptedAnswer

python-collections
type: Tag
tag name: python-collections
tags question: http://stackoverflow.com/q/50974070

http://stackoverflow.com/q/50868339
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88738832
has title: Identifying x, y coordinates in the same row and are closest to 1000, 2000 respectively
type: Question
has comment: http://stackoverflow.com/comment/88738652
has body: I have a pandas dataframe with x,y columns containing coordinates. These coordinates are ground lidar point cloud coordinates. I would like to find the scan position coordinate of x closest to 1000 and y coordinate closest to 2000 ( original scan position which was set up to X = 1000, Y = 2000 during the scanning). Here is the example data (h - height, i - intensity): x y h i 0 1088.347856 1877.719005 94.869 0.0 1 1083.338856 1886.024105 95.404 2566.0 2 1078.758756 1890.846705 93.314 0.0 3 1078.781556 1890.810205 93.479 257.0 4 1078.791256 1890.804605 93.559 1026.0 5 1078.804756 1890.778805 93.729 1540.0 6 1078.900756 1890.792905 94.324 1283.0 7 1078.900756 1890.792905 94.579 0.0 8 1078.919556 1890.771805 94.749 513.0 9 1078.892856 1890.663205 95.934 770.0 10 1078.841956 1890.731405 95.259 1026.0 I did so far, tried to find closest coordinates: for x_min in df['x']: for y_min in df['y']: x_min = min(df.iloc[:,0], key=lambda x:abs(x-1000)) y_min = min(df.iloc[:,1], key=lambda y:abs(y-2000)) This gave me around 100 X,Y values closest to 1000 and 2000. Now I want to find index values of these numbers. item_index_x = np.where(df.iloc[:,0]==x_min) item_index_y = np.where(df.iloc[:,1]==y_min) Here I tried to find if there are any X,Y coordinates in the same row, not sure if below code is correct. if item_index_x == item_index_y: print(item_index_x) print(item_index_y) Unfortunately, it didn't give any coordinate closest to 1000, 2000 in the same row. But it found coordinates with X closest to 1000 and Y closest to 2000 independently, meaning for example X = 1000.00001 but Y = 1998.0023. I was wondering if there is anyone who can help me.
score: 0
tagged with: pandas
upvote count: 1
tagged with: lidar
answer count: 1
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50868638

http://stackoverflow.com/comment/88798753
type: AnswerComment
has text: Yep. But if you some day find a way how to solve this problem - let me know, I have the same problem in 1 of my projects :)
comment on: http://stackoverflow.com/a/50894284
type: Comment
score: 0

http://stackoverflow.com/q/50955719
tagged with: range
tagged with: python
upvote count: 4
has comment: http://stackoverflow.com/comment/88909157
has body: I'm new to Python and learning about For Loops and wrote this code: cars = [1, 2, 3, 4] trucks = ['red', 'blue', 'green', 'white'] for numbers in cars: print (f"I can count: {numbers}") for colors in trucks: print(f"I can list colors: {colors}") new_list = [] for numbers in range(0, 4): new_list.append(numbers) for numbers in new_list: print(f"I can count more: {new_list}!") and I'm getting this result: I can count: 1 I can count: 2 I can count: 3 I can count: 4 I can list colors: red I can list colors: blue I can list colors: green I can list colors: white I can count more: [0, 1, 2, 3]! I can count more: [0, 1, 2, 3]! I can count more: [0, 1, 2, 3]! I can count more: [0, 1, 2, 3]! For the "I can count more" part, how do I get it to list the range in numeric order: I can count more: 1! I can count more: 2!, etc. instead of printing the entire range in the line?
type: Question
has answer: http://stackoverflow.com/a/50955770
answer count: 2
tagged with: for-loop
has title: For-Loop printing entire range
downvote count: 0
score: 4
has comment: http://stackoverflow.com/comment/88909076
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51036715

http://stackoverflow.com/comment/88951998
comment on: http://stackoverflow.com/q/50977944
type: Comment
type: QuestionComment
score: 0
has text: What do you want `if(sub_arr[i]==Large_arr[j])` to do? Check whether all of the columns are equal? Check whether any of them are equal? Somehow loop over them and do the `if `code for the ones that are equal and the `else` code for the ones that aren't?

http://stackoverflow.com/q/50913151
answer count: 1
tagged with: python
tagged with: python-3.x
tagged with: pyqt5
type: AnsweredQuestion
tagged with: colorbar
tagged with: matplotlib
type: Question
has body: I'm trying to do something pretty straight forward in Matplotlib, but hitting a ton of hurdles; after googling for hours, I'm thinking this takes some very specific magic. I just want my GUI to start on a blank screen and then import a file that needs a colorbar - if the file is good, a colorbar is added. If the file is added again (or a different one), the colorbar is removed and a new one is plotted. If the file is bad, we reset to initial conditions (no colorbars or plot). I really hope the below code makes sense for what I'm getting at here, thank you so much for your help and time in advance: import sys import os import random import matplotlib matplotlib.use('Qt5Agg') from PyQt5 import QtCore, QtWidgets from PyQt5.QtWidgets import QGridLayout, QFileDialog, QPushButton import numpy as np from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.figure import Figure class MyMplCanvas(FigureCanvas): def __init__(self, parent=None, width=5, height=4, dpi=100): MyMplCanvas.fig = Figure(figsize=(width, height), dpi=dpi) self.axes = MyMplCanvas.fig.add_subplot(111) self.compute_initial_figure() FigureCanvas.__init__(self, MyMplCanvas.fig) self.setParent(parent) FigureCanvas.setSizePolicy(self, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) def compute_initial_figure(self): pass class MyDynamicMplCanvas(MyMplCanvas): def __init__(self, *args, **kwargs): MyMplCanvas.__init__(self, *args, **kwargs) def compute_initial_figure(self): C=np.random.rand(500).reshape((20,25)) S=np.random.rand(500).reshape((20,25)) dc = self.function(S,C) im = self.axes.imshow(dc, alpha = 0) MyMplCanvas.fig.patch.set_facecolor('k') self.axes.patch.set_facecolor('k') # don't want to show the cb initially (imagine GUI starts on a blank screen) #cb = MyMplCanvas.fig.colorbar(im, ax=self.axes, #orientation='vertical')#,use_gridspec=True)?? def update_figure(self): # need something like the below to delete s…
accepted answer: http://stackoverflow.com/a/56211475
has title: How to remove Matplotlib colorbar upon subsequent replots?
score: 0
has answer: http://stackoverflow.com/a/56211475

http://stackoverflow.com/comment/88982438
score: 1
type: AnswerComment
has text: Hm ok then i is like an extra discriminator (lets say), both the discriminator and classfiier will provide some erro to the generator. Correct me if I am mistaken?
type: Comment
comment on: http://stackoverflow.com/a/50984159

http://stackoverflow.com/comment/88867259
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50933895
has text: Sorry I'm a bit new to Python so it never occurred to me that my output was indeed a List of Tuples. My problem has been solved though.

http://stackoverflow.com/comment/88990945
score: 0
comment on: http://stackoverflow.com/q/50998417
type: Comment
type: QuestionComment
has text: The line `li = map(lambda x: '"'+x+'"', my_input)` adds quotation marks to your capitalized string. Why are you surprised that the string has the quotation marks? Remove that line. From Python's point of view, `"` and `'` serve the same purpose.

http://stackoverflow.com/a/50894174
upvote count: 1
has comment: http://stackoverflow.com/comment/88793813
has comment: http://stackoverflow.com/comment/88788929
downvote count: 0
score: 1
type: Answer
answers question: http://stackoverflow.com/q/50894152
has body: This should give you an idea of just how useful concat is. a.index = pd.MultiIndex.from_tuples([('One', v) for v in a.index]) b.index = pd.MultiIndex.from_tuples([('Two', v) for v in b.index]) a.append(b) One 0 0 1 1 2 2 Two 0 0 1 1 2 2 3 3 dtype: int64 The same thing is achieved by pd.concat([a, b]).

http://stackoverflow.com/comment/88849533
type: Comment
score: 1
comment on: http://stackoverflow.com/a/50923731
type: AnswerComment
has text: It's a very nice example of using `np.logical_or.reduce()` together with Pandas! +1

teradata
type: Tag
tag name: teradata
tags question: http://stackoverflow.com/q/50887182

http://stackoverflow.com/comment/88812790
comment on: http://stackoverflow.com/q/50906422
score: 1
has text: Can you explain WHY for the key `'1'` the value is `[0,10,1,9]`, how are the coordinates calculated?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50863715
has body: I am trying to load and use a dll in python. I have been trying to use windows-kill but I don't know much at all about C++. I was able to compile it fine in visual studio and the exe file works fine but I'd like to figure out how to load the dll with Python so I can learn how to load other dll's that I may want to use eventually. So far this is the code I have come up with. I wasn't sure if it needed SIGINT or a number for the value because the command line uses -SIGINT but I have been trying both. lib = ctypes.CDLL('windows-kill-library.dll') libOpen = getattr(lib, "?sendSignal@WindowsKillLibrary@@YAXKK@Z") libOpen.argtypes = [wintypes.DWORD, wintypes.DWORD] val = 'SIGINT' # val = 0 l = libOpen(9844, val) print(l) Using SIGINT as the val I get the error: ctypes.ArgumentError: argument 2: <class 'TypeError'>: wrong type and using a number as a value I get: OSError: [WinError -529697949] Windows Error 0xe06d7363 I know the argtypes must be wrong or something but I have been trying lots of different things and getting the same errors. This is the undecorated name: void WindowsKillLibrary::sendSignal(unsigned long,unsigned long) I have tried using ctypes.c_ulong and some others for the argtypes but still get the same errors. In visual studio when I hover over DWORD in the 2 lines below: DWORD signal_type; DWORD signal_pid; It says "typedef unsigned long DWORD" if that helps. Here is also the usage example that can be found here /// /// Sends the signal. /// /// The signal target process id. /// The signal type. void sendSignal(DWORD signal_pid, DWORD signal_type); Does anyone know how I can make this work? Thanks.
answer count: 1
type: UnansweredQuestion
tagged with: windows
tagged with: python
tagged with: c++
type: Question
has title: Trying to load and use a dll file in python properly
tagged with: ctypes
has answer: http://stackoverflow.com/a/50864861
score: 0

http://stackoverflow.com/comment/88749385
type: Comment
type: QuestionComment
has text: I think you can build on this answer https://stackoverflow.com/a/27865750/187292
score: 1
comment on: http://stackoverflow.com/q/50873446

http://stackoverflow.com/comment/88734914
has text: You need to either (a) write a server program that listens for commands over some protocol you come up with then executes them and returns the results, or (b) use some existing server like and talk its protocol.
comment on: http://stackoverflow.com/q/50866238
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/88810453
has text: @irfanyounus (1) don't put `-` in a variable name, as in `Old-ip`, because that's the subtraction operator (2) `data1` is a list and doesn't have a replace method, use the string, i.e. `data12 = data.replace(...)`.
comment on: http://stackoverflow.com/a/50900549
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/50865014
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50864868
has body: What you are trying to do is a perfect application for a new Player class: class Player: def __init__(self, name): self.name = name self.score = 0 def __repr__(self, name): return self.name Then, instead of players_list.append(players), you would do players_list.append(Player(players)) (also IMHO you should use something like name instead of players just so it's more clear what that actually is). Then, all the players in your list will have an associated score that you can access like players_list[0].score. Hope this helps, good luck learning.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88732686
has comment: http://stackoverflow.com/comment/88734147
has comment: http://stackoverflow.com/comment/88732752
answers question: http://stackoverflow.com/q/50864868
has comment: http://stackoverflow.com/comment/88733460
has comment: http://stackoverflow.com/comment/88733911
has comment: http://stackoverflow.com/comment/88733752
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/88733175
downvote count: 0
has comment: http://stackoverflow.com/comment/88732919
has comment: http://stackoverflow.com/comment/88734118
has comment: http://stackoverflow.com/comment/88733903
has comment: http://stackoverflow.com/comment/88733961
has comment: http://stackoverflow.com/comment/88733814
has comment: http://stackoverflow.com/comment/88733648

http://stackoverflow.com/q/51002511
tagged with: pandas
has answer: http://stackoverflow.com/a/51277727
has answer: http://stackoverflow.com/a/51002808
tagged with: unix
has body: I have multiple *.txt heavy files (~ 200 GB each) and I am trying to count the values in a certain column ('val'). I used python pandas for this casebut i am happy to use unix or any faster method. file = pd.read_csv('example1.txt', sep = '\t') print(file['val'].value_counts()) However, I got a message 'Killed' or that the memory limit has been used. Any suggestion to do my job when using heavy files?
type: Question
has title: value_counts() in heavy/large data files python/pandas/unix
tagged with: python
tagged with: large-data
has comment: http://stackoverflow.com/comment/88998972
tagged with: large-files
score: 0
linked to: http://stackoverflow.com/q/25428661
has comment: http://stackoverflow.com/comment/88999039
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88998883
answer count: 2

http://stackoverflow.com/comment/88807675
score: 0
has text: I have never seen the view mode in kanban before, it must be tree or form
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50882645

http://stackoverflow.com/comment/88717848
score: 1
has text: Have tried anything yet ?
comment on: http://stackoverflow.com/q/50857684
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88765502
type: QuestionComment
has text: How about finding the bounding box and then masking masking outside of your boundary? Or fill it with nan for plotting.
comment on: http://stackoverflow.com/q/50881585
score: 0
type: Comment

http://stackoverflow.com/a/50949990
answers question: http://stackoverflow.com/q/50949854
type: Answer
has comment: http://stackoverflow.com/comment/88899781
accepted answer of: http://stackoverflow.com/q/50949854
has comment: http://stackoverflow.com/comment/88897876
has comment: http://stackoverflow.com/comment/88897807
upvote count: 2
has comment: http://stackoverflow.com/comment/88897840
has body: Python knows how to handle encoding inside your program because it uses whatever encoding your terminal application is using. When you are sending (piping) your output out, it needs to be encoded. This is because using pipe actually sends streams of bytes between the applications. Every pipe is a unidirectional channel, where one side writes data and the other side reads it. Using pipes or redirections, you are sending out data to a fd, which is read by the another application. So you need to make sure Python correctly encode the data before it sends it out, and then the input program needs to decode it before processing. You also might find this question useful Update: I'll try to elaborate more about encoding. What I mean by the first line of my answer is, because your Python interpreter uses specific encoding, it knows how to transform the hexa values (actual bytes) to symbols. My interpreter doesn't; if I try to create a string from your text - I get an error: &gt;&gt;&gt; s = 'bibliothèque' Unsupported characters in input This is because I use different encoding on my interpreter. Your shell uses different encoding than the Python interpreter. When Python sends data out of your program, it uses default encoding: ASCII. It can't translate your special character (which displayed by the hexa value \xe8) using ASCII. So, you have to specify which encoding to use in order for Python to send it. You might be able to overcome this if you change your shell encoding - check this question on SO. PS - There's a great video by Ned Batchelder about Unicode on youtube - Maybe this will shed some more light on the subject.
score: 2
has comment: http://stackoverflow.com/comment/88898231
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/88804420
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50902252
has text: The values in each column are tuples? If you simply create a new column with the flattened concatenated string of column A, just run through the rows using `df.iterrows()` and have a few boolean flags for `seen_opentag` and `seen_closetag` and break by index (returned by `iterrows()`).

http://stackoverflow.com/a/51007779
has comment: http://stackoverflow.com/comment/98523868
has comment: http://stackoverflow.com/comment/98482357
has body: Try the below way. It should fetch you the required response along with the tabular data available in that site generated according to the search criteria. import requests from bs4 import BeautifulSoup URL = "http://www.hkexnews.hk/sdw/search/searchsdw.aspx" with requests.Session() as s: s.headers={"User-Agent":"Mozilla/5.0"} res = s.get(URL) soup = BeautifulSoup(res.text,"lxml") payload = {item['name']:item.get('value','') for item in soup.select("input[name]")} payload['__EVENTTARGET'] = 'btnSearch' payload['txtStockCode'] = '00001' payload['txtParticipantID'] = 'A00001' req = s.post(URL,data=payload,headers={"User-Agent":"Mozilla/5.0"}) soup_obj = BeautifulSoup(req.text,"lxml") for items in soup_obj.select("#pnlResultSummary .ccass-search-datarow"): data = [item.get_text(strip=True) for item in items.select("div")] print(data)
has comment: http://stackoverflow.com/comment/98466644
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51007603
score: 3
type: Answer
answers question: http://stackoverflow.com/q/51007603
has comment: http://stackoverflow.com/comment/98523653
has comment: http://stackoverflow.com/comment/98464219
upvote count: 3
has comment: http://stackoverflow.com/comment/89008865

http://stackoverflow.com/q/50957641
upvote count: 2
tagged with: python
score: 2
type: AnsweredQuestion
has body: I have 98,000 USA home street addresses that I need to sort in 'walking' order, i.e. listed in the order that you would walk, down one side of the street and then cross the street and walk back. import pandas as pd df = pd.read_excel('c:pdsort.xlsx') # add boolean column for even or odd on number column is_even = df.loc[:,'number'] % 2 == 0 df.loc[:, 'even'] = is_even # group and then sort by number df.groupby(['town','street','even']).apply(lambda x: x.sort_values('number')) # sort odd numbers ascending and even numbers descending Desired df results, sort ascending for odd street numbers, then switch to descending sort for even. [sorry, first stackoverflow question, don't qualify yet to copy image of Jupyter notebook] 4 columns: number,street,town,even desired outcome for column 'number': 1231 1233 1235 1237 1239 1238 1236 1234 1232 1230
possible better answer: http://stackoverflow.com/a/50957916
has answer: http://stackoverflow.com/a/50957916
type: Question
has answer: http://stackoverflow.com/a/50958025
tagged with: sorting
has title: Conditionally sort a single column in ascending and descending order in Pandas
accepted answer: http://stackoverflow.com/a/50958025
has comment: http://stackoverflow.com/comment/88912692
answer count: 2
tagged with: pandas-groupby
tagged with: pandas
downvote count: 0
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/q/50876768
accepted answer: http://stackoverflow.com/a/50876860
type: Question
answer count: 2
tagged with: for-loop
downvote count: 0
favorite count: 0
has title: Finding sum of values generated from a for loop in Python
tagged with: python
possible better answer: http://stackoverflow.com/a/50876934
has answer: http://stackoverflow.com/a/50876934
upvote count: 2
has answer: http://stackoverflow.com/a/50876860
score: 2
type: AnsweredQuestion
has body: Hi totally new and struggling with a likely simple prob. I have a for-loop creating values and printing the running total as they're generated. I need to find a way to print the sum of those running totals (in the case below: 3 + 33 + 333) I have a feeling a nested loop is an option but not sure where it'd go. Am I close? (Thanks) Here is my code thus far: def nSum(num): #calculating values for the variable (num) to the p power: p = 0 newValue = 0 for i in range(num): currentVal = num * 10**p p = p+1 #running total of the curent values: newValue = currentVal + newValue print(newValue) return newValue print(nSum(3)) #Want nSum to be total of all the newValues from the loop

http://stackoverflow.com/comment/88798006
type: AnswerComment
type: Comment
has text: Maybe try using "username": `def clean_username(self): return self.cleaned_data["username"].lower()`
score: 1
comment on: http://stackoverflow.com/a/50898764

http://stackoverflow.com/q/50938486
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/88875237
has comment: http://stackoverflow.com/comment/88875282
type: UnansweredQuestion
has body: I have imported pefile and using it to fetch entries from the StringTable attribute. I get the below error: 'ascii' codec can't decode byte 0xc2 in position 9: ordinal not in range(128) Traceback (most recent call last): File "peinfo.py", line 74, in getPeInfo ans.append("Product Name : {}".format(convert_to_printable(st_entry.entries.get('ProductName', 'none')))) UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 9: ordinal not in range(128) A gist of my changes are : def getPeInfo(filename): ans = [] try: pe = pefile.PE(filename, fast_load=True) except: return "PE header not found." pe.parse_data_directories( directories=[ pefile.DIRECTORY_ENTRY['IMAGE_DIRECTORY_ENTRY_IMPORT'], pefile.DIRECTORY_ENTRY['IMAGE_DIRECTORY_ENTRY_RESOURCE'], ]) ans.append("\n File Info") if hasattr(pe, 'FileInfo'): if type(pe.FileInfo) == type([]): entry = pe.FileInfo[0] if hasattr(entry, 'StringTable'): st_entry = entry.StringTable[0] ans.append("Product Name : {}".format(convert_to_printable(st_entry.entries.get('ProductName', 'none'))))
tagged with: python
answer count: 0
has title: Using pefile returns unicodeDecodeError
type: Question

http://stackoverflow.com/q/50993064
answer count: 0
has comment: http://stackoverflow.com/comment/88980974
type: UnansweredQuestion
tagged with: output
type: Question
has comment: http://stackoverflow.com/comment/88983804
score: 0
has body: Currently I can use pandas to create columns and export lists as columns. Ex: newRatiosDF = pd.DataFrame(newRatios) entityidC = pd.DataFrame(X['entity_id']) final = pd.concat([entityidC['entity_id'],newRatiosDF]) newRatiosDF.to_csv('../venv/output/letsseeit.csv') Output Looks Like: entity_id Ratios 0 3000 5 1 3001 7 ... 500 3099 2 However this is not how I want to output my code. I would much rather have the index's be the entity_ids, so I have index's in a column and a row and then those index's reference the ratios in each box. Ex of what I am looking for: 3000 3001 ... 3099 3000 nan 7 12 3001 4 nan 6 ... 3099 2 8 nan The reason I have nans is because I do not want to find the ratio of the something between the same thing. If anyone has any examples of how to code this using pandas (or a different library) it would be much appreciated. My ratios are in a 2D array already so all I need to do is figure out how to make the indices the entity_ids and then put the ratios in their correct places. You can assume that the entity_id's are already in order and they match with their corresponding ratio values. All I'm looking for is the "How To" on manipulating pandas (or a different library) to do this. If you have questions about my code please let me know and I'll do my best to answer them quickly, your help is much appreciated. EDIT 1 I build the array doing this: newRatios = np.zeros((xdfSize,xdfSize)) for ep in XDF['EmailPrefix']: for ep2 in XDF['EmailPrefix']: if rows &lt;= xdfSize: if columns != rows: newRatios[columns,rows] = fuzz.token_sort_ratio(ep,ep2) else: newRatios[columns,rows] = None rows += 1 rows = 0 columns += 1 Then the print out looks like this: [[0. 1. 1. ... 1. 1. 1.] [1. 0. 1. ... 1. 1. 1.] [1. 1. 0. ... 1. 1. 1.] ... [1. 1. 1. ... 0. 1. 1.] [1. 1. 1. ... 1. 0. 1.] [1. 1. 1. ... 1. 1. 0.]]
has comment: http://stackoverflow.com/comment/88980908
has comment: http://stackoverflow.com/comment/88981949
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has title: Export to 2D list to CSV with specific Indices, Pandas
has comment: http://stackoverflow.com/comment/88981947
tagged with: list

http://stackoverflow.com/comment/88779175
type: AnswerComment
type: Comment
has text: setattr & getattr are exactly what I was looking for. Thanks so much Charles. I am now able to run this loop as a single block of code. Thanks also for all of your other comments & suggestions - I am looking at and working through them all in an iterative manner to build my Python knowledge - very helpful.
comment on: http://stackoverflow.com/a/50869071
score: 0

http://stackoverflow.com/comment/118447955
has text: @XueQing check for the installation path of Tesseract-OCR in your system. Replace this path with Windows path mentioned in the answer, it should work.
type: Comment
comment on: http://stackoverflow.com/a/53672281
score: 1
type: AnswerComment

http://stackoverflow.com/q/50951227
type: AnsweredQuestion
has title: Calling another language with MQL5
has body: I would like to scan an economic calendar (and in a second step possibly a news source) like this one for use in MetaTrader/MQL5. I guess I would need another programming language than MQL5 for that, possibly (but not necessarily) C#? (How) can it be done in principle? Thank you very much in advance!
type: Question
tagged with: c#
answer count: 1
tagged with: http://stackoverflow.com/tag/r
score: 0
tagged with: python
has answer: http://stackoverflow.com/a/50953970
tagged with: php
accepted answer: http://stackoverflow.com/a/50953970
tagged with: mql5

http://stackoverflow.com/a/51008226
type: Answer
has body: A simple way is to create two new Series indexed by the teams: home = pd.Series(data.HomePoint.values, data.Home) away = pd.Series(data.AwayPoint.values, data.Away) Then, the result you want is: home.add(away, fill_value=0).astype(int) Note that home + away does not work, because team F never played away, so would result in NaN for them. So we use Series.add() with fill_value=0. A complicated way is to use DataFrame.melt(): goo = data.melt(['HomePoint', 'AwayPoint'], var_name='At', value_name='Team') goo.HomePoint.where(goo.At == 'Home', goo.AwayPoint).groupby(goo.Team).sum() Or from the other perspective: ooze = data.melt(['Home', 'Away']) ooze.value.groupby(ooze.Home.where(ooze.variable == 'HomePoint', ooze.Away)).sum()
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/89061643
accepted answer of: http://stackoverflow.com/q/51002693
answers question: http://stackoverflow.com/q/51002693
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/89020712
type: Comment
score: 1
has text: We are very keen here for the code you wish to show readers to be in the question itself. Partly this is because we don't want readers to have to go fetch it when it could be shown on the same page, but mainly this is because we find external links are often deleted, and when that happens we generally have the administrative work of deleting the question (since the question is no longer understandable). Of course, this will take any good answers with it, and we'd rather not do that. With that in mind, would you edit your question?
comment on: http://stackoverflow.com/q/51010481
type: QuestionComment

http://stackoverflow.com/q/50971367
has body: I have three 4-dimensional arrays need to be binned to create a multi-dimensional histogram. In the example below, I have used numpy, but the actual arrays are being read in from a NetCDF file using xarray. I know that xarray uses dask in the backend, and I have tried creating a small dask cluster on the machine I am using, which has 20 cores, but I don't get any speedup in the for loops, but I do get the speedup in the digitize step. I am hoping someone can help me parallelize the for loop based on dask. import numpy as np # Initial datasets s = np.random.rand(5,2,3,4) ws = np.random.rand(5,2,3,4) wd = np.random.rand(5, 2, 3, 4) # Digitize to different bins s_map = np.digitize(s, [0, .5, 1]) ws_map = np.digitize(ws, [0, .25, .5, .75, 1]) wd_map = np.digitize(wd, [.25, .5, 1]) # Get indexes that have values s_ids = np.unique(s_map) ws_ids = np.unique(ws_map) wd_ids = np.unique(wd_map) # Create output array count = np.zeros((s_ids.size, ws_ids.size, wd_ids.size) + s.shape[1:]) # Loop over each of the maps to count how many values fall into each bin for i, s_id in enumerate(s_ids): s_mask = s_map == s_id for j, ws_id in enumerate(ws_ids): ws_mask = s_mask &amp; (ws_map == ws_id) for k, wd_id in enumerate(wd_ids): mask = ws_mask &amp; (wd_map == wd_id) count[i, j, k, ...] += np.count_nonzero(mask, axis=0)
type: Question
has comment: http://stackoverflow.com/comment/89040381
has comment: http://stackoverflow.com/comment/88941336
tagged with: numpy
score: 0
has comment: http://stackoverflow.com/comment/88943154
tagged with: dask
type: UnansweredQuestion
has title: Parallelize For loops in Numpy and Dask for creating a multi-dimensional histogram
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/89065250

http://stackoverflow.com/q/50901144
type: UnansweredQuestion
tagged with: socket.io
has body: I'm trying to learn how to use WebSocket with a python backend and an Angular 6 front end. It looks like the WebSocket connection gets destroy as the updates does only work when I put a breakpoint on the following line: ngOnInit() { this.sub = this.socketService.getQuotes() .subscribe(quote =&gt; { console.log('got price: ' + quote); this.price = quote; }); } // breakpoint The backend is pretty simple: def send_market_price(): threading.Timer(5.0, send_market_price).start() print('sending price ws') socketio.emit('market', market.update_market()) if __name__ == '__main__': send_market_price() print('starting') socketio.run(app) the service is basic too: @Injectable() export class SocketService { public socket; public observer: Observer&lt;number&gt;; getQuotes(): Observable&lt;number&gt; { this.socket = socketio(SERVER_URL); this.socket.on('market', (res) =&gt; { this.observer.next(res); }); return this.createObservable(); } createObservable(): Observable&lt;number&gt; { return new Observable(observer =&gt; { this.observer = observer; }); } Is there anything wrong in my code to do this basic feature? EDIT after some tests, it looks like that the backend is bugged. I did the same thing getting a Node.js code and it works great. What is wrong with this python code: import threading from flask import Flask, jsonify from flask_cors import CORS from flask_socketio import SocketIO from market_engine import market from market_engine.market import RandomMarket app = Flask(__name__) app.config['SECRET_KEY'] = 'secret!' socketio = SocketIO(app) CORS(app) market = RandomMarket() @socketio.on('connect') def connect(): print('Client connected') @socketio.on('disconnect') def disconnect(): print('Client disconnected') def send_market_price(): threading.Timer(5.0, send_market_price).start() print('sending price ws') socketio.emit('market', market.update_market()) if __name__ == '__main__': send_market_price() print('starting') socketio.run(app)
has title: WebSocket with angular 6 gets destroyed
has comment: http://stackoverflow.com/comment/88822067
tagged with: flask-socketio
has comment: http://stackoverflow.com/comment/88803481
type: Question
score: 0
has comment: http://stackoverflow.com/comment/88803349
tagged with: websocket
tagged with: angular
tagged with: python
answer count: 0

pypandoc
tags question: http://stackoverflow.com/q/50932821
tag name: pypandoc
type: Tag

http://stackoverflow.com/comment/88840675
comment on: http://stackoverflow.com/a/50920463
type: AnswerComment
type: Comment
has text: No thank you. StackOverflow is a Q&A website. It is not a site where you should ask other people to write code for you. You are welcome, however, to try to code it yourself and post questions regarding any problems you experience.
score: 3

http://stackoverflow.com/a/50920917
score: 1
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/50920598
type: Answer
has body: you have two option for that 1) many to one, 2) many to many 1) many to one is ForeignKey to add in category model and link each category with business, in this you can identify which category is child of buisness, you can find more details in django document class Category(models.Model): name = models.CharField(max_length=100) slug = models.CharField(max_length=100) business = models.ForeignKey(Business, on_delete=models.CASCADE) 2) many to many is select multiple category in business, and you can access all thing in business model and in you write query on business model and access to also category for that you need write category before buisness, you can find more detail in django document class Business(models.Model): user = models.ForeignKey('User', on_delete=models.CASCADE) business_name = models.CharField(max_length=100) category = models.IntegerField() keyword = models.CharField(max_length=100) category= models.ManyToManyField(Category)

http://stackoverflow.com/comment/88781189
type: Comment
comment on: http://stackoverflow.com/a/50889747
score: 0
type: AnswerComment
has text: Sorry for the previous comment, I still had my old result072.csv I have tried to run this, but the result072.csv seems to be empty even though,when manually checked there should be some matches. What can it be? Thank you so much for the help, it is for my thesis! :)

http://stackoverflow.com/q/50879786
accepted answer: http://stackoverflow.com/a/50879806
has body: I have a string which contains several pairs of 2D co-ordinate points as follows: input = '(1, 2), (3, 5.5), (7, -2), (16, 0), (5, 3)' I want to take this string and end up with two lists, named X and Y which contain the X and Y co-ordinates respectively of the points in the string (in their original order): outputs: X = ['1', '3', '7', '16', '5'] Y = ['2', '5.5', '-2', '0', '3'] How can I do this using Python 3?
has comment: http://stackoverflow.com/comment/88761643
downvote count: 0
answer count: 1
tagged with: string
favorite count: 0
score: 3
tagged with: python
type: AnsweredQuestion
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50879806
tagged with: list
upvote count: 3
has comment: http://stackoverflow.com/comment/88761734
type: Question
has title: Python - Convert list of 2D co-ordinate pairs to 2 lists of X and Y components
tagged with: coordinates

http://stackoverflow.com/comment/88869953
type: Comment
has text: You could also put the dict into the class
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50935518

win32gui
type: Tag
tag name: win32gui
tags question: http://stackoverflow.com/q/50956383
tags question: http://stackoverflow.com/q/51005957

http://stackoverflow.com/a/52783759
type: Answer
answers question: http://stackoverflow.com/q/50872445
has body: You need to type python -m SimpleHTTPServer at your command prompt, not inside the python interpreter. That is a python error message and the line above is a command line for your OS.
score: 0

http://stackoverflow.com/a/51001853
answers question: http://stackoverflow.com/q/51001660
downvote count: 0
type: Answer
score: 1
upvote count: 1
has body: If I'm understanding correctly, you want the difference for each set and the union of the rest of the sets. I would use a loop and functools.reduce and operator.or_: Setup import functools import operator a = set([1, 2, 3, 4, 5]) b = set([4, 5, 6, 7, 7, 9]) c = set([1, 2, 6, 8, 10, 12, 45]) d = set([11, 3, 23, 3, 4, 44]) set_list = [a, b, c, d] Loop and save results # I don't know what you want to do with the results so # I'll save them in a list... results = [] for i in set_list: list_copy = list(set_list) list_copy.remove(i) r = i - functools.reduce(operator.or_, list_copy) results.append(r) print(results) # prints [set(), {9, 7}, {8, 10, 12, 45}, {11, 44, 23}]

http://stackoverflow.com/comment/88920846
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50960783
type: Comment
has text: @CodyChung You are welcome. I kind of also like my `numpy` solution... I wasn't expecting it to be this simple.

http://stackoverflow.com/q/50945387
downvote count: 3
has comment: http://stackoverflow.com/comment/88888673
has comment: http://stackoverflow.com/comment/88890688
answer count: 1
tagged with: user-interface
has answer: http://stackoverflow.com/a/50946011
favorite count: 0
score: -3
tagged with: python
has body: I am getting the error as 'r1' object has no attribute 'Frame_Display'. class gui: def __init__(self,master): Frame_Menu = LabelFrame(root, bd=1,text='Menu', labelanchor=N, height=550, width=200, relief=SUNKEN) Frame_Menu.grid(row=0, column=0) Frame_Display = LabelFrame(root, bd=1, text='System Layout', labelanchor=N, height=550, width=750, relief=SUNKEN) Frame_Display.grid(row=0, column=1, columnspan=3, rowspan=1, sticky=W+E+N+S) class r1(gui): def __init__(self, level=None, *args, **kwargs): super(gui, self).__init__(*args, **kwargs) vf1r1_button=tk.Button(self.Frame_Display,text="VF1R1",bg="red",state=DISABLED).grid(row=8,column=2,pady=(1,0)) vf2r1_button=tk.Button(self.Frame_Display,text="VF2R1",bg="red",state=DISABLED).grid(row=10,column=2) r1_Button=tk.Button(self.Frame_Display,text="Reactor 1",bg="red").grid(row=9,column=4,padx=(30,0)) root=tk.Toplevel() root.title("GUI Using classes") a = r1() root.mainloop() ****edit 1 - traceback error added below**** runfile('C:/Users/rohit/Desktop/GUI-Classes.py', wdir='C:/Users/rohit/Desktop') Traceback (most recent call last): File "&lt;ipython-input-20-4b3be26cf4d4&gt;", line 1, in &lt;module&gt; runfile('C:/Users/rohit/Desktop/GUI-Classes.py', wdir='C:/Users/rohit/Desktop') File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 705, in runfile execfile(filename, namespace) File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "C:/Users/rohit/Desktop/GUI-Classes.py", line 62, in &lt;module&gt; a = r1() File "C:/Users/rohit/Desktop/GUI-Classes.py", line 50, in __init__ vf1r1_button=tk.Button(self.Frame_Display,text="VF1R1",bg="red",state=DISABLED).grid(row=8,column=2,pady=(1,0)) AttributeError: 'r1' object has no attribute 'Frame_Display' I want to place the buttons in r1 on the main gui and in frame_display
has comment: http://stackoverflow.com/comment/88888711
type: AnsweredQuestion
upvote count: 0
tagged with: tkinter
has comment: http://stackoverflow.com/comment/88888522
has comment: http://stackoverflow.com/comment/88888277
type: Question
accepted answer: http://stackoverflow.com/a/50946011
has title: object has no attribute error in gui

http://stackoverflow.com/q/50899707
favorite count: 0
type: Question
tagged with: python
has body: Below is the last part of my selenium web scraper that loops through the different tabs of this website page, selects the "export data" button, downloads the data, adds a "yearid" column, then loads the data into a MySQL table. df = pd.read_csv(desired_filepath) df = df.replace('%','',regex=True) df["yearid"] = datetime.today().year df.to_csv(desired_filepath) engine = create_engine("mysql+pymysql://{user}:{pw}@localhost/{db}" .format(user="walker", pw="password", db="data")) df.to_sql(con=engine, name='fg_test_hitting_{}'.format(button_text), if_exists='replace') time.sleep(10) driver.quit() The scraper works great, however when the data gets loaded into the MySQL table, there are certain columns that get loaded as TEXT when they should be loaded as numeric, preferably a DOUBLE data type. I noticed this only occurs in the column names that have a % sign at the end of the string (i.e. BB%). I have eliminated the % sign in all rows underneath the column headers, but the data is still loading into MYSQL as TEXT. Is there any way to change the data type for all columns that have a % sign in the column name before the data gets loaded into MySQL? Thanks in advance!
answer count: 1
has comment: http://stackoverflow.com/comment/88799253
has answer: http://stackoverflow.com/a/50900488
tagged with: selenium
tagged with: mysql
upvote count: 1
tagged with: sqlalchemy
downvote count: 0
has title: Changing Data Types in Pandas Data Frame
has comment: http://stackoverflow.com/comment/88799564
accepted answer: http://stackoverflow.com/a/50900488
tagged with: pandas
type: AnsweredQuestion
score: 1

http://stackoverflow.com/comment/88879317
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50939765
type: Comment
has text: @PeterJames123, you're redefining the question. this is beyond the scope of what you initially asked

tkinter
tags question: http://stackoverflow.com/q/51008690
tags question: http://stackoverflow.com/q/50934201
tags question: http://stackoverflow.com/q/50977756
tags question: http://stackoverflow.com/q/50991338
tags question: http://stackoverflow.com/q/50883019
tags question: http://stackoverflow.com/q/50893792
tags question: http://stackoverflow.com/q/50910659
tags question: http://stackoverflow.com/q/50951872
tags question: http://stackoverflow.com/q/50989759
tags question: http://stackoverflow.com/q/50923769
tags question: http://stackoverflow.com/q/50957742
tags question: http://stackoverflow.com/q/50958972
tags question: http://stackoverflow.com/q/50958876
tags question: http://stackoverflow.com/q/50899891
tags question: http://stackoverflow.com/q/51007361
tags question: http://stackoverflow.com/q/50988340
tags question: http://stackoverflow.com/q/50995790
tags question: http://stackoverflow.com/q/50973015
tags question: http://stackoverflow.com/q/50947340
tags question: http://stackoverflow.com/q/50936978
tags question: http://stackoverflow.com/q/51011167
tags question: http://stackoverflow.com/q/50918557
tags question: http://stackoverflow.com/q/50988574
tags question: http://stackoverflow.com/q/50906725
tags question: http://stackoverflow.com/q/50905398
tags question: http://stackoverflow.com/q/50970511
tag name: tkinter
tags question: http://stackoverflow.com/q/50865221
tags question: http://stackoverflow.com/q/50858952
tags question: http://stackoverflow.com/q/50942111
tags question: http://stackoverflow.com/q/50919221
tags question: http://stackoverflow.com/q/50964709
tags question: http://stackoverflow.com/q/50944376
tags question: http://stackoverflow.com/q/50886900
tags question: http://stackoverflow.com/q/50970795
tags question: http://stackoverflow.com/q/50933839
tags question: http://stackoverflow.com/q/50938277
tags question: http://stackoverflow.com/q/50926580
tags question: http://stackoverflow.com/q/50958112
tags question: http://stackoverflow.com/q/50893789
tags question: http://stackoverflow.com/q/50938207
tags question: http://stackoverflow.com/q/50916382
tags question: http://stackoverflow.com/q/50966342
tags question: http://stackoverflow.com/q/50910764
tags question: http://stackoverflow.com/q/50856226
tags question: http://stackoverflow.com/q/51010130
tags question: http://stackoverflow.com/q/50864772
tags question: http://stackoverflow.com/q/50960522
tags question: http://stackoverflow.com/q/50945387
tags question: http://stackoverflow.com/q/50969928
tags question: http://stackoverflow.com/q/50922175
tags question: http://stackoverflow.com/q/51003420
tags question: http://stackoverflow.com/q/50868751
tags question: http://stackoverflow.com/q/50880259
tags question: http://stackoverflow.com/q/51002858
tags question: http://stackoverflow.com/q/50940128
tags question: http://stackoverflow.com/q/50886101
tags question: http://stackoverflow.com/q/50979965
tags question: http://stackoverflow.com/q/50999353
tags question: http://stackoverflow.com/q/50952721
tags question: http://stackoverflow.com/q/50972668
tags question: http://stackoverflow.com/q/51009903
tags question: http://stackoverflow.com/q/50909641
tags question: http://stackoverflow.com/q/50911036
tags question: http://stackoverflow.com/q/50955987
tags question: http://stackoverflow.com/q/50948727
tags question: http://stackoverflow.com/q/50906964
tags question: http://stackoverflow.com/q/50919285
tags question: http://stackoverflow.com/q/50944627
tags question: http://stackoverflow.com/q/50956383
tags question: http://stackoverflow.com/q/50910558
tags question: http://stackoverflow.com/q/50973137
tags question: http://stackoverflow.com/q/50860640
tags question: http://stackoverflow.com/q/50979467
tags question: http://stackoverflow.com/q/50902318
tags question: http://stackoverflow.com/q/50873455
tags question: http://stackoverflow.com/q/51003567
tags question: http://stackoverflow.com/q/50926565
tags question: http://stackoverflow.com/q/50913071
tags question: http://stackoverflow.com/q/50911128

http://stackoverflow.com/a/51167398
has comment: http://stackoverflow.com/comment/89329539
has comment: http://stackoverflow.com/comment/89330324
has comment: http://stackoverflow.com/comment/89328711
upvote count: 1
has body: The last : is causing the issue. Replace it with . prior to the convert. Assuming your time column is df.time, df['ns'] = df.time.apply(lambda x: x[-3:]) #make up ns column df.time = df.time.apply(lambda x: str(x)[:-4] + ".") # cut off ns and replace ":" with "." df.time = df.time + df.ns # combine above 2 df.drop('ns', axis=1, inplace=True) # we no longer need "ns" column df.time = pd.to_datetime(df.time, unit='ns') # Now you can convert time to "ns"
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50980606
answers question: http://stackoverflow.com/q/50980606
type: Answer
has comment: http://stackoverflow.com/comment/89329781
downvote count: 0
has comment: http://stackoverflow.com/comment/89329508
score: 1

http://stackoverflow.com/q/50934222
answer count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/88868458
type: Question
has body: I am fairly new to python. My problem is I have a SqlAlchemy model class say Message which has 150 properties like so: class Message(database.Model): id = database.Column(database.Integer, primary_key=True) username = database.Column(database.String(80), unique=True) email = database.Column(database.String(120), unique=True) def getId(self): return self.id; def getUserName(self): return self.username; def getEmail(self): return self.email; class DataTesting(object): def datatest(self): kwargs = json.loads(self.getData()) instance = Message(**kwargs) print(instance.getUserName()) def getData(self): return """ { "id": 1, "username": "user1", "email": "email1" } """ I am calling datatest() from another class. I received the JSON from the source which has all the keys which are defined in Message class. My requirement is to map JSON to Message class object and then save this object in db. I don't want to wite from_json() because the number of properties are too high and don't want to use constructor because of the same reason. I need something which can transform my json to Message class. Please point me in the right direction.
has comment: http://stackoverflow.com/comment/88868045
has comment: http://stackoverflow.com/comment/88868875
downvote count: 0
tagged with: flask-sqlalchemy
favorite count: 0
has comment: http://stackoverflow.com/comment/88867835
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88869711
tagged with: python
has comment: http://stackoverflow.com/comment/88868650
has title: Flask SqlAlchemy map json to model class

http://stackoverflow.com/comment/88958800
type: AnswerComment
comment on: http://stackoverflow.com/a/50981572
type: Comment
score: 1
has text: A `print` after an `if` that `break`s works only if `if` condition is not satisfied. So there is no need of `else:` line.

http://stackoverflow.com/comment/88969380
has text: If you understand Ned's article you'll understand why this 3 line program does what it does: `lst = [[1],[2],[3]]` `for a in lst: a *= 2` `print(lst)`
comment on: http://stackoverflow.com/a/50987134
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50951506
upvote count: 0
answer count: 1
has body: A SocketIO server created using aiohttp appends a new string to a global dict zoo on receiving a addAnimal message from its socketio clients. Is it possible to also print out the dict zoo every 5 seconds? My current code below does not seem to print zoo every 5 seconds. import time from aiohttp import web import socketio zoo = [] sio = socketio.AsyncServer() app = web.Application() sio.attach(app) @sio.on('addAnimal') async def onAddAnimal(sid, animal): zoo.append(animal) print('Zoo: ', zoo) if __name__ == '__main__': web.run_app(app) while True: print('Zoo:', zoo) time.delay(5)
favorite count: 0
has title: How to make SocketIO/aiohttp print to screen every X seconds
tagged with: python
tagged with: python-3.x
tagged with: aiohttp
has answer: http://stackoverflow.com/a/50986120
downvote count: 1
tagged with: socket.io
type: Question
accepted answer: http://stackoverflow.com/a/50986120
type: AnsweredQuestion
score: -1
tagged with: python-socketio

http://stackoverflow.com/comment/88736149
has text: @user2715898 google "python memoization decorator" hopefully you can take one of the existing solutions and understand it ... and figure out how you might add a timelimit
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50866911
score: 1

http://stackoverflow.com/comment/88993129
comment on: http://stackoverflow.com/q/50998813
has text: Thank you for responding. I am updating my question. I had syntax errors and mislabeled a variable. Not typing '.py' doesn't seem to matter at all. In fact, all the programs ARE running in sequence when I run bmi_main.py. *The problem, I think, is that 'height' is a variable local to module 2 but I need to use it in module 3, so it needs to be global. How do I do that? I've tried initializing it in 'main' but it's giving me definition errors. Doing 'global height;' in module 2 does nothing.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/50880096
has comment: http://stackoverflow.com/comment/88763061
accepted answer of: http://stackoverflow.com/q/50879915
has comment: http://stackoverflow.com/comment/88762451
has body: On time-series datasets, data splitting takes place in a different way. See this link for more info. Alternatively, you can try TimeSeriesSplit from scikit-learn package. So the main idea is this, suppose you have 10 points of data according to timestamp. Now the splits will be like this : Split 1 : Train_indices : 1 Test_indices : 2 Split 2 : Train_indices : 1, 2 Test_indices : 3 Split 3 : Train_indices : 1, 2, 3 Test_indices : 4 Split 4 : Train_indices : 1, 2, 3, 4 Test_indices : 5 So on and so forth. You can check the example shown in the link above to get a better idea of how TimeSeriesSplit works in sklearn Update If you have a separate time column, you can simply sort the data based on that column and apply timeSeriesSplit as mentioned above to get the splits. In order to ensure 67% training and 33% testing data in final split, specify number of splits as following: no_of_split = int((len(data)-3)/3) Example X = np.array([[1, 2], [3, 4], [1, 2], [3, 4],[1, 2], [3, 4],[3, 4],[1, 2], [3, 4],[3, 4],[1, 2], [3, 4] ]) y = np.array([1, 2, 3, 4, 5, 6,7,8,9,10,11,12]) tscv = TimeSeriesSplit(n_splits=int((len(y)-3)/3)) for train_index, test_index in tscv.split(X): print("TRAIN:", train_index, "TEST:", test_index) #To get the indices X_train, X_test = X[train_index], X[test_index] y_train, y_test = y[train_index], y[test_index] OUTPUT : ('TRAIN:', array([0, 1, 2]), 'TEST:', array([3, 4, 5])) ('TRAIN:', array([0, 1, 2, 3, 4, 5]), 'TEST:', array([6, 7, 8])) ('TRAIN:', array([0, 1, 2, 3, 4, 5, 6, 7, 8]), 'TEST:', array([ 9, 10, 11])) ​
has comment: http://stackoverflow.com/comment/88763026
type: Answer
has comment: http://stackoverflow.com/comment/88765040
score: 11
has comment: http://stackoverflow.com/comment/88762805
answers question: http://stackoverflow.com/q/50879915
has comment: http://stackoverflow.com/comment/88762941
has comment: http://stackoverflow.com/comment/88764989
upvote count: 11
has comment: http://stackoverflow.com/comment/88762586
has comment: http://stackoverflow.com/comment/88764731
has comment: http://stackoverflow.com/comment/88762893
has comment: http://stackoverflow.com/comment/88762573
has comment: http://stackoverflow.com/comment/88762974
has comment: http://stackoverflow.com/comment/88762994
has comment: http://stackoverflow.com/comment/88762875
has comment: http://stackoverflow.com/comment/88762644
has comment: http://stackoverflow.com/comment/88765787
has comment: http://stackoverflow.com/comment/88762486
has comment: http://stackoverflow.com/comment/88763918
has comment: http://stackoverflow.com/comment/88762676
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/50859683
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/50859877
has answer: http://stackoverflow.com/a/50859877
accepted answer: http://stackoverflow.com/a/50859696
has title: Set values of a dataframe based on a second dataframe
has body: I would like to mask a Pandas dataframe based on booleans in another dataframe. So, I've created a pandas DataFrame of 1 and 0: boolean_data = [(1, 0), (0, 1), (0, 0)] df_criteria = DataFrame(data=boolean_data, index=['A','B','C'], columns=['x','y']) x y A 1 0 B 0 1 C 0 0 I would like to use the above df_criteria to mask values of a second dataframe df_result, i.e., where df_criteria(i,j)=1, df_result(i,j)=0. df_result = DataFrame( data=[(10, 20), (30, 20), (10, 10)], index=['A','B','C'], columns=['x','y']) df_result (before masking) x y A 10 20 B 30 20 C 10 10 df_result (after masking) x y A 0 20 B 30 0 C 10 10
tagged with: python
type: AnsweredQuestion
upvote count: 2
type: Question
has answer: http://stackoverflow.com/a/50859696
answer count: 2
tagged with: pandas
score: 2

http://stackoverflow.com/a/57906704
type: Answer
answers question: http://stackoverflow.com/q/50973569
score: 3
upvote count: 3
downvote count: 0
has body: It seems that recent Django Rest Framework update has the default choice for a field retrieves from the result of the to_representation. File location: venv/lib/python3.6/site-packages/rest_framework/relations.py Under RelatedField Class see get_choices method. Opened issue Possible solution: reference link from collections import OrderedDict class ModifiedRelatedField(serializers.RelatedField): def get_choices(self, cutoff=None): queryset = self.get_queryset() if queryset is None: # Ensure that field.choices returns something sensible # even when accessed with a read-only field. return {} if cutoff is not None: queryset = queryset[:cutoff] return OrderedDict([ ( item.pk, self.display_value(item) ) for item in queryset ]) class CityRelatedField(ModifiedRelatedField): def to_representation(self, value): city = { 'id': value.id, 'name': value.name } return city class AirportSerializer(serializers.ModelSerializer): city = CityRelatedField(queryset=models.City.objects.all()) class Meta: model = models.Airport fields = ('id', 'city', 'name', 'iata') Hope it will help.

http://stackoverflow.com/comment/88789473
type: Comment
type: QuestionComment
has text: @Chiefir Thank you very much. More_like_this function is working with models which is i guess much better for my case. so i wouldn't have to turn them to string and apply different algorithms. I've just read the documentation but i haven't tried it yet. I'm going to try it asap and see if i get what i want. I've also found the question you mentioned i've tested the solution it worked for your example really good but as soon as i change the place of SOME and TEXT so it be TEXT and SOME it won't work properly. Thank you very much for your help. I hope more_like_this works :)
score: 0
comment on: http://stackoverflow.com/q/50889419

http://stackoverflow.com/q/50895683
has comment: http://stackoverflow.com/comment/88791352
has answer: http://stackoverflow.com/a/50895720
has body: I have a variable that can be int or None. If is something else I raise an error. I have the following code: if not isinstance(id, int) or id is not None: raise AttributeError('must be called with a id of type INT or NONE') This is not working, because each condition negates the other and will always raise the error.
tagged with: python-3.5
answer count: 1
accepted answer: http://stackoverflow.com/a/50895720
favorite count: 0
tagged with: python-3.x
has title: Check if a variable is instance of a type or None
tagged with: python
type: AnsweredQuestion
upvote count: 2
has comment: http://stackoverflow.com/comment/88791429
downvote count: 3
type: Question
score: -1
tagged with: python-3.6

http://stackoverflow.com/a/51002123
has comment: http://stackoverflow.com/comment/88998013
score: 1
has body: I've played with your sample data a little so that one user logs in on three days. The problem in your attempt is that you are trying to "just plot" the logins. If you want to see the frequency of logins, you have to calculate that. So I read the data and use a proper DateTime index, then use groupby followed by resample to calculate the frequencies. I think with 400 users this might become a bit messy, but this will do a plot of the daily logins per user. import pandas import io d = """id,datetime 130,2018-05-17T19:46:18 133,2018-05-17T20:59:57 133,2018-05-17T21:54:01 142,2018-05-17T22:49:07 114,2018-05-17T23:02:34 136,2018-05-18T06:06:48 136,2018-05-18T12:21:38 130,2018-05-18T12:49:33 120,2018-05-18T14:03:58 130,2018-05-19T15:28:36""" # for the data aboce, this is a quick way to parse it df = pandas.read_csv(io.StringIO(d), parse_dates=['datetime'], index_col='datetime') # This method is more roundabout but is perhaps useful if you have other data df = pandas.read_csv(io.StringIO(d)) df.datetime = pandas.to_datetime(df.datetime) df = df.set_index('datetime') # Plot daily logins per user id r = df.groupby('id').resample('D').apply(len).unstack('id').plot()
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88998364
has comment: http://stackoverflow.com/comment/88998250
type: Answer
has comment: http://stackoverflow.com/comment/88998701
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51001858
answers question: http://stackoverflow.com/q/51001858

http://stackoverflow.com/a/50926670
answers question: http://stackoverflow.com/q/50923769
accepted answer of: http://stackoverflow.com/q/50923769
has body: You're creating two instances of Tk(). This means that you have two Tcl interpreters, which are completely separated (for more info on this read this answer by Bryan Oakley). You didn't post enough code to exactly see what's happening, but I'm pretty sure it has to do with trying to access information in one Tcl interpreter from the other. So in general, make sure you only have one instance of Tk(). To have multiple windows which share the same Tcl interpreter, make the second a Toplevel() window.
type: AcceptedAnswer
score: 0
type: Answer

http://stackoverflow.com/q/50910480
has body: Is it possible to have a class attribute targeting another attribute from the same object and have a function to update the value of the target? class MyObject(object): def __init__(self): self.var_1 = 1 self.var_2 = 2 self.var_3 = 3 self.current_var = self.var_1 def update_var(self, value): self.current_var = ... Expected outcome: &gt;&gt;&gt; x = MyObject() &gt;&gt;&gt; x.update_var(10) &gt;&gt;&gt; x.var_1 10 &gt;&gt;&gt; x.current_var = x.var_2 &gt;&gt;&gt; x.update_var(5) &gt;&gt;&gt; x.var_2 5
upvote count: 5
has comment: http://stackoverflow.com/comment/88820913
accepted answer: http://stackoverflow.com/a/50910816
has comment: http://stackoverflow.com/comment/88821045
has comment: http://stackoverflow.com/comment/88820940
answer count: 3
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/50910732
has comment: http://stackoverflow.com/comment/88821212
has title: Python set attribute equal to another attribute
has answer: http://stackoverflow.com/a/50910732
tagged with: python
has answer: http://stackoverflow.com/a/50910816
has comment: http://stackoverflow.com/comment/88821025
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88821237
has answer: http://stackoverflow.com/a/50912174
type: Question
score: 5

http://stackoverflow.com/a/51123013
has body: I have solved the problem of question 2 by introducing scaling and offset. The other two problems were due to the canvas being redrawn over the created lines. Those problems are now fixed. The class for DraggablePoint now looks like this: import matplotlib.pyplot as plt import matplotlib.patches as patches from matplotlib.lines import Line2D import matplotlib class DraggablePoint: lock = None def __init__(self, parent, dominant, x=10, y=10, size=1): """Creates a draggable Point on a matplotlib canvas""" matplotlib.matplotlib_fname() # The FigureCanvas self.parent = parent # The Point self.point = patches.Ellipse((x, y), size, size, fc='r', alpha=0.5, edgecolor='r') #Coordinates of the point self.x = x self.y = y self.x_offset = 260 self.y_offset = 640 self.dy = 640 self.dx = 260 self.x_offset_factor = 0.06 self.y_offset_factor = -0.089 self.x_scaling = self.x * self.x_offset_factor self.y_scaling = self.y * self.y_offset_factor self.dy = self.y_offset + self.y_scaling self.dx = self.x_offset + self.x_scaling # Adds the point to the Plot parent.fig.axes[0].add_patch(self.point) # Used in the on_press() function self.press = None self.background = None # initiate the mpl_connects self.connect() # The Other DraggablePoint, with whom the line shall connect with. self.partner = None # The Line2D self.line = None self.dominant = dominant for pair in self.parent.point_pairs: if self in pair: if self == pair[1]: line_x = [pair[0].x + pair[0].dx, self.x+self.dx] line_y = [pair[0].y + pair[0].dy, self.y+self.dy] self.line = Line2D(line_x, line_y, color='r', alpha=0.5) parent.fig.axes[0].add_line(self.line) else: line_x = [pair[1].x + pair[1].dx, self.x + self.dx] line_y = [pair[1].y + pair[1].dy, self.y + self.dy] self.line = Line2D(line_x, line_y, color='r', alpha=0.5) parent.fig.axes[0].add_line(self.line) for pair in self.parent.point_pairs: self.point.axes.draw_artist(pair[1].line) def connect(self): 'connect to all the events we need' # print("LOG.INFO: DraggablePoint.co…
score: 1
upvote count: 1
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51004906
type: Answer
accepted answer of: http://stackoverflow.com/q/51004906

http://stackoverflow.com/q/51007129
has title: DLL Load failed error when installing opencv for Python 3.6.3 on Windows 10
answer count: 2
has answer: http://stackoverflow.com/a/76355389
downvote count: 0
score: 1
favorite count: 0
type: UnansweredQuestion
has body: I have python 3.6.3 32-bit version running on windows 10 64-bit machine. python version info Since the opencv found on this official website only supports python 2.7, I read here that I can use the following method to install opencv for python 3.6 However when I try to import cv2 in python, I get the following error: &gt;&gt;&gt; import cv2 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: DLL load failed: The specified module could not be found. I also tried downloading opencv for python 3.6 from this unofficial site and following these instructions. I am still getting the same error. Can somebody help me fix this?
tagged with: python
has answer: http://stackoverflow.com/a/51007152
linked to: http://stackoverflow.com/q/43184887
upvote count: 1
type: Question
tagged with: opencv

http://stackoverflow.com/comment/88849416
has text: when I print ridereq , the first time it shows nothing , but when I run again it shows the the dictionary
comment on: http://stackoverflow.com/q/50924750
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50984298
has comment: http://stackoverflow.com/comment/88972284
score: 0
tagged with: django-2.0
has answer: http://stackoverflow.com/a/51021136
has comment: http://stackoverflow.com/comment/88965128
tagged with: django
tagged with: python
has body: I have a problem with queryset in Django 2.0, after some research, I don't find any problem looks like mine. I think it's because of my very old legacy database create by someone I didn't know. So, I have a sqlite database who looks like this: Has you can see, the Table Properties don't have primary_key, so i made a models with django inspectdb command who looks like this: from django.db import models class Record(models.Model): id = models.IntegerField(db_column='ID', primary_key=True) class Meta: db_table = 'Records' def __str__(self): return "%s" % self.id class Propertie(models.Model): id = models.ForeignKey(Record, models.DO_NOTHING, db_column='ID', primary_key=True) item = models.CharField(db_column='Item', max_length=500) value = models.CharField(db_column='Value', max_length=500) class Meta: db_table = 'Properties' def __str__(self): return '[%s]- %s -&gt; %s' % (self.item, self.value, self.id) I set Properties.id as primary_key but it's a ForeignKey and Django say to set this field as OneToOneField and it's normal and logic, but 1 Record is linked to 9 Properties so Porpertie.id can't be unique this is my first problem because I can't alter the database. My second and real problem is when I run this query: def my_view(request): epoch = datetime.date(1970, 1, 1) period_from = stat_form.cleaned_data.get("period_from") period_to = stat_form.cleaned_data.get("period_to") product = stat_form.cleaned_data.get("kit") timestamp_from = period_from - epoch timestamp_to = period_to - epoch records = Record.objects.using("statool").filter( propertie__item="product", propertie__value=product, ).filter( propertie__item="stamp", propertie__value__gt=str(int(timestamp_from.total_seconds())), propertie__value__lt=str(int(timestamp_to.total_seconds())), ).count() this QuerySet is empty but it should return approximately 16XXX Record I don't know what happens? Because if I do this query: records = Record.objects.using("statool").filter( propertie__item="product", propertie__v…
has comment: http://stackoverflow.com/comment/88968617
accepted answer: http://stackoverflow.com/a/51021136
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/28101580
type: Question
tagged with: django-queryset
answer count: 1
tagged with: django-filter
has title: Django - Multi filtering queryset return empty queryset

http://stackoverflow.com/a/50893452
answers question: http://stackoverflow.com/q/50878885
type: Answer
has body: Lambda (native code) layers are not supported in TensorFlow.js. You will need to replace it with a custom layer. This is tricky. Here is an example custom layer: https://github.com/tensorflow/tfjs-examples/tree/master/custom-layer
upvote count: 3
score: 3
downvote count: 0

http://stackoverflow.com/q/50871813
has comment: http://stackoverflow.com/comment/88752470
has title: Add space between widgets WxPython
type: Question
has body: This is my code: class TabTwo(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent) self.resetButton = wx.Button(self, label="Reset") self.contactButton = wx.Button(self, label="Contact") self.copyrightButton = wx.Button(self, label="Copyright") v_sizer = wx.BoxSizer(wx.VERTICAL) h_sizer = wx.BoxSizer(wx.HORIZONTAL) v_sizer.Add(self.resetButton, 0, wx.EXPAND, 30) v_sizer.Add(self.contactButton, 0, wx.EXPAND, 30) v_sizer.Add(self.copyrightButton, 0, wx.EXPAND, 30) self.SetSizer(v_sizer) How do I add some space between the buttons (Reset, Contact and Copyright) so that it doesn't look to much like it's been pressed together.
accepted answer: http://stackoverflow.com/a/50872518
upvote count: 3
tagged with: wxwidgets
has answer: http://stackoverflow.com/a/50872518
answer count: 1
tagged with: wxpython
linked to: http://stackoverflow.com/q/9306808
has comment: http://stackoverflow.com/comment/88751903
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88752079
tagged with: python
type: AnsweredQuestion
score: 3
downvote count: 0

algorithm
tags question: http://stackoverflow.com/q/50866477
tags question: http://stackoverflow.com/q/50868588
tags question: http://stackoverflow.com/q/50896944
tag name: algorithm
tags question: http://stackoverflow.com/q/50946387
tags question: http://stackoverflow.com/q/50902062
tags question: http://stackoverflow.com/q/50884330
tags question: http://stackoverflow.com/q/50875644
tags question: http://stackoverflow.com/q/50984758
tags question: http://stackoverflow.com/q/50955583
tags question: http://stackoverflow.com/q/50987691
tags question: http://stackoverflow.com/q/50890336
tags question: http://stackoverflow.com/q/50972843
tags question: http://stackoverflow.com/q/50957340
tags question: http://stackoverflow.com/q/50888786
tags question: http://stackoverflow.com/q/50943979
tags question: http://stackoverflow.com/q/50916898
tags question: http://stackoverflow.com/q/51003564
tags question: http://stackoverflow.com/q/50865446
tags question: http://stackoverflow.com/q/50976550
type: Tag
tags question: http://stackoverflow.com/q/50941661
tags question: http://stackoverflow.com/q/50925906
tags question: http://stackoverflow.com/q/51011297
tags question: http://stackoverflow.com/q/50865041
tags question: http://stackoverflow.com/q/50985232
tags question: http://stackoverflow.com/q/50929904
tags question: http://stackoverflow.com/q/50930549
tags question: http://stackoverflow.com/q/50886890
tags question: http://stackoverflow.com/q/50900899
tags question: http://stackoverflow.com/q/50896837
tags question: http://stackoverflow.com/q/50906200
tags question: http://stackoverflow.com/q/50932756
tags question: http://stackoverflow.com/q/50978864

http://stackoverflow.com/q/50870470
has comment: http://stackoverflow.com/comment/88789620
tagged with: python-3.7
answer count: 1
has comment: http://stackoverflow.com/comment/88745349
has comment: http://stackoverflow.com/comment/88743348
has comment: http://stackoverflow.com/comment/88745700
has answer: http://stackoverflow.com/a/50897678
favorite count: 0
has body: I am writing regx for removing test qualifier and extra delimiter from the string. I have some pattern as below, "ID"~"Name"~"DESC" 1~2014~13~"DS"~DF" 1~2014~13~"DS"~"DF" "1ABCA~B C"~"ERTE" "2"~"XYZ"~"ABC~ is~ bother" "3"~"YYZ"~"MEL O CRÈME DOUGHNUTS RECLASS" 4~"XAA"~"sf~sd sdfsf" 5~"TES"~"SFSFSF"sdfsf" 6~"ABC"SDDSL~"dfadf" the expected output is, ID~Name~DESC 1~2014~13~DS~DF 1~2014~13~DS~DF 1ABCA B C~ERTE 2~XYZ~ABC is bother 3~YYZ~MEL O CRÈME DOUGHNUTS RECLASS 4~XAA~sf sd sdfsf 5~TES~SFSFSF"sdfsf 6~ABCSDDSL~dfadf I have written below code for the same, import re delimiter = '~' pattern = re.compile(r'"' + delimiter + r'"') pattern1 = re.compile(r'"[^"]*(?:""[^"]*)*"') with open("source file path here ", "r") as \ test: for line in test: fields = re.split(pattern, line) print(fields) output = "" if re.match('^[^"]', line): matches = re.findall(pattern1, line) print(matches) for match in matches: line = re.sub(match, re.sub('^["]|["]$', "", match), line) print(line) else: lastfield = fields[-1] for field in fields: if field != lastfield: field = re.sub('^["]|["]$', "", field) output = output + re.sub('[' + delimiter + ']', " ", field) \ + delimiter else: field = re.sub('^["]|["]$', "", field) output = output + re.sub('[' + delimiter + ']', " ", field) print(output) looking for optimize way to do this and the code which will handle all the patterns.
has comment: http://stackoverflow.com/comment/88745664
has comment: http://stackoverflow.com/comment/88768110
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/88743011
has comment: http://stackoverflow.com/comment/88743049
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88771650
score: 1
has comment: http://stackoverflow.com/comment/88743076
upvote count: 3
has comment: http://stackoverflow.com/comment/88743140
downvote count: 2
accepted answer: http://stackoverflow.com/a/50897678
has comment: http://stackoverflow.com/comment/88794368
has comment: http://stackoverflow.com/comment/88787400
has comment: http://stackoverflow.com/comment/88787568
has comment: http://stackoverflow.com/comment/88773021
type: Question
has comment: http://stackoverflow.com/comment/88745803
has comment: http://stackoverflow.com/comment/88743176
has comment: http://stackoverflow.com/comment/88744669
has comment: http://stackoverflow.com/comment/88745521
has title: regx for python

http://stackoverflow.com/comment/88826749
comment on: http://stackoverflow.com/a/50912638
type: Comment
score: 0
has text: You can make a new question, copy-paste the code into the body of the question, then highlight it and press ctrl-k to format it.
type: AnswerComment

http://stackoverflow.com/a/75207401
answers question: http://stackoverflow.com/q/50974960
upvote count: 3
has body: A virtual environment is the integration of a collection of dependencies that ensure one or more applications can seamless work together. It provides a set of runtime guarantees for the applications of interest. Virtual environments isolate the given set of dependencies from the system's applications allowing users and developers to have as many application contexts as desired. In particular, Python virtual environments are designed to isolate a particular set of dependencies tied to a particular version of Python from the system Python. In this way, a user can have multiple system Python versions each of which can have a corresponding set of virtual environments each with independent dependencies. Because Python virtual environments only apply to Python, any non-Python application installed in the system will be seen by all Python virtual environments in the exact same way. In concrete terms, one can have Python3.7 to Python3.11 installed as system Pythons while at the same time having four Python3.10 virtual environments (venv1-venv4) each with different versions of the requests library. Applications within venv2 may only work with the particular version of requests in that virtual environment and no other. On the other hand, Anaconda virtual environments extend the set of dependencies beyond Python to include virtually any application. This means that they can include system applications (non-Python) together with the complete set of underlying libraries completely independent of system applications. For example, an anaconda virtual environment on, say, Apple Silicon with the HDF5 library will have the complete build of HDF5 for Apple Silicon only within the virtual environment. Any application that is run outside this Anaconda virtual environment will be completely ignorant of the existence of HDF5. Docker, or containers in general, are a completely different technology only available on Linux machines in which applications are virtually isolated from one anothe…
type: Answer
score: 3
downvote count: 0

http://stackoverflow.com/comment/88737711
type: QuestionComment
comment on: http://stackoverflow.com/q/50867793
type: Comment
has text: The only way you get direct support for this sort of operation is using third party extensions, e.g. `numpy` `array`s. Python built-ins don't have a concept of multidimensional structures; it's composable (so you can have a structure of structures and work with each layer independently), but not specialized to multidimensions.
score: 0

http://stackoverflow.com/q/50948169
has body: I installed graphviz in anaconda version 2.7, but while executing graphviz I find an error that says: InvocationException: GraphViz's executables not found
upvote count: 0
has answer: http://stackoverflow.com/a/59807657
score: -1
tagged with: graphviz
has answer: http://stackoverflow.com/a/50948504
type: Question
answer count: 2
tagged with: python
favorite count: 0
type: UnansweredQuestion
has title: Graphviz Python visualization execution error
downvote count: 1

http://stackoverflow.com/comment/89004558
type: AnswerComment
type: Comment
has text: I have not get to rest framework part yet. Can I know what is the first part code for?
comment on: http://stackoverflow.com/a/51003751
score: 0

http://stackoverflow.com/a/50991421
downvote count: 0
has comment: http://stackoverflow.com/comment/88978377
type: Answer
has comment: http://stackoverflow.com/comment/88977702
answers question: http://stackoverflow.com/q/50991261
has comment: http://stackoverflow.com/comment/88978306
has comment: http://stackoverflow.com/comment/88978098
has body: From http://flask-bcrypt.readthedocs.io/en/latest/ pw_hash = bcrypt.generate_password_hash('hunter2') bcrypt.check_password_hash(pw_hash, 'hunter2') # returns True The reverse function needs to check the hash against the password, in your case user.password should actually be hashPwd if user and bcrypt.check_password_hash(hashPwd, form.password.data):
score: 4
has comment: http://stackoverflow.com/comment/88978078
upvote count: 4

http://stackoverflow.com/q/50873711
accepted answer: http://stackoverflow.com/a/50890831
answer count: 1
score: 0
tagged with: elementtree
tagged with: http://stackoverflow.com/tag/xml
has title: Python create xml file dynamically
has body: i'm having trouble creating the xml file in python. My script at start loads a text file, read each line and check if the content contains a specific string, depending on it i want to create a tag or in the xml file. For that i'm using the ElementTree module. This the code for line in myfile.read().splitlines(): if 'EXTINF' in line: root = etree.Element("item") etree.SubElement(root, "title").text = line elif 'http' in line: etree.SubElement(root, "link").text = 'http:\\mysite.com\' tree = etree.ElementTree(root) tree.write('my\\path\\'+xml_file.xml) The xml file contains only the last element iterated by for loop. The output i would like is: "my title" "http:\\mysite.com" "my title" "http:\\mysite.com" "my title" "http:\\mysite.com" What's wrong? Thanks
tagged with: file
has answer: http://stackoverflow.com/a/50890831
tagged with: python
type: AnsweredQuestion
type: Question

http://stackoverflow.com/q/50888967
score: -1
has comment: http://stackoverflow.com/comment/91553845
answer count: 2
upvote count: 0
has comment: http://stackoverflow.com/comment/88779194
favorite count: 0
has answer: http://stackoverflow.com/a/50889112
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88779423
has answer: http://stackoverflow.com/a/50889086
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/50889112
has comment: http://stackoverflow.com/comment/88779392
has title: python Dictionary clearing not iterable
possible better answer: http://stackoverflow.com/a/50889086
linked to: http://stackoverflow.com/q/1334020
has body: I'm new in Python, hope somebody can help me I tried this, but i got an error: TypeError: argument of type 'NoneType' is not iterable I think the problem is that some value are none and i can't delete something thats none? etheurticker= finexticker.get('ETH/EUR') if 'askVolume' and 'bidVolume' and 'vwap' and 'open' and 'previousClose' and 'change' and 'percentage' and 'baseVolume' and 'quoteVolume' and 'info'and 'average' in etheurticker: del etheurticker['askVolume'] del etheurticker['bidVolume'] del etheurticker['vwap'] del etheurticker['open'] del etheurticker['previousClose'] del etheurticker['change'] del etheurticker['percentage'] del etheurticker['baseVolume'] del etheurticker['quoteVolume'] del etheurticker['info'] del etheurticker['average'] This is the dictionary without clearing: {'symbol': 'ETH/EUR', 'timestamp': 1529160540908.2085, 'datetime': '2018-06- 16T14:49:01.908Z', 'high': 440.45, 'low': 416.57356472, 'bid': 422.75, 'bidVolume': None, 'ask': 422.77, 'askVolume': None, 'vwap': None, 'open':None, 'close': 422.76, 'last': 422.76, 'previousClose': None, 'change': None, 'percentage': None, 'average': 422.76, 'baseVolume': 3318.1630349899992, 'quoteVolume': None, 'info': {'mid': '422.76', 'bid': '422.75', 'ask': '422.77', 'last_price': '422.76', 'low': '416.57356472', 'high': '440.45', 'volume': '3318.1630349899992', 'timestamp': '1529160540.908208614', 'pair': 'ETHEUR'}} Hope anybody can help me :)
has comment: http://stackoverflow.com/comment/88779265

http://stackoverflow.com/q/50938727
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50950007
type: Question
possible better answer: http://stackoverflow.com/a/50950007
has answer: http://stackoverflow.com/a/50938757
has body: Okay, so this code works fine for me. a = [1, 2, 3, 4] c = ['Three' if i is 3 else "Not Three" for i in a] print(c) Output: ['Not Three', 'Not Three', 'Three', 'Not Three'] But doing the same thing a bit more complexly, this code does not work. Where am I missing something? import numpy as np # 2 random np array of 10 elements ranging from -1 to 1 x = np.random.rand((10))*2 - 1 y = np.random.rand((10))*2 - 1 # xor = x&gt;0 and y&gt;0 or x&lt;=0 and y&lt;=0 xor = np.logical_or( np.logical_and( np.greater(x, 0), np.greater(y, 0)), np.logical_and( np.less_equal(x, 0), np.less_equal(y, 0)) ) print(xor) # prints an array of random true and false of shape 200 colors = np.array(['blue' if i is True else 'red' for i in xor]) # should print array of 'blue' and 'red' according to xor. But prints all 'red' print(colors) Outputs: [ True True False False True True True False False True] ['red' 'red' 'red' 'red' 'red' 'red' 'red' 'red' 'red' 'red']
tagged with: list-comprehension
tagged with: numpy
score: 0
answer count: 2
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/50938757
tagged with: python
has title: List comprehension not working in python

http://stackoverflow.com/q/50929948
upvote count: 1
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/50930234
linked to: http://stackoverflow.com/q/6190776
has comment: http://stackoverflow.com/comment/88859247
score: 0
linked to: http://stackoverflow.com/q/73663
answer count: 2
favorite count: 0
has body: I made this function that does a for loop and then passes a calculated variable to a formula outside of the loop. However, I would like to stop the whole code if all the conditions are not met for my function. I put a break in my for loop hoping that it would stop my whole function but it only stopped the for loop from printing the error text a bunch of times. Is there a way that I can stop the whole code if all conditions of my function are not properly met? I'm trying to make it so that it only shows the error print if the user puts the wrong text in. def some_function(x, activation): """ Arguments: x = data activation stored as text string: "yes" or "no" Returns: z """ for i in range(10): if activation == "yes": y = 2 * x elif activation == "no": y = 100 * x else: print("ERROR: you must choose an activation. activation types: \"yes\" or \"no\"") break z = y + 200 return z test some_function(3, "enzyme") ERROR: you must choose an activation. activation types: "yes" or "no" --------------------------------------------------------------------------- UnboundLocalError Traceback (most recent call last) &lt;ipython-input-41-7a8962459048&gt; in &lt;module&gt;() ----&gt; 1 some_function(3, "y") &lt;ipython-input-39-e16f270340d2&gt; in some_function(x, activation) 17 break 18 ---&gt; 19 z = y + 200 20 21 return z UnboundLocalError: local variable 'y' referenced before assignment
has comment: http://stackoverflow.com/comment/88871897
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50930359
tagged with: python
has comment: http://stackoverflow.com/comment/130763593
has comment: http://stackoverflow.com/comment/88871396
has title: how to stop code after break in loop
has comment: http://stackoverflow.com/comment/88859103

http://stackoverflow.com/a/54116165
downvote count: 0
upvote count: 2
answers question: http://stackoverflow.com/q/51002441
type: Answer
score: 2
has body: run anaconda prompt as administrator and try the following command "conda install -c conda-forge hmmlearn", that installs the package from another channel, or try any other channel from the link: https://anaconda.org/search?q=hmmlearn

http://stackoverflow.com/comment/88985944
type: AnswerComment
comment on: http://stackoverflow.com/a/50995708
type: Comment
has text: Why is there a need to try? It's pretty straight forward. The code will work as it is. Just pointing out a redundant condition.
score: 0

http://stackoverflow.com/comment/88999026
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51002694
has text: Variables and environment variables are not the same thing.

http://stackoverflow.com/comment/88980458
has text: @seuling yeah you are right . its not booked in admin its not showing booking. but in carlistview car is not showing that i booked . but the form is not saving i think so . in admin i cannot see any booking
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50982757

http://stackoverflow.com/comment/88786961
type: Comment
type: QuestionComment
has text: Try storing the values: `t2a, t2b = t+t, t*2`. Then they won't have the same `id` (except when they're the same object because of the small-int optimization or compiler constant folding, of course…)
score: 0
comment on: http://stackoverflow.com/q/50893267

http://stackoverflow.com/a/51007867
upvote count: 1
score: 1
has body: @roganjosh is right, raw_input returns a string, so you have to do the below: input_age = raw_input("What is your age, " + input_name + "? ") if not input_age: print("You didn't enter anything") elif input_age.isdigit(): if int(input_age) &lt; 12 : print("Sorry, you are not old enogh to play") elif int(input_age) &gt;= 12: print ("Welcome") if not input_age.isdigit(): print("You entered a character or characters instead of a digit or digits")
accepted answer of: http://stackoverflow.com/q/51007680
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51007680
type: Answer

http://stackoverflow.com/comment/88862945
has text: What dependencies have you tried installing? What distribution are you using?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50932009

http://stackoverflow.com/comment/88881139
comment on: http://stackoverflow.com/q/50941570
score: 0
type: Comment
type: QuestionComment
has text: Normally the system automatically deletes "typo" questions after a couple of days, but we'll have to delete this one manually because it has upvoted answers, and those answers also prevent you from deleting it. Sorry about that.

http://stackoverflow.com/comment/88915576
has text: is your while condition `True` -- in other words, is your line `while True:`?
type: Comment
comment on: http://stackoverflow.com/a/50959103
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88802066
type: QuestionComment
has text: Have you tried using pip's `--no-cache-dir`?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50883524

http://stackoverflow.com/comment/88793477
type: Comment
has text: The `.grid` method returns `None`, so with `start=ttk.Button(root, text="Start", command=start).grid(row=0,column=0,padx=10,pady=10)` you set `start` to `None`. And you shouldn't try to use `start` for the name of the button and the name of a function. It doesn't really hurt here, since you never need the function name after you pass it into the button constructor. OTOH, why even bother naming the button, you don't use that name anywhere?
score: 1
comment on: http://stackoverflow.com/q/50896847
type: QuestionComment

http://stackoverflow.com/comment/88835013
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50901392
has text: In `change_screen()` method, replace `self.ids.screens.ids.manager.current` with `self.parent.ids.screen.current`

http://stackoverflow.com/comment/88808912
type: AnswerComment
has text: @Daannnn How long is this expected to take? Are you going to have to perform this task frequently or is it just a one off? These are some questions you'd want to ask yourself before you consider it a big data problem. If so, ask another question on stack overflow stating that you have tried my answer and someone might now some faster (potentially numpy/cython) approaches to this problem. Hope that helps
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50857139

http://stackoverflow.com/q/50918728
has comment: http://stackoverflow.com/comment/88837477
type: Question
tagged with: discord.py
has comment: http://stackoverflow.com/comment/88837447
score: 0
has comment: http://stackoverflow.com/comment/88837450
has body: So, I have a bot, I want it to save data to json file, I get error when running: Ignoring exception in on_ready Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/discord/client.py", line 307, in _run_event yield from getattr(self, event)(*args, **kwargs) File "/home/zorin/Desktop/den.py", line 14, in on_ready amounts = json.load(f) File "/usr/local/lib/python3.6/json/__init__.py", line 299, in load parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw) File "/usr/local/lib/python3.6/json/__init__.py", line 354, in loads return _default_decoder.decode(s) File "/usr/local/lib/python3.6/json/decoder.py", line 339, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/local/lib/python3.6/json/decoder.py", line 357, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) Is there a special way I should be doing this? Json file is a empty amounts.json. Code: from discord.ext import commands import json import discord bot = commands.Bot('!') amounts = {} @bot.event async def on_ready(): global amounts try: with open('amounts.json') as f: amounts = json.load(f) except FileNotFoundError: print("Could not load amounts.json") amounts = {} @bot.command(pass_context=True) async def balance(ctx): id = ctx.message.author.id if id in amounts: await bot.say("You have {} in the bank".format(amounts[ctx.message.author.id])) else: await bot.say("You do not have an account") @bot.command(pass_context=True) async def register(ctx): id = ctx.message.author.id if id not in amounts: amounts[id] = 100 await bot.say("You are now registered") else: await bot.say("You already have an account") @bot.command(pass_context=True) async def transfer(ctx, amount: int, other: discord.Member): primary_id = ctx.message.author.id other_id = other.id if primary_id not in amounts: await bot.say("You do not have an account") elif other_id not in amou…
has comment: http://stackoverflow.com/comment/88837425
has comment: http://stackoverflow.com/comment/88837488
has title: Discord.py bot has issue with json
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88837481
tagged with: python

http://stackoverflow.com/q/50890662
answer count: 1
has title: Accessing distinct foreign key relationships with django queryset
tagged with: django-rest-framework
score: 4
favorite count: 0
tagged with: foreign-keys
has body: Given basic book/author models: class Book(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey('Author') publisher = models.ForeignKey('Publisher') class Author(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) Lets say I have a very complex query to select books based on a bunch of parameters (my actual models are much more complex than these). For simplification sake, my complex query for this example will just select books that have the word "the" in their title: q = Book.objects.filter(title__icontains="the") Is there a way (other than looping, or using reverse foreign key lookups) to get all distinct Author objects linked to the books in this query? E.g. I have tried adding: q = q.values('author').distinct() But this simply returns the author__id values. I am trying to go about it this way, as my 'complex query' is quite time/resource intensive, and I'd only like to run that query once (to get the books, and separate a list of distinct authors). Also the data sets need to be flattened (a separate list of Books and Authors) as it is getting presented via django rest framework, and my clients require the data sets to be flat. E.g.: { "books": [ {"id": 1, "title": "The Book.", "author": 1, "publisher": 1}, {"id": 2, "title": "The Other Book.", "author": 2, "publisher": 1}, {"id": 3, "title": "The Best Book.", "author": 1, "publisher": 1}, ], "authors": [ {"id": 1, "first_name": "Joe", "last_name": "Smith"}, {"id": 2, "first_name": "Gina", "last_name": "Randolph"} ] } Alternatively, is there a simple way with django rest framework to take the results of a complex query with nested foreign keys, and flatten it out?
has answer: http://stackoverflow.com/a/50890704
accepted answer: http://stackoverflow.com/a/50890704
upvote count: 4
tagged with: django
tagged with: python
type: AnsweredQuestion
type: Question
tagged with: django-queryset
downvote count: 0

http://stackoverflow.com/comment/135734194
has text: That's correct, and the workaround is to convert the non-native JSON formats to strings. At the JSON import, the conversion to the non-native JSON formats can be then done manually. Also added the latest version I'm using (the first solution).
comment on: http://stackoverflow.com/a/73634275
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/88951964
type: QuestionComment
has text: @abarnert made the changes
score: 0
comment on: http://stackoverflow.com/q/50977944
type: Comment

http://stackoverflow.com/q/51009330
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/120889905
tagged with: python
upvote count: 2
tagged with: django
type: Question
has title: Error: MagickWand shared library not found. You probably had not installed ImageMagick library. (even though I have)
has answer: http://stackoverflow.com/a/68398598
has comment: http://stackoverflow.com/comment/89017685
linked to: http://stackoverflow.com/q/49894919
tagged with: imagemagick
answer count: 2
score: 2
downvote count: 0
has body: I've installed Imagemagick and wand however I get this error message when trying to start my django server: ImportError: MagickWand shared library not found. You probably had not installed ImageMagick library. Try to install: brew install freetype imagemagick so I perform brew install freetype imagemagick and then it responds with: Warning: freetype 2.9.1 is already installed and up-to-date To reinstall 2.9.1, run `brew reinstall freetype` Warning: imagemagick 7.0.8-2 is already installed and up-to-date To reinstall 7.0.8-2, run `brew reinstall imagemagick` so I perform brew reinstall imagemagick and then it returns the original error: ImportError: MagickWand shared library not found. You probably had not installed ImageMagick library. Try to install: brew install freetype imagemagick and this cycle continues. Any idea what the problem is?
has answer: http://stackoverflow.com/a/60146091
favorite count: 0

http://stackoverflow.com/comment/88910148
score: 0
type: Comment
has text: no no, actually, I'm using schedule module, but I need to update my question with more information. Do you care if take a time to update my question? I'll make it simple
type: QuestionComment
comment on: http://stackoverflow.com/q/50955963

http://stackoverflow.com/q/50883330
has answer: http://stackoverflow.com/a/50904735
upvote count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/128432960
has title: finding contours of a plant root
has comment: http://stackoverflow.com/comment/88810733
tagged with: contour
downvote count: 0
has body: I have an image which has roots like this: I want to crop each root individually out. I initially thought of heavy dilation followed by erosion and contour detection of the blob, but since the roots are thin, it does not work well. I also directly applied canny edge and contour detection like this image below. It has around 62000 contours, but I cannot use it to get the outline of each root. I also thresholded the image using HSV followed by some median blurring. But it did not reduce much noise. Further blurring only leads to losing the root features. Can anyone suggest me a better approach to tackle this problem? Will any Machine Learning based approach work better? Thanks
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88772215
tagged with: edge-detection
type: Question
answer count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/88773213
has answer: http://stackoverflow.com/a/50889095
has comment: http://stackoverflow.com/comment/88782584
has comment: http://stackoverflow.com/comment/88808398
has comment: http://stackoverflow.com/comment/88829530
tagged with: opencv

http://stackoverflow.com/comment/88780260
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/173270/discussion-between-ahmed-osama-and-jeru-luke).
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50886765
type: AnswerComment

http://stackoverflow.com/q/50883812
type: Question
has title: Learning dictionaries with multiple attributes - How to edit when a key has more than one?
has comment: http://stackoverflow.com/comment/88769675
has body: I'm trying to edit (add, subtract, and stuff like that) to this dictionary: data = {'Altri': [10000, 4.3910, 4.3910], 'BCP': [10000, 0.2312, 0.2312], 'Corticeira Amorim': [10000, 12.2500, 12.2500], 'CTT': [10000, 5.5480, 5.5480], 'EDP': [10000, 3.2840, 3.2840], 'EDP Renovaveis': [10000, 6.9910, 6.9910], 'Galp Energia': [10000, 13.7850, 13.7850], 'Ibersol': [10000, 14.9000, 14.9000], 'Jeronimo Martins': [10000, 17.5600, 17.5600], 'Mota-Engil': [10000, 2.7340, 2.7340], 'NOS': [10000, 5.5150, 5.5150], 'Novabase': [10000, 3.2390, 3.2390], 'Pharol': [10000, 0.2690, 0.2690], 'REN': [10000, 2.8680, 2.8680], 'Semapa': [10000, 16.7000, 16.7000], 'Sonae Capital': [10000, 0.8740, 0.8740], 'Sonae SGPS': [10000, 0.9260, 0.9260], 'Navigator': [10000, 4.0720, 4.0720], 'Montepio UP': [10000, 0.7470, 0.7470]} my logic: BANK NAME - BALANCE - BUY VALUE - SELL VALUE What I am trying to do: So I know that I can do stuff like print(data["Altri"]) But how can I edit the buy and sell values? Can someone show me how to do like a print of the sell value? I keep googling stuff but it's rather hard to find stuff for this kind of dictionary.
has comment: http://stackoverflow.com/comment/88769641
has answer: http://stackoverflow.com/a/50883871
score: 0
has comment: http://stackoverflow.com/comment/88769667
answer count: 1
has comment: http://stackoverflow.com/comment/88769623
accepted answer: http://stackoverflow.com/a/50883871
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88769723

http://stackoverflow.com/q/50917456
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50917641
has title: Efficient way to compute the probability distribution of a vector of pairs in python
type: Question
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/50917641
tagged with: python
tagged with: binomial-cdf
has body: Suppose we have a numpy array v v=np.array([3, 5]) Now we use the below code to find a new vector say w v1=np.array(range(v[0]+1)) v2=np.array(range(v[1]+1)) w=np.array(list(itertools.product(v1,v2))) So w looks like this, array([[0, 0], [0, 1], [0, 2], [0, 3], [0, 4], [0, 5], [1, 0], [1, 1], [1, 2], [1, 3], [1, 4], [1, 5], [2, 0], [2, 1], [2, 2], [2, 3], [2, 4], [2, 5], [3, 0], [3, 1], [3, 2], [3, 3], [3, 4], [3, 5]]) Now, we need to find the probability vector corresponding to each pair in w knowing that the first element in each pair follows a Binomial distribution Bin(v[0], 0.1) and the second element of each pair follows a Binomial distribution Bin(v[1], 0.05). One way to do it is by this one liner import scipy.stats as ss prob_vector=np.array(list((ss.binom.pmf(i[0],v[0], 0.1) * ss.binom.pmf(i[1],v[1], 0.05)) for i in w)) output: array([5.64086303e-01, 1.48443764e-01, 1.56256594e-02, 8.22403125e-04, 2.16421875e-05, 2.27812500e-07, 1.88028768e-01, 4.94812547e-02, 5.20855312e-03, 2.74134375e-04, 7.21406250e-06, 7.59375000e-08, 2.08920853e-02, 5.49791719e-03, 5.78728125e-04, 3.04593750e-05, 8.01562500e-07, 8.43750000e-09, 7.73780938e-04, 2.03626563e-04, 2.14343750e-05, 1.12812500e-06, 2.96875000e-08, 3.12500000e-10]) But it takes tooo much time to compute, especially since I am iterating over several v vectors!! Is there an efficient way to compute prob_vector? Thanks

http://stackoverflow.com/a/50881235
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50880647
accepted answer of: http://stackoverflow.com/q/50880647
type: Answer
has body: You might need to convert the incoming json to python dictionary Assuming this is your response response = {"Subtitles": ...} #convert to dict import json json_data = json.loads(response) # print content for a_subtitle in response['Subtitles']: print(a_subtitle['content']) # extract family and timestamp family = json_data["Class"]["family"] timestamp = json_data["Class"]["Timestamp"] image_url = "https://example.com/image/" + family + "/" + str(timestamp)
has comment: http://stackoverflow.com/comment/88764888
has comment: http://stackoverflow.com/comment/88861481
upvote count: 1
score: 1

http://stackoverflow.com/q/51009252
type: AnsweredQuestion
has title: How to use the tuples created in one python script to another?
upvote count: 2
score: 0
downvote count: 2
answer count: 1
favorite count: 0
tagged with: tuples
has body: Suppose I have a tuple of tuples I created say a = ((2,2),(5,5),(6,2)) in my current python script A.py. I want to import these tuple of tuples into another python script B.py. Writing into a text file requires it to a be string but I want to export a defined in A.py as it is. How do I go about it?
has answer: http://stackoverflow.com/a/51009364
accepted answer: http://stackoverflow.com/a/51009364
tagged with: python
type: Question

http://stackoverflow.com/a/50865514
answers question: http://stackoverflow.com/q/50861943
score: 0
type: Answer
has body: Oops, of course it was something stupid. This line was wrong: name = sa.Column('contact', sa.String) Should have been: name = sa.Column(sa.String)

http://stackoverflow.com/a/50959081
answers question: http://stackoverflow.com/q/50958938
score: 0
type: Answer
has body: In the block of code that begins on line 24: if b == 'Sword': Instead of using k2 and p2 for reassigning the knight and player health, use the same variable as the initial assignment outside of the loop, player and knight. knight = (knight - randint(3,4)) player = (player - randint(2,6)) Each time the loop is run, the updated health value will be used.

http://stackoverflow.com/a/50997329
type: Answer
upvote count: 4
has comment: http://stackoverflow.com/comment/88989411
has body: It is due to the design goals of the requests project. This behavior is documented here. You may want to use a lower level library, if it is problematic for the library to be correcting content length or adding desirable headers. Requests bills itself as: "an elegant and simple HTTP library for Python, built for human beings." and a part of that is advertising that it can accept compressed content and all mime types. Note: Custom headers are given less precedence than more specific sources of information. For instance: Authorization headers set with headers= will be overridden if credentials are specified in .netrc, which in turn will be overridden by the auth= parameter. Authorization headers will be removed if you get redirected off-host. Proxy-Authorization headers will be overridden by proxy credentials provided in the URL. Content-Length headers will be overridden when we can determine the length of the content.
accepted answer of: http://stackoverflow.com/q/50997220
type: AcceptedAnswer
downvote count: 0
score: 4
answers question: http://stackoverflow.com/q/50997220

http://stackoverflow.com/q/50864509
tagged with: python
type: UnansweredQuestion
tagged with: selenium
type: Question
has body: I am trying to use selenium with python and am running into an issue when trying to use the webdriver.expectedConditions class. The following code is excerpted from a couple of classes, but all necessary code is included: from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC def isVisible(self, driver, HOW, WHAT, timeout=2): locator=(HOW,WHAT) try: WebDriverWait(driver, timeout).until(EC.visibility_of_element_located(locator)) return True except TimeoutException: return False newApplicationXpath = "//input[@value='New']" self.assertTrue(self.isVisible(self.driver, "By.XPATH", newApplicationXpath, 120)) Traceback: WebDriverException: Message: unknown error: Unsupported locator strategy: By (Session info: chrome=66.0.3359.139) (Driver info: chromedriver=2.37.544315 (730aa6a5fdba159ac9f4c1e8cbc59bf1b5ce12b7),platform=Linux 4.1.12-112.14.10.el7uek.bug27766149.x86_64 x86_64)
answer count: 1
has answer: http://stackoverflow.com/a/50864561
score: 0
has title: unknown error: Unsupported locator strategy: By

http://stackoverflow.com/comment/130740650
type: AnswerComment
comment on: http://stackoverflow.com/a/73954830
has text: I tried to use this with slides generated from SSRS. Those slides have one image of all of the content but the pictures do not have a name. May I suggest checking for the image attribute instead of checking for picture in the name? if hasattr(shp, 'image'): and then I changed the image name saved to file to include a variable which increments each loop.
type: Comment
score: 0

http://stackoverflow.com/q/51009154
downvote count: 0
accepted answer: http://stackoverflow.com/a/51011725
has title: Does Perl 6 have an equivalent to Python's bytearray method?
favorite count: 0
has comment: http://stackoverflow.com/comment/89011514
upvote count: 8
type: Question
tagged with: python
linked to: http://stackoverflow.com/q/7555689
has body: I can't find bytearray method or similar in Raku doc as in Python. In Python, the bytearray defined as this: class bytearray([source[, encoding[, errors]]]) Return a new array of bytes. The bytearray class is a mutable sequence of integers in the range 0 &lt;= x &lt; 256. It has most of the usual methods of mutable sequences, described in Mutable Sequence Types, as well as most methods that the str type has, see String Methods. Does Raku should provide this method or some module?
tagged with: raku
answer count: 2
has answer: http://stackoverflow.com/a/51011725
score: 8
tagged with: encoding
possible better answer: http://stackoverflow.com/a/51010355
has answer: http://stackoverflow.com/a/51010355
type: AnsweredQuestion

http://stackoverflow.com/q/50877313
downvote count: 3
tagged with: python
upvote count: 9
has comment: http://stackoverflow.com/comment/88756593
score: 6
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50877615
linked to: http://stackoverflow.com/q/41956806
has answer: http://stackoverflow.com/a/50877585
accepted answer: http://stackoverflow.com/a/50877585
has title: Python == with or vs. in list comparison
has body: When checking for equality, is there any actual difference between speed and functionality of the following: number = 'one' if number == 'one' or number == 'two': vs. number = 'one' if number in ['one', 'two']:
has comment: http://stackoverflow.com/comment/88765824
has comment: http://stackoverflow.com/comment/88757216
type: Question
has comment: http://stackoverflow.com/comment/88757077
tagged with: python-2.7
answer count: 2
has comment: http://stackoverflow.com/comment/88756765
favorite count: 0
has comment: http://stackoverflow.com/comment/88758052
possible better answer: http://stackoverflow.com/a/50877615

http://stackoverflow.com/comment/88867654
type: Comment
type: QuestionComment
score: 0
has text: Replace RelativeLayout with StackLayout
comment on: http://stackoverflow.com/q/50878126

http://stackoverflow.com/comment/88953947
type: QuestionComment
comment on: http://stackoverflow.com/q/50978923
has text: Would you be open to using a 3rd party library like numpy or pandas?
score: 0
type: Comment

http://stackoverflow.com/comment/88883048
type: QuestionComment
has text: Ah, yeah ok, why not. I added a link in the question and the code is the one I've already posted
score: 0
comment on: http://stackoverflow.com/q/50919585
type: Comment

http://stackoverflow.com/comment/88759230
type: QuestionComment
score: 0
has text: https://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference see this for an explanation of pass by value/ reference. What you're trying to do isn't possible in Python, so you'll need to restructure your code
comment on: http://stackoverflow.com/q/50878530
type: Comment

http://stackoverflow.com/q/50871509
has comment: http://stackoverflow.com/comment/88745322
has comment: http://stackoverflow.com/comment/88746920
type: Question
has comment: http://stackoverflow.com/comment/88745105
score: 0
has comment: http://stackoverflow.com/comment/88747857
has answer: http://stackoverflow.com/a/69610819
has comment: http://stackoverflow.com/comment/88746798
answer count: 1
has comment: http://stackoverflow.com/comment/88847829
has body: I am coding in c to solve a question. In the c code, I need to call a self-defined python to solve a equation. I am able to call the python function for twice time, however when i call the third time, I get an error:"Unhandled exception at 0x00007FEDF8A4E0C(multiarray.cp35-win_amd64.pyd) in Project.1.exe: 0xC0000005: Access violation writing location 0x000000000000000A." It is very strange because in the first and second time, I can call the function successfully and if I independently call the function with the parameters used in the third time, the function can run very well. However, if I try to do the work continuously, it causes the exception above. I have seen a similar question 'C's Python API: Calling python function 2X causes Access violation writing location' in STACKOVERFLOW, however, there is no answer for that problem. PyObject* pRet = PyEval_CallObject(pv, args); The c code above is the place where causing the exception when calling the python function the third time. The whole process calling the python function is described more clearly below. Here comes the python function first from sympy import * init_printing(use_unicode=True) def evaluate_dH(eps,bmax,H,B_H1,B_H2): x=symbols("x") expr=eps*(x-bmax)**2*x**(H+2)-(H+2)*x*B_H1+(H+1)*B_H2 result=solve(expr,x)#result is a list type When solving out the equation, I used two condition that ">bmax" and "not a complex" to find the value in 'result' I need. the final is only one. Thus, return result[0] Second, here comes the calling process in c code. Firstly, "double find_dH" is a c function I used in my main function. double find_dH (....) { double B_H2 = findBH(region, vecp_vertex, H + 2, index); double B_H1 = findBH(region, vecp_vertex, H + 1, index); double eps = 0.01; double bmax = findbmax(region, vecp_vertex); Py_Initialize(); PyObject *pModule = NULL; PyRun_SimpleString("import sys"); PyRun_SimpleString("sys.path.append('./')"); pModule = PyImport_ImportModule("evaluate_dH"); PyObject* pv = PyObject…
has comment: http://stackoverflow.com/comment/88746118
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88744934
tagged with: python
has title: an access violation writing location error the third time when calling a python function in c code
tagged with: c++

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

http://stackoverflow.com/a/51000934
has comment: http://stackoverflow.com/comment/88996163
has comment: http://stackoverflow.com/comment/88997543
accepted answer of: http://stackoverflow.com/q/51000606
has comment: http://stackoverflow.com/comment/88996881
answers question: http://stackoverflow.com/q/51000606
has comment: http://stackoverflow.com/comment/88997429
upvote count: 1
has comment: http://stackoverflow.com/comment/88996013
type: AcceptedAnswer
has body: As @wiesion said in a comment to the question, you could try to reset the buffer with data.seek(0). Why? Well, in your code you have this data = request.FILES['file'] data_50 = request.FILES['file'] meaning that data and data_50 will point to the same file. When you call data.read(), the content gets read and the current position stays at the end of the file. When you later call data_50.read(), the current position is already at the end (because its the same file as data) and there is no more content to be read, so the call to read() returns no content. So there is no image to be saved. By calling data.seek(0) (or data_50.seek(0) or request.FILES['file'].seek(0)) you are telling that file to place the current position at the start of the file again, so that a next call to read() can output the whole file content again. input_file = BytesIO(data.read()) image_crop = Image.open(input_file) print('print 2') # ADD THIS LINE TO YOUR CODE # it modifies the 'data' object, which is the same as 'data_50' data.seek(0) # Problem starts. input_file_50 = BytesIO(data_50.read()) image_crop_50 = Image.open(input_file_50) Another way you could try (without calling .seek(0)) would be to assing the result of .read() to a variable: file_content = request.FILES['file'].read() input_file = BytesIO(file_content) input_file_50 = BytesIO(file_content) image_crop = Image.open(input_file) image_crop_50 = Image.open(input_file_50) Maybe you could try this version and let us know if it solves your problem.
type: Answer
has comment: http://stackoverflow.com/comment/88996145
downvote count: 0
score: 1

http://stackoverflow.com/comment/88964016
has text: This may help https://stackoverflow.com/questions/37903479/python-lambda-function-parsing-dynamodbs-json-format
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50984277
score: 1

http://stackoverflow.com/comment/88746076
has text: I've edited my question. Please let me know if you don't understand
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50871340
score: 0

http://stackoverflow.com/comment/88750727
type: AnswerComment
type: Comment
score: 0
has text: @akhilrastogi Your dislike for Amadan's answer is really odd to me. This answer is 7 times slower than Amadan's for me on your example array and more than an order of magnitude slower on larger arrays.
comment on: http://stackoverflow.com/a/50874565

google-cloud-platform
tags question: http://stackoverflow.com/q/50889174
tags question: http://stackoverflow.com/q/50935649
tags question: http://stackoverflow.com/q/50960540
tags question: http://stackoverflow.com/q/50953718
tags question: http://stackoverflow.com/q/50974836
tags question: http://stackoverflow.com/q/50885739
tags question: http://stackoverflow.com/q/50970504
tags question: http://stackoverflow.com/q/50977476
tags question: http://stackoverflow.com/q/50860448
type: Tag
tag name: google-cloud-platform
tags question: http://stackoverflow.com/q/50918217
tags question: http://stackoverflow.com/q/50959061
tags question: http://stackoverflow.com/q/50932363
tags question: http://stackoverflow.com/q/50934415

http://stackoverflow.com/comment/88783667
type: AnswerComment
comment on: http://stackoverflow.com/a/50891417
has text: Thanks for replying.. actually I did check the `timeit` module in `python` as well before posting.. and did see this.. What I was wondering is why it is necessary to have 2 different options `-n` and `-r`, why not just have 1? I will check the code that you mentioned in some more detail to see if there is any difference..
type: Comment
score: 1

http://stackoverflow.com/a/50892614
has comment: http://stackoverflow.com/comment/88785809
has comment: http://stackoverflow.com/comment/88786060
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/88785839
has body: Take a look at itertools.product to generate arguments, and then simply call the function: arguments = itertools.product(list_of_values_for_arg_1, list_of_values_for_arg_2, ..., list_of_values_for_arg_n) # or arguments = itertools.product(*list_of_lists) for arg in arguments: result=func(*arg) So to generate dict you need to do something like this: {arg: func(*arg) for arg in itertools.product(*list_of_lists)}
accepted answer of: http://stackoverflow.com/q/50892564
answers question: http://stackoverflow.com/q/50892564
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88785887
has comment: http://stackoverflow.com/comment/88785919
type: Answer

http://stackoverflow.com/a/55859978
has body: I had the same issue, asking me for Microsoft Visual Studio C++ 14 Build tools, I've tried every possible solution that I saw on Stackoverflow and github. The only fix that worked for me is using the .whl file in https://www.lfd.uci.edu/~gohlke/pythonlibs/#hmmlearn and more importantly using a 32-bit version of the whl file (I just realized i was using 32bit Python3.6 while in a 64bit Win10 OS) In the specific .venv folder, activate the environment and type: pip install &lt;yourdir&gt;/hmmlearn‑0.2.1‑cp36‑cp36m‑win32.whl
type: Answer
has comment: http://stackoverflow.com/comment/113688827
has comment: http://stackoverflow.com/comment/137351943
has comment: http://stackoverflow.com/comment/137400632
score: 4
upvote count: 4
downvote count: 0
answers question: http://stackoverflow.com/q/51002441

http://stackoverflow.com/comment/88940046
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50929181
has text: @Evgeny I will write something executable next time. Thank you for the help!

http://stackoverflow.com/a/50957709
type: AcceptedAnswer
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50956747
downvote count: 0
has comment: http://stackoverflow.com/comment/88913079
has body: In Python/NumPy, explicitly replicating an array to make it match another is not necessary. Dimensions of size 1 (singleton dimensions) are automatically expanded in a process they call "broadcasting". For example, given X = np.array([[1,2,3,4,5],[4,5,6,7,8],[7,8,9,10,11]]) you can write X - np.max(X, axis=0) The array returned by np.max has a shape of (5,), which is compatible with the shape of X ((3, 5)). NumPy aligns the shapes starting at the last dimension, and fills in singleton dimensions at the front if one array has fewer than the other. However, this process sometimes needs a little bit of help. Because np.max returns an array with fewer dimensions than the input, broadcasting cannot, in general. match up these arrays. For example, X - np.max(X, axis=1) doesn't work. The best solution is to use the keepdims argument to np.max: X - np.max(X, axis=1, keepdims=True) The other option is to add singleton dimensions using np.newaxis in indexing: X - np.max(X, axis=1)[:, np.newaxis]
has comment: http://stackoverflow.com/comment/88913004
accepted answer of: http://stackoverflow.com/q/50956747

http://stackoverflow.com/comment/88758012
type: Comment
has text: Thanks! But I am adding only those features back that I do not run PCA on.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50877894

http://stackoverflow.com/q/50960258
accepted answer: http://stackoverflow.com/a/50960287
tagged with: python
has answer: http://stackoverflow.com/a/50960287
tagged with: mysql
type: AnsweredQuestion
has title: Fix python Sqlalchemy model can not insert mysql syntax error
tagged with: sqlalchemy
type: Question
score: 0
answer count: 1
has body: Python Model: class SYSLocation(SYSModel): __tablename__ = 'sys_location' rank = db.Column(db.Integer) Call: db.session.add(model) It generate mysql script: INSERT INTO `sys_location` ( rank) VALUES (13000) sql error : You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'rank) VALUES (13000)' at line 1 I check this query run error mysql version 8.0.11 because rank is keyword. But this sql can run mysql version 10.1.25-MariaDB. How to fix my Sqlalchemy model run all version of mysql?

http://stackoverflow.com/comment/88858762
comment on: http://stackoverflow.com/q/50929437
has text: Virtualenv takes care of the pip version, in this case pip3 to use with python3.6
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/50913494
answer count: 1
has comment: http://stackoverflow.com/comment/88829192
has body: I know all of the datasets that can be loaded with sns.load_dataset() are all example datasets, used for Seaborn's documentation, but do these example datasets use actual data? I'm asking because I want to know if it's useful to pay attention to the results I get as I play around with these datasets, or if I should just see them as solely a means to learning the module.
favorite count: 0
type: UnansweredQuestion
tagged with: seaborn
tagged with: data-visualization
has title: Does Seaborn's sns.load_dataset() function use real data?
tagged with: python
downvote count: 0
score: 1
type: Question
tagged with: data-science
upvote count: 1
has answer: http://stackoverflow.com/a/50913987

http://stackoverflow.com/comment/88968553
has text: @jpp - DataFrame A (df1), DataFrame B (df2). concat performed because of this sentence `I want to loop through each column of Dataframe A (or not loop), and copy each column to Dataframe B`
score: 1
comment on: http://stackoverflow.com/a/50982165
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50926421
accepted answer: http://stackoverflow.com/a/50926604
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/50926604
has comment: http://stackoverflow.com/comment/88855260
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88852454
has body: I am trying to sort a list of tuples. Each tuple represents a grid x and y value. I want to sort the tuples based upon the grid's object attribute that they represent. For example: my grid of y * x elements where each element has an object named node. Each node has an attribute called globalGoal. list a = [(1, 2), (2, 4)] (1, 2) reference grid[1][2] grid[1][2] = node node.globalGoal = (int) value is the value I wish to sort if (1, 2) represents the globalGoal value of 75 and (2, 4) represents the globalGoal value of 45 then I want my list ordered as [(2, 4), (1, 2)] my test code that I assembled from other stackoverflow answers is: class getSortedKey: global grid def __init__(self, node): self.node = grid[node[0]][node[1]].globalGoal def __cmp__(self, othernode): return(cmp(self.node, othernode)) a = [(1, 2), (2, 4)] a.sort(key=lambda b: getSortedKey(b)) firstly I have a problem getting my grid list containing all the nodes into the class, secondly I get the error: TypeError: '&lt;' not supported between instances of 'getSortedKey' and 'getSortedKey' Am I going in the right direction, or is there a simple way to achieve this. I can achieve what I want by writing my own sorting function (bubble sort) but it is too slow. My next step would be to write a quick sort but I'm struggling with sorting in my particular scenario, so I thought using Pythons own sort would be far better, but obviously I have hit a wall. Any help gratefully received. I have searched for similar answers but nothing seems to be what I need (unless I have mis understood other answers)
type: Question
tagged with: sorting
has title: Sorting tuples that reference objects
has comment: http://stackoverflow.com/comment/88852928

http://stackoverflow.com/comment/88880671
type: AnswerComment
comment on: http://stackoverflow.com/a/50935565
type: Comment
has text: Thank y for the prompt response, but now I get the following error: `IndexError: tuple index out of range` (also with `[apple]`).
score: 0

http://stackoverflow.com/a/54590047
answers question: http://stackoverflow.com/q/50863397
type: Answer
has body: I tried a loop to get rid of the offset. It may affect the estimator though. Probably, not a good way to handle the initial offset. Mat_&lt;float&gt; measurement(2, 1); KF.statePre.at&lt;float&gt; (0) = curMeasurement.x; KF.statePre.at&lt;float&gt; (1) = curMeasurement.y; KF.statePre.at&lt;float&gt; (2) = 0; KF.statePre.at&lt;float&gt; (3) = 0; measurement(0) = curMeasurement.x; measurement(1) = curMeasurement.y; for (int i = 0; i &lt; 100; i++) { KF.predict(); KF.correct(measurement); }
score: 0

http://stackoverflow.com/q/50880165
has comment: http://stackoverflow.com/comment/88762607
has comment: http://stackoverflow.com/comment/88762648
has body: I have two list that are connected together. In the first one I store questions and in the second one I store answers. If I deem a question or an answer unacceptable, I would like to remove both, keeping the order unchanged. This is an example: Questions : Answers 0 Hi how.. : 0 answer0 1 What are.. : 1 answer1 2 What is : 2 answer2 .................(The list will be VERY big) I want to remove for example entry 1 in both lists, while keeping the order the same. How can I do so?
has answer: http://stackoverflow.com/a/50880188
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/88762674
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88762625
tagged with: python
has title: Computationally efficient way of removing an entry from list without changing the order?
tagged with: list
type: Question

http://stackoverflow.com/a/50894809
answers question: http://stackoverflow.com/q/50894760
score: 3
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88789734
upvote count: 3
has body: In the line grid = GridSearchCV(RandomForestClassifier, param_grid, cv=5, scoring='roc_auc'), instead of what you've written, try grid = GridSearchCV(RandomForestClassifier(), param_grid, cv=5, scoring='roc_auc') I can't say for sure.. Because you're not giving me X and y, or I could be able to reproduce it in my laptop and let you know if it works! Let me know if it works!
type: Answer
accepted answer of: http://stackoverflow.com/q/50894760
downvote count: 0

http://stackoverflow.com/a/50950898
type: Answer
has body: As argument of url tag you should use url name, not regular expression: &lt;form class="form" method="POST" action="{% url 'add_test' %}"&gt; Instead of &lt;form class="form" method="POST" action="{% url 'test-management/test/add_test/' %}"&gt;
score: 2
answers question: http://stackoverflow.com/q/50950864
has comment: http://stackoverflow.com/comment/88900460
accepted answer of: http://stackoverflow.com/q/50950864
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88900139
upvote count: 2

http://stackoverflow.com/comment/88921448
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50962326
type: Comment
has text: coldspeed, it's 8 after midnight, you never sleep? :)

http://stackoverflow.com/q/51007306
has answer: http://stackoverflow.com/a/51007378
has body: I am making a snake game in Python by the help of google , but I found some errors which i dont understand why its so happening...my code is import random import curses s = curses.initscr() curses.curs_set(0) sh, sw = s.getmaxyx() w = curses.newwin(sh, sw, 0, 0) w.keypad(1) w.timeout(100) snk_x = sw/4 snk_y = sh/2 snake = [ [snk_y, snk_x], [snk_y, snk_x-1], [snk_y, snk_x-2] ] food = [sh/2, sw/2] w.addch(food[0], food[1], curses.ACS_PI) key = curses.KEY_RIGHT while True: next_key = w.getch() key = key if next_key == -1 else next_key if snake[0][0] in [0, sh] or snake[0][1] in [0, sw] or snake[0] in snake[1:]: curses.endwin() quit() new_head = [ snake[0][0], snake[0][1]] if key == curses.KEY_DOWN: new_head[0] += 1 if key == curses.KEY_UP: new_head[0] -= 1 if key == curses.KEY_LEFT: new_head[1] -= 1 if key == curses.KEY_RIGHT: new_head[1] += 1 snake.insert(0, new_head) if snake[0] == food: food = None while food is None: nf = [ random.randint(1, sh-1), random.randint(1, sw-1) ] food = nf if nf not in snake else None w.addch(food[0], food[1], curses.ACS_PI) else: tail = snake.pop() w.addch(tail[0], tail[1], ' ') w.addch(snake[0][0], snake[0][1], curses.ACS_CKBOARD) While running this code I got two errors, i.e., Traceback (most recent call last): File "snakegame.py", line 20, in &lt;module&gt; w.addch(food[0], food[1], curses.ACS_PI) TypeError: integer argument expected, got float
has answer: http://stackoverflow.com/a/64935590
favorite count: 0
has answer: http://stackoverflow.com/a/67762334
has comment: http://stackoverflow.com/comment/89030073
has title: type error :integer argument expected
has comment: http://stackoverflow.com/comment/89029803
tagged with: python
has comment: http://stackoverflow.com/comment/89007749
has answer: http://stackoverflow.com/a/61095157
has comment: http://stackoverflow.com/comment/89007836
has comment: http://stackoverflow.com/comment/89029930
has comment: http://stackoverflow.com/comment/89007928
has answer: http://stackoverflow.com/a/57539807
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89030887
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/54104391
has comment: http://stackoverflow.com/comment/89030026
answer count: 6
type: Question
score: 0

http://stackoverflow.com/a/50884489
has comment: http://stackoverflow.com/comment/88830189
has body: Use F.array(), F.explode() and F.collect_set(): from pyspark.sql import functions as F df.withColumn('con', F.explode(F.array('device', 'model'))) \ .groupby('id').agg(F.collect_set('con').alias('Group_con')) \ .show(3,0) # +---+--------------------------------------------------------------------------+ # |id |Group_con | # +---+--------------------------------------------------------------------------+ # |3 |[cctv, mac pro, spy camera, mac] | # |1 |[windows pc, iphone5, windows, iphone, android phone, spy camera, android]| # |2 |[apple iphone, camera, iphone] | # +---+--------------------------------------------------------------------------+ (tested on spark version 2.2.1)
has comment: http://stackoverflow.com/comment/88830112
has comment: http://stackoverflow.com/comment/88833347
has comment: http://stackoverflow.com/comment/88829697
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88833157
answers question: http://stackoverflow.com/q/50884060
accepted answer of: http://stackoverflow.com/q/50884060
upvote count: 2
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/88830624

http://stackoverflow.com/comment/88818524
type: AnswerComment
has text: This is a solution to his problem but since OP is new I'd add a note to warned him about using globals. Especially in a code where his variables are not named correctly. That could lead to unwanted behavior.
comment on: http://stackoverflow.com/a/50909299
type: Comment
score: 0

http://stackoverflow.com/q/50965349
has comment: http://stackoverflow.com/comment/88927552
has body: I have a dataframe, which can be downloaded here. The first column contains a question while the second column contains an answers to that question. My aim: To create two .txt files, one that contains questions and one that contains answers. Each questions and answer should be written on a individual row. So that Row 50 in each .txt file contains the 50th question and the 50th answer. (IE that if the files are recombined the questions/answer pairs match up) The code snippet below opens a textfile, writes each row of the column to that file and removes any \n. It seems to work for about 96% of the rows, but very rarely it writes a single DF row across multiple text lines. These rare events don't seem to have any defining characteristics, they are not extremely long etc. For the file I attached above, the first one occurs at text file line 395 in the answers column. f = open("Answers.txt","a", newline="\n",encoding='utf-8') for i in tqdm(data['answers_body']): line = i.replace('\n','') f.write(line) f.write("\n") Interestingly, if I remove the f.write and just print to the console it seems to be work as expected... the issue only occurs during the write process.
answer count: 3
tagged with: pandas
tagged with: read-write
possible better answer: http://stackoverflow.com/a/50965476
has answer: http://stackoverflow.com/a/50965476
has title: Python writing a string to an maximum of one line in a textile
tagged with: python-3.x
score: 0
tagged with: python
has answer: http://stackoverflow.com/a/50965697
tagged with: text
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88927109
accepted answer: http://stackoverflow.com/a/50965697
has comment: http://stackoverflow.com/comment/88955832
type: Question
has answer: http://stackoverflow.com/a/50965503

http://stackoverflow.com/comment/88817818
has text: off course I can just a second
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50908642

http://stackoverflow.com/comment/93503668
has text: @KevinUpton I did not solve it yet. Still trying by directly using TensorFlow.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50900736
type: QuestionComment

http://stackoverflow.com/q/50860306
tagged with: merge
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50860414
type: Question
has body: I have a dataframe df1, which needs to have a new column 'h[mm]' appended. The values in the new 'h[mm]' should be looked up in df2 depending on values in df1's 'Profile' column. The situation could be compared to Excel's 'vlookup' or 'index/match'. I have successfully added the new column 'h[mm]' with the correct values to df1. However, it changes the order of the original df1, which is not desired in my case. A simplified reproducible version of the dataframes df1 and df2 are: pile_type = ['P01', 'P20', 'P05', 'P23', 'P04', 'P01'] profile = ['HE200A', 'HE220A', 'HE240B', 'NaN', 'HE200A', 'HE300B'] df1 = pd.DataFrame({'Pile_type': pile_type, 'Profile': profile}) profile_database = ['HE200A', 'HE220A', 'HE240B', 'HE500B', 'HE300B'] profile_height_database = [190, 210, 240, 500, 300] df2 = pd.DataFrame({'Profile': profile_database, 'h[mm]': profile_height_database}) The closest I came to a solution is using pd.merge_ordered(): df_mo= pd.merge_ordered(df1, df2, left_by='Profile') Which still does not preserve the original order of df1 in the resulting df_mo: print('df1:', df1) print('df2:', df2) print('df_mo:', df_mo) df1: Pile_type Profile 0 P01 HE200A 1 P20 HE220A 2 P05 HE240B 3 P23 NaN 4 P04 HE200A 5 P01 HE300B df2: Profile h[mm] 0 HE200A 190 1 HE220A 210 2 HE240B 240 3 HE500B 500 4 HE300B 300 df_mo: Pile_type Profile h[mm] 0 P01 HE200A 190.0 1 P04 HE200A 190.0 2 P20 HE220A 210.0 3 P05 HE240B 240.0 4 P23 NaN NaN 5 P01 HE300B 300.0 I have also tried the standard pd.merge() without luck.
upvote count: 5
has title: Preserve order of dataframe after merge
downvote count: 0
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/50860414
tagged with: pandas
answer count: 1
favorite count: 0
tagged with: python-3.x
score: 5
tagged with: python

http://stackoverflow.com/comment/88839246
type: AnswerComment
comment on: http://stackoverflow.com/a/50891219
score: 0
has text: sure, you can also do with both rectangles. Just change the np.where clause
type: Comment

http://stackoverflow.com/comment/88773964
score: 2
comment on: http://stackoverflow.com/q/50886076
type: QuestionComment
type: Comment
has text: What if there are multiple `'ac='` in a sublist?

http://stackoverflow.com/comment/88918354
score: 0
has text: Hi @roganjosh I installed xlwt file with pip install xlwt. Now it says another error WindowsError: [Error 3] The system cannot find the path specified: ''
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50940673

http://stackoverflow.com/comment/88719933
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50858252
has text: Thank you, I overlooked the fact in the tutorials, that I have to enter the command in the shell.

http://stackoverflow.com/comment/88795936
comment on: http://stackoverflow.com/q/50897978
score: 0
has text: what should I do instead of this !
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50956309
type: Question
has answer: http://stackoverflow.com/a/50956404
has answer: http://stackoverflow.com/a/50956407
answer count: 3
tagged with: strptime
upvote count: 1
has answer: http://stackoverflow.com/a/50956401
has comment: http://stackoverflow.com/comment/88910179
has title: strptime not working for below format
favorite count: 0
has comment: http://stackoverflow.com/comment/88910684
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88910076
has body: I have used the below format which is being read from a log file, The formatter used is matching the DateTime format. not sure why it is still erroring. - ValueError: time data " '2018-01-01 10:00:00'" does not match format '%Y-%m-%d %H:%M:%S' f = open("log.txt", 'w') f.write("UID, SID, LogTime\n") f.write("1, 1, '2018-01-01 10:00:00'\n") f.write("1, 1, '2018-01-01 10:30:00'\n") f.write("1, 1, '2018-01-01 11:30:00'\n") f.close() x = open("log.txt", 'r') print (x.read()) x.close() import numpy as np from datetime import datetime a = open("log.txt", 'r+') temp = None header = a.readline() for line in a: line = line.strip() columns = line.split(',') print (columns) UID = columns[0] SID = columns[1] print (columns[2]) LogTime = datetime.strptime(columns[2],"%Y-%m-%d %H:%M:%S") a.write(','+LogTime-temp) temp = LogTime
downvote count: 0
score: 1

http://stackoverflow.com/comment/89715339
type: Comment
has text: Nope, it's a security feature, and the only current solutions I've found are just workarounds that don't work for me. I guess in the meantime I'll just have to wait for the developers to implement something for headless downloading.
score: 0
comment on: http://stackoverflow.com/q/50885849
type: QuestionComment

http://stackoverflow.com/comment/88968364
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50977476
has text: Can you provide your pip commands? or requirements.txt file? How are you doing dependencies installation?
score: 0

http://stackoverflow.com/a/51005985
type: AcceptedAnswer
downvote count: 0
has body: The problem is that the function radon returns values way too high for tensorflow. Tensorflow wants values between 0 and 255 (uint8) per channel. I didn't look why that is, but I did a quick test after looking at the values in sinogram and decided to divide by np.max(sinogram) and the result looks much closer to what you expect I believe :) from skimage.transform import radon,iradon import tensorflow as tf import matplotlib.pyplot as plt import numpy as np sess = tf.Session() img = plt.imread('shepp-logan.jpg') theta = np.linspace(0., 180., max(img.shape), endpoint=False) sinogram = radon(img, theta=theta, circle=True) # scaling the values here sinogram = 255*sinogram/np.max(sinogram) sinogram = tf.cast(sinogram, tf.uint8) sinogram = tf.expand_dims(sinogram, -1) sinogram = tf.image.encode_jpeg(sinogram, quality=100, format='grayscale') writer = tf.write_file('test_sinogram.jpg', sinogram) sess.run(writer) As for tensorboard, which I recommend you use, you have to use tf.summary.image: https://www.tensorflow.org/api_docs/python/tf/summary/image And here is a guide for tensorboard: https://www.tensorflow.org/programmers_guide/summaries_and_tensorboard
upvote count: 8
type: Answer
score: 8
answers question: http://stackoverflow.com/q/51004123
accepted answer of: http://stackoverflow.com/q/51004123

http://stackoverflow.com/q/51005819
has body: I am trying to install the development version of owlready2; I take the following step; Extracted the development version downloaded from https://bitbucket.org/jibalamy/owlready2/downloads/ uninstalled previously installed owlready versions went to the extracted directory and did python setup.py develop but it is giving me the error that No module named owlready2 The code I am trying to run is below; from owlready2 import * onto = get_ontology("http://myplatform.com/test_sensor_onto") onto.imported_ontologies = [] sosa = get_ontology("file://sosa.owl").load() ssn = get_ontology("file://ssn.owl").load() onto.imported_ontologies.append(sosa) onto.imported_ontologies.append(ssn) sensor = sosa.Sensor("mySensor", namespace = onto) onto.save("test_sensor_onto2.owl") I have also tried to use python setup.py install, but then it gives an error that sensor =sosa.Sensor("mySensor", namespace = onto) TypeError: 'NoneType' object is not callable This error is same as for non-development versions of owlready2. I am wondering if I am doing anything wrong while installing the development version or I have to change some settings somewhere?
tagged with: owlready
tagged with: python
downvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51005919
score: 2
has title: Installing development version of a module in python
type: Question
upvote count: 2
answer count: 1
favorite count: 0

http://stackoverflow.com/a/69178830
score: 0
answers question: http://stackoverflow.com/q/51001877
has body: airflow 2.1.1 WTF_CSRF_ENABLED = True AUTH_TYPE = AUTH_LDAP AUTH_ROLE_ADMIN = 'Admin' AUTH_USER_REGISTRATION = True AUTH_USER_REGISTRATION_ROLE = "Public" AUTH_LDAP_USE_TLS = False AUTH_LDAP_SERVER = "ldap://ldapserver.local:389" AUTH_LDAP_SEARCH = "OU=Users,DC=ldapserver,DC=local" AUTH_LDAP_BIND_USER = "CN=Query User,OU=People,dc=ldapserver,dc=local" AUTH_LDAP_BIND_PASSWORD = "password" AUTH_LDAP_UID_FIELD = "sAMAccountName" AUTH_ROLES_MAPPING = { "CN=group_1_name,OU=Groups,DC=ldapserver,DC=local": ["Admin"], "CN=group_2_name,OU=Groups,DC=ldapserver,DC=local": ["Viewer"], } AUTH_LDAP_GROUP_FIELD = "memberOf" AUTH_ROLES_SYNC_AT_LOGIN = False PERMANENT_SESSION_LIFETIME = 1800
type: Answer

http://stackoverflow.com/comment/88950639
comment on: http://stackoverflow.com/a/50976975
type: AnswerComment
type: Comment
score: 1
has text: See: [operator precedence](https://www.mathworks.com/help/matlab/matlab_prog/operator-precedence.html) and [`colon`](https://www.mathworks.com/help/matlab/ref/colon.html)

lsa
tags question: http://stackoverflow.com/q/50915223
tag name: lsa
type: Tag

http://stackoverflow.com/q/51005141
has title: Failed building wheel for Twisted Command
tagged with: python
tagged with: visual-studio
answer count: 0
has comment: http://stackoverflow.com/comment/89006544
score: 0
type: Question
has comment: http://stackoverflow.com/comment/89004631
linked to: http://stackoverflow.com/q/27670365
has comment: http://stackoverflow.com/comment/89006643
has body: I'm working on a crypto trading bot to interface with the Binance API. There has been a toolkit somebody has developed to interface with Binance easier (I haven't spent the time to learn Python HTTP Requests for REST APIs yet) and I am attempting to install this toolkit, which is where I am running into trouble. The module wiki can be found here: https://python-binance.readthedocs.io/en/latest/ The error occurs while using !pip install python-binance in Spyder. I keep getting an error and have spent hours repairing my Visual C++ 2015, 2017, etc. and trying to find them to add to my python path in case that was the issue. Omitting all of the installation steps it spits out in my python console, it errors once it reaches this point every time. Unfortunately that landing hub link page isn't found. I've gone to Microsoft and updated to the latest versions as well. I'm guessing this has somethign to do with my paths in spyder, but I can't even find the Visual files in my computer beyond Visual Studio 8. building 'twisted.test.raiser' extension error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools ---------------------------------------- Failed building wheel for Twisted Command "c:\users\g\anaconda3\python.exe -u -c "import setuptools, tokenize;file='C:\Users\G\AppData\Local\Temp\pip-install-eyvyab9r\Twisted\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\G\AppData\Local\Temp\pip-record-vdboumt8\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\G\AppData\Local\Temp\pip-install-eyvyab9r\Twisted\"
tagged with: visual-c++
tagged with: spyder
linked to: http://stackoverflow.com/q/39537303
linked to: http://stackoverflow.com/q/29846087
has comment: http://stackoverflow.com/comment/89003979
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89003935
linked to: http://stackoverflow.com/q/38949519

http://stackoverflow.com/q/50974157
type: Question
has answer: http://stackoverflow.com/a/50974408
tagged with: dataframe
has comment: http://stackoverflow.com/comment/88944870
tagged with: numpy
answer count: 1
downvote count: 0
has title: How to replace a range of numbers in a column with a categorical value, given that range of numbers are of the type float
favorite count: 0
has body: df['ratio_usage'] = np.where(df['ratio_usage'].between(0.9,0.1), 'Excellent', df['ratio_usage']) df['ratio_usage'] = np.where(df['ratio_usage'].between(0.8,0.89), 'Very Good', df['ratio_usage']) df['ratio_usage'] = np.where(df['ratio_usage'].between(0.7,0.79), 'Good', df['ratio_usage']) df['ratio_usage'] = np.where(df['ratio_usage'].between(0.6,0.69), 'Fair', df['ratio_usage']) df['ratio_usage'] = np.where(df['ratio_usage'].between(0.5,0.59), 'Satisfactory', df['ratio_usage']) df['ratio_usage'] = np.where(df['ratio_usage'].between(0.4,0.49), 'Poor', df['ratio_usage']) df['ratio_usage'] = np.where(df['ratio_usage'].between(0.3,0.0), 'Very Poor', df['ratio_usage']) df['ratio_usage'] = np.where(df['ratio_usage'].between(1.01,2), 'Fatal', df['ratio_usage']) df['ratio_usage'] = np.where(df['ratio_usage'].between(2.1,1000), 'Outliers', df['ratio_usage']) It executes and replaces the first line of code but it generates error such as: TypeError Traceback (most recent call last) &lt;ipython-input-269-7ad3204ddca1&gt; in &lt;module&gt;() 1 df['ratio_usage'] = np.where(df['ratio_usage'].between(0.9,0.1), 'Excellent', df['ratio_usage']) ----&gt; 2 df['ratio_usage'] = np.where(df['ratio_usage'].between(0.8,0.89), 'Very Good', df['ratio_usage']) 3 df['ratio_usage'] = np.where(df['ratio_usage'].between(0.7,0.79), 'Good', df['ratio_usage']) 4 df['ratio_usage'] = np.where(df['ratio_usage'].between(0.6,0.69), 'Fair', df['ratio_usage']) 5 df['ratio_usage'] = np.where(df['ratio_usage'].between(0.5,0.59), 'Satisfactory', df['ratio_usage']) ~\Anaconda\lib\site-packages\pandas\core\series.py in between(self, left, right, inclusive) 3654 """ 3655 if inclusive: -&gt; 3656 lmask = self &gt;= left 3657 rmask = self &lt;= right 3658 else: ~\Anaconda\lib\site-packages\pandas\core\ops.py in wrapper(self, other, axis) 1251 1252 with np.errstate(all='ignore'): -&gt; 1253 res = na_op(values, other) 1254 if is_scalar(res): 1255 raise TypeError('Could not compare {typ} type with Series' ~\Anaconda\li…
has comment: http://stackoverflow.com/comment/88944541
accepted answer: http://stackoverflow.com/a/50974408
tagged with: multiple-conditions
tagged with: range
tagged with: python
score: 2
type: AnsweredQuestion
upvote count: 2
has comment: http://stackoverflow.com/comment/88944589
has comment: http://stackoverflow.com/comment/88944644
has comment: http://stackoverflow.com/comment/88944570
has comment: http://stackoverflow.com/comment/88944601

http://stackoverflow.com/a/50867417
score: 2
has comment: http://stackoverflow.com/comment/88738717
has comment: http://stackoverflow.com/comment/88764186
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50866447
has body: Take the cross-section at each value: for i in df.index.levels[2].unique(): print(df.xs(i, level=2)) Or if it's not important not to have the third level in the index, you can do: for i, j in df.groupby(level=2).groups.items(): print(df.loc[j])
answers question: http://stackoverflow.com/q/50866447
upvote count: 2

http://stackoverflow.com/q/50926509
answer count: 2
has answer: http://stackoverflow.com/a/66963578
has title: Python dfply: unable to mask on multiple conditions
tagged with: dfply
has body: I am an R user learning how to use Python's dfply, the Python equivalent to R's dplyr. My problem: in dfply, I am unable to mask on multiple conditions in a pipe. I seek a solution involving dfply pipes rather than multiple lines of subsetting. My code: # Import import pandas as pd import numpy as np from dfply import * # Create data frame and mask it df = pd.DataFrame({'a':[np.nan,2,3,4,5],'b':[6,7,8,9,np.nan],'c':[5,4,3,2,1]}) df2 = (df &gt;&gt; mask((X.a.isnull()) | ~(X.b.isnull()))) print(df) print(df2) Here is the oringal data frame, df: a b c 0 NaN 6.0 5 1 2.0 7.0 4 2 3.0 8.0 3 3 4.0 9.0 2 4 5.0 NaN 1 And here is the result of the piped mask, df2: a b c 0 NaN 6.0 5 4 5.0 NaN 1 However, I expect this instead: a b c 0 NaN 6.0 5 1 2.0 7.0 4 2 3.0 8.0 3 3 4.0 9.0 2 Why don't the "|" and "~" operators result in rows in which column "a" is either NaN or column "b" is not NaN? By the way, I also tried np.logical_or(): df = pd.DataFrame({'a':[np.nan,2,3,4,5],'b':[6,7,8,9,np.nan],'c':[5,4,3,2,1]}) df2 = (df &gt;&gt; mask(np.logical_or(X.a.isnull(),~X.b.isnull()))) print(df) print(df2) But this resulted in error: mask(np.logical_or(X.a.isnull(),~X.b.isnull()))) ValueError: invalid __array_struct__
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51521730
type: Question
score: 0
tagged with: logical-operators

http://stackoverflow.com/q/50920960
tagged with: dataframe
possible better answer: http://stackoverflow.com/a/50921010
has title: Complex json to pandas dataframe
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/50921072
downvote count: 0
has body: There are lots of question about json to pandas dataframe but none of them solved my issues. I am practicing on this complex json file which looks like this { "type" : "FeatureCollection", "features" : [ { "Id" : 265068000, "type" : "Feature", "geometry" : { "type" : "Point", "coordinates" : [ 22.170376666666666, 65.57273333333333 ] }, "properties" : { "timestampExternal" : 1529151039629 } }, { "Id" : 265745760, "type" : "Feature", "geometry" : { "type" : "Point", "coordinates" : [ 20.329506666666667, 63.675425000000004 ] }, "properties" : { "timestampExternal" : 1529151278287 } } ] } I want to convert this json directly to pandas dataframe using pd.read_json() My Primary Goal is to extract Id, Coordinates and timestampExternal. As this is very complex json, normal way of pd.read_json(), simply doesnt give correct output. Can you suggest me, how can i approach to solve in this kind of situations. Expected output is something like this Id,Coordinates,timestampExternal 265068000,[22.170376666666666, 65.57273333333333],1529151039629 265745760,[20.329506666666667, 63.675425000000004],1529151278287
tagged with: pandas
favorite count: 0
has comment: http://stackoverflow.com/comment/88841386
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50921072
has answer: http://stackoverflow.com/a/50921010
type: AnsweredQuestion
score: 1
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/comment/89015690
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51011245
score: 0
has text: Running the same code on about 100 files takes seconds.

http://stackoverflow.com/q/50983848
upvote count: 1
has body: Have updated the django-rest-framework to last version, why there still have the error? ImportError: No module named 'django.core.urlresolvers' From the post: https://stackoverflow.com/a/47330759/7646621 I have update the djangorestframework to the version 3.8.2. But the issue still exists. File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/rest_framework_docs/urls.py", line 2, in &lt;module&gt; from rest_framework_docs.views import DRFDocsView File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/rest_framework_docs/views.py", line 3, in &lt;module&gt; from rest_framework_docs.api_docs import ApiDocumentation File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/rest_framework_docs/api_docs.py", line 3, in &lt;module&gt; from django.core.urlresolvers import RegexURLResolver, RegexURLPattern ImportError: No module named 'django.core.urlresolvers' my Django version is Version: 2.0.6.
linked to: http://stackoverflow.com/q/47329526
has title: Have updated the django-rest-framework to last version, why there still have the `No module named 'django.core.urlresolvers'` error?
type: UnansweredQuestion
downvote count: 0
score: 1
tagged with: django-rest-framework
favorite count: 0
type: Question
answer count: 2
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/50984036
has answer: http://stackoverflow.com/a/50983880

http://stackoverflow.com/comment/88790051
has text: The error message is coming from rdkit; it stores information in pickle to communicate, and the way that information is structured is versioned. Make sure your rdkit versions *across your cluster* is compatible.
comment on: http://stackoverflow.com/q/50894963
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51011357
accepted answer of: http://stackoverflow.com/q/51011204
has comment: http://stackoverflow.com/comment/89015478
has body: In some programming languages like Matlab, indexes are references with parentheses. In Python, indexes are represented with square brackets. If I have a list, mylist = [1,2,3,4], I reference elements like this: &gt; mylist[1] 2 Wen you say y(idxN), Python thinks you are trying to pass idxN as an argument a function named y.
answers question: http://stackoverflow.com/q/51011204
upvote count: 1
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/89053354
downvote count: 0
score: 1

http://stackoverflow.com/q/50865953
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88734504
has comment: http://stackoverflow.com/comment/88734475
has comment: http://stackoverflow.com/comment/88734459
accepted answer: http://stackoverflow.com/a/50866495
tagged with: parsing
type: Question
tagged with: python
tagged with: regex
has body: I'm parsing through a text a sometimes I get the following {"name":"John","last" : Doe", "Food":"Fries","Coffee" : "Need} I'm dealing with someone else's data here so I just have to deal with it. Is there a possible use of regex expressions (or anything else for that matter) Where I can read through the file and whenever I find unmatched quotations modify the file by matching them. So I can end up with {"name":"John","last" : "Doe", "Food":"Fries","Coffee" : "Need"}
has comment: http://stackoverflow.com/comment/88734738
score: 0
tagged with: http://stackoverflow.com/tag/json
answer count: 1
has answer: http://stackoverflow.com/a/50866495
has comment: http://stackoverflow.com/comment/88734783
has title: How to ensure matched quotations in JSON using Python?
has comment: http://stackoverflow.com/comment/88734912

http://stackoverflow.com/comment/88819374
has text: can you give me two urls ? to try it
score: 0
comment on: http://stackoverflow.com/q/50906465
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88734160
score: 0
has text: Sorry! English is not my mother tongue.
comment on: http://stackoverflow.com/a/50865782
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/88825492
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50900899
score: 1
has text: `_map[target] - set([i, j])` creates a new set, which potentially can be of linear size. I'm not sure if it's possible to construct a bad test case for that, though. My suspicion is that your code has too much Pythonic overhead, like `tuple(sorted(...))` — commenting that out gives 2x speed up for me locally.

http://stackoverflow.com/q/50919440
favorite count: 0
has comment: http://stackoverflow.com/comment/88838774
has title: Python threading. Why are the threads blocking on each other?
has answer: http://stackoverflow.com/a/50919464
accepted answer: http://stackoverflow.com/a/50919464
has body: import threading import time def someMethod(x): time.sleep(20) print(x); def someMethod2(x): time.sleep(1) print(x); t1 = threading.Thread(name="t1", target=someMethod(1)); t2 = threading.Thread(name="t2", target=someMethod2(2)); t1.start(); t2.start(); I'd expect the output to be 2 followed by 1 but it is 1 followed by 2. Total time is 21 seconds. How can I make it run in parallel so the output is 2 followed by 1 and both threads run in parallel so the total time is 20 units?
tagged with: python
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/88839583
duplicate of: http://stackoverflow.com/q/11792629
type: Question
upvote count: 1
linked to: http://stackoverflow.com/q/11792629
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/88873502
comment on: http://stackoverflow.com/q/50937464
type: QuestionComment
type: Comment
has text: @DyZ: I'm not so sure that applies here. Nowhere in the posted code is a module being called.
score: 0

http://stackoverflow.com/a/50862758
score: 2
has comment: http://stackoverflow.com/comment/88729207
downvote count: 0
has body: import time print(time.strftime("%Y-%m-%dT%H:%M:%S%z"))
upvote count: 2
has comment: http://stackoverflow.com/comment/88729723
has comment: http://stackoverflow.com/comment/88729047
has comment: http://stackoverflow.com/comment/88729301
has comment: http://stackoverflow.com/comment/88728149
type: Answer
has comment: http://stackoverflow.com/comment/88728989
answers question: http://stackoverflow.com/q/50862720

http://stackoverflow.com/a/50980543
upvote count: 0
score: -2
type: Answer
has body: This Should Help #request said user input x= input("Please Press 1 to continue Or 2 to Exit") #use a While loop While True: #then an if statement if x==1: #call your function printit() else:break This should Do the trick
downvote count: 2
answers question: http://stackoverflow.com/q/50980461

http://stackoverflow.com/a/50961890
type: Answer
upvote count: 1
score: 1
has body: You can convert your DataFrame to a numpy array and pass as input # convert class labels in numerical data, assuming you have two classes df['Level'].replace(['Low Level'],0) df['Level'].replace(['High Level'],1) # extra data and class labels data = df'Salary','LoanAmt' target = df['Level'] # convert df to numpy arrays data = data.values target = target.values # you would ideally want to do a test train split. #Train the model on training data and test on the test data for accuracy #pass in fit function neigh = KNeighborsClassifier(n_neighbors=5,algorithm='auto') neigh.fit(data,target) ## how to passs the parameters here? Some useful links: Convert pandas dataframe to numpy array, preserving index Replacing few values in a pandas dataframe column with another value Selecting columns in a pandas dataframe
answers question: http://stackoverflow.com/q/50961658
has comment: http://stackoverflow.com/comment/88922102
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50961658
has comment: http://stackoverflow.com/comment/88921308
downvote count: 0
has comment: http://stackoverflow.com/comment/88920606

http://stackoverflow.com/q/50908196
score: 0
has answer: http://stackoverflow.com/a/67564802
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/50908316
has comment: http://stackoverflow.com/comment/88816165
has answer: http://stackoverflow.com/a/50908316
tagged with: python
has answer: http://stackoverflow.com/a/50908238
answer count: 4
has body: I am trying to learn to use this simple birthday one-liner in Python (3.6.5) but am getting SyntaxError: invalid syntax, can someone help me figure out where I've gone wrong: print map(lambda x: "Happy Birthday to " + ("you" if x != 2 else "dear Name"),range(4)) Thanks!
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88816200
linked to: http://stackoverflow.com/q/32583304
has title: Syntax error with Python birthday code
type: Question
has answer: http://stackoverflow.com/a/50908449
accepted answer: http://stackoverflow.com/a/50908238

http://stackoverflow.com/comment/89024712
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50920974
has text: Don't do frame = cv2.imread(frame) . I wrote wrong i guess. just remove this step

http://stackoverflow.com/q/50956659
tagged with: python
tagged with: psycopg2
has title: ModuleNotFoundError on psycopg2 only on compiled script
score: 3
downvote count: 0
has answer: http://stackoverflow.com/a/50981062
type: Question
has body: I am currently working through a tutorial on database entry using psycopg2 but I can't seem to get my script to find it. Used pip install and my script is written in Atom. When I import psycopg2 in the command prompt it works fine but my Atom script wont run: ATOM SCRIPT import sys sys.path.append('c:\\users\j.meiring\appdata\local\programs\python\python36-32\lib\site-packages') print(sys.path) import psycopg2 def create_table(): conn=psycopg2.connect("dbname='database1' user='postgres' password='postgres123' host='localhost' port='5432'") cur=conn.cursor() cur.execute("CREATE TABLE IF NOT EXISTS store (item TEXT, quantity INTEGER, price REAL)") conn.commit() conn.close() def insert(item,quantity,price): conn=psycopg2.connect("lite.db") cur=conn.cursor() cur.execute("INSERT INTO store VALUES (?,?,?)",(item,quantity,price)) conn.commit() conn.close() def view(): conn=psycopg2.connect("lite.db") cur=conn.cursor() cur.execute("SELECT * FROM store") rows=cur.fetchall() conn.close() return rows def delete(item): conn=psycopg2.connect("lite.db") cur=conn.cursor() cur.execute("DELETE FROM store WHERE item=?",(item,)) conn.commit() conn.close() def update(quantity,price,item): conn=psycopg2.connect("lite.db") cur=conn.cursor() cur.execute("UPDATE store SET quantity=?, price=? WHERE item=?",(quantity,price,item,)) conn.commit() conn.close() create_table() #print(view()) CMD OUTPUT C:\Users\J.Meiring\Documents\Py\Database&gt;script2.py ['C:\\Users\\J.Meiring\\Documents\\Py\\Database', 'C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python36_64\\python36.zip', 'C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python36_64\\DLLs', 'C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python36_64\\lib', 'C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python36_64', 'C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python36_64\\lib\\site-packages', 'c:\\users\\j.meiring\x07ppdata\\local\\programs\\python\\python36-32\\lib\\site-packages'…
tagged with: python-3.6
upvote count: 3
tagged with: atom-editor
answer count: 1
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion

http://stackoverflow.com/comment/88794470
comment on: http://stackoverflow.com/q/50896980
score: 0
type: Comment
type: QuestionComment
has text: Your example would be a lot better if it used integers for indexing and worked.

http://stackoverflow.com/comment/88813098
has text: Sorry, I meant can you [edit your question](https://stackoverflow.com/posts/50905695/edit) to include a few lines of data.
score: 0
comment on: http://stackoverflow.com/q/50905695
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90669104
type: Comment
type: QuestionComment
score: 0
has text: Also I am confused by PATH variable, what do you mean exactly? The path to the exe I package in the msi? If so `C:\TestProgram\bin` @Bachrc
comment on: http://stackoverflow.com/q/50880639

http://stackoverflow.com/q/50942796
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/88996119
has comment: http://stackoverflow.com/comment/88883327
tagged with: python-3.6
has body: I've recently stumbled upon a weird behavior of the mutable class attributes. Theoretically (and practically), a mutable argument defined on a class level will be shared within all instances until any instance will overwrite the reference. In our project, we have directory structure similar to below: ├─── main.py └─── src ├─── __init__.py ├─── cache_user.py └─── common_cache.py common_cache.py: class CommonCache: cache = {} cache_user.py: from .common_cache import CommonCache class CacheUser(CommonCache): pass main.py: from src.cache_user import CacheUser from src.common_cache import CommonCache common_cache = CommonCache() cache_user = CacheUser() print(id(common_cache.cache)) print(id(CommonCache.cache)) print(id(cache_user.cache)) print(id(CacheUser.cache)) Result of running main.py: 2163305605304 2163305605304 2163305605304 2163305605304 All ID's are the same as expected which proves, that all instances and classes are sharing common reference to the same dictionary. However, when we add src directory into PYTHONPATH and slightly change imports, something weird will happen. cache_user.py: from src.common_cache import CommonCache class CacheUser(CommonCache): pass main.py from cache_user import CacheUser from common_cache import CommonCache common_cache = CommonCache() cache_user = CacheUser() print(id(common_cache.cache)) print(id(CommonCache.cache)) print(id(cache_user.cache)) print(id(CacheUser.cache)) Result of running main.py: 2067930459016 2067930459016 2067930458440 2067930458440 Now, CommonCache (and instances) have their own cache dictionary, different from CacheUser (and instances). What happened? The only thing that changes is the method how we do imports. If we will put breakpoint in CommonCache class we can clearly see, that cache = {} is executed twice - once per import. If we would have more than one class that does import of CommonCache, only the distinct import methods will trigger cache = {}. Solving this issue in our project wasn't just unifyin…
answer count: 1
tagged with: python
favorite count: 0
type: UnansweredQuestion
score: 2
has title: Mutable class attributes with different importing strategies
downvote count: 0
has answer: http://stackoverflow.com/a/51001531

http://stackoverflow.com/q/50870437
has comment: http://stackoverflow.com/comment/88742527
tagged with: tensorflow
tagged with: neural-network
type: UnansweredQuestion
score: -3
tagged with: deep-learning
upvote count: 0
has answer: http://stackoverflow.com/a/50870611
favorite count: 0
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/88742566
has comment: http://stackoverflow.com/comment/88742462
has comment: http://stackoverflow.com/comment/88742495
linked to: http://stackoverflow.com/q/35400065
has title: Multiclass Text Classification of Wikipedia Articles
has comment: http://stackoverflow.com/comment/88742674
has body: I have a collection of Wikipedia dumps. I need to classify them in a list of categories that I have. The categories are like, Sports, Law, Music, Movie, etc. There are around 300 categories. I extracted the descriptions from the articles, and the category list of the articles. What I observed is that the nouns in the descriptions give a pretty good idea of the entity. For example, the first sentence of the description is the most important. For example, in "Christiano Ronaldo is a Portuguese professional footballer", footballer is a noun. Also in the list of categories on Ronaldo's wikipedia page, the words 'footballer' and 'football' are repeated multiple times. Considering that, I cleaned all the description using Natural Language Processing and extracted only the nouns out of the data. Overall, there would be 20,000 different words (nouns) in the complete corpus of the data that I have. As mentioned before, there are around 300 classes. What I've done till now is pretty basic. I extract the nouns from the data about an entity. Then I process them with NLP techniques like stemming. Then I use GloVe to get vectors of the most common nouns in the description, and the categories. Then I find the category with the nearest cosine distance of the vectors representing the common word and the category. For example, if the most common word in the data about an entity is 'Novel'. Then the cosine distance of the word 'Novel' and the category 'Book' is small and I output that the entity is a 'Book'. But this gives an accuracy of around 60% which is not good. Hence, I would like to use Deep Learning using Tensorflow, or some other library that does the classification for me. My input vector would be of the form [0,1,0,6,0,...,10,0,..] of width 20,000, the number of distinct words, where each index corresponds to the frequency of the word (this is important as frequency is of prime importance for me) occurring in the description. The output should be of the form [0.12, 0.2, 0.0…
downvote count: 3
tagged with: text-classification
answer count: 1

http://stackoverflow.com/comment/88987635
score: 0
has text: How do I do that?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50996623

http://stackoverflow.com/comment/88954681
has text: It says there, `ValueError: time data '2018-01-01' does not match format '%d, %m, %Y'`. Change your format to `'%Y-%m-%d'`, and it should work fine. Example: `datetime.strptime('2018-01-01', '%Y-%m-%d')`
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50979354

http://stackoverflow.com/comment/89017096
type: AnswerComment
score: 0
type: Comment
has text: Thank you, I have changed it to w+ and it start working good)
comment on: http://stackoverflow.com/a/51010827

http://stackoverflow.com/comment/89098810
has text: wouldn't [`visibility_of_all_elements_located`](https://selenium-python.readthedocs.io/api.html) be enough??
comment on: http://stackoverflow.com/a/50951755
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/50953938
has body: Could you try to downgrade "boto3" package to see if there is no issue there? Get available versions: pip install boto3==some_nonsense_word Then: pip uninstall boto3 Finally: pip install boto3==&lt;VERSION&gt; Answer based on the findings from the following GitHub issue comment: https://github.com/ansible/ansible-modules-core/issues/2014#issuecomment-144620598
type: Answer
upvote count: 4
downvote count: 0
answers question: http://stackoverflow.com/q/50953465
score: 4

http://stackoverflow.com/q/50963625
has comment: http://stackoverflow.com/comment/88923857
has answer: http://stackoverflow.com/a/55653655
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/67743676
type: UnansweredQuestion
tagged with: spyder
tagged with: python
answer count: 4
has body: I'm using Python 3.6 through Spyder in Anaconda3. I have both the Anaconda installation and a "clean" python installation. Before I installed the "clean" python, when I ran the Python -V command in cmd I got the following version description Python 3.6.5 :: Anaconda, Inc. Now when I run the command it just says Python 3.6.5. and the pip list is a whole lot shorter. When ever I open Spyder and find some package that I don't have... how would I go about installing said package? If I just open cmd and write pip install ... it will install in the "clean" python directory. How do I tell it to connect to Spyder?
linked to: http://stackoverflow.com/q/20994716
has answer: http://stackoverflow.com/a/60371824
tagged with: pip
type: Question
tagged with: anaconda
upvote count: 12
has answer: http://stackoverflow.com/a/52729167
score: 12
has title: Pip install in Spyder

http://stackoverflow.com/a/50880692
has body: a. If you want to reinstall a package you can always uninstall the package and reinstall it with the following. pip uninstall requests pip install requests b. If you are seeing "Requirement already satisfied" inside of your vanilla python installation then it must already be installed there. You can check the packages that are installed by running the following. (you can run this on your virtual environment and your vanilla python installation to compare the results) pip freeze defusedxml==0.5.0 isodate==0.6.0 lxml==4.2.1 pkgconfig==1.3.1 python3-saml==1.4.1 six==1.11.0 xmlsec==1.3.3
downvote count: 0
has comment: http://stackoverflow.com/comment/88827633
score: 1
answers question: http://stackoverflow.com/q/50874361
has comment: http://stackoverflow.com/comment/88862323
upvote count: 1
has comment: http://stackoverflow.com/comment/88855663
has comment: http://stackoverflow.com/comment/88790495
type: Answer
has comment: http://stackoverflow.com/comment/88861710

http://stackoverflow.com/q/50942291
tagged with: string
has comment: http://stackoverflow.com/comment/88882136
has comment: http://stackoverflow.com/comment/88882093
tagged with: datetime
tagged with: python
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/50942380
has body: I have the following text file that has these lists : ['2009-08-31 23:58:06 ', '1'] ['2009-08-31 23:58:06 ', '1'] ['2009-08-31 23:58:06 ', '0'] ['2009-08-31 23:58:06 ', '1'] ['2009-08-31 23:58:06 ', '1'] ['2009-08-31 23:58:06 ', '1'] ['2009-08-31 23:58:06 ', '1'] ['2009-08-31 23:58:06 ', '1'] ['2009-08-31 23:58:06 ', '1'] ['2009-08-31 23:58:06 ', '1'] ['2009-08-31 23:58:06 ', '1'] ['2009-08-31 23:58:07 ', '1'] ['2009-08-31 23:58:07 ', '1'] ['2009-08-31 23:58:07 ', '1'] The second element is an integer, however, the first element is a string. I need the first element of each lis to be a date instead of string? I tried this code: word[0]=datetime.strptime(word[0],'%Y/%m/%d %H:%M:%S') but I get this error: ValueError: time data '2009-04-02 22:50:06 ' does not match format '%Y/%m/%d %H:%M:%S' the current code I have that cleans the data is the following: with open('newdata.txt') as f: for line in f: tweet=re.sub(r'T\t',"",line) t=re.sub(r'W\t',"\/\/",tweet) data=t.split("\/\/") sentiment_value= s.sentiment(data[1]) data.append(sentiment_value) words = [w.replace('pos', '1') for w in data] word=[w.replace('neg','0')for w in words] del word[1] print(word)
has comment: http://stackoverflow.com/comment/88919514
has title: How can I change the first element in a list from string to date format?
type: Question
has answer: http://stackoverflow.com/a/50942429
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/50942372
accepted answer: http://stackoverflow.com/a/50942372
possible better answer: http://stackoverflow.com/a/50942380

http://stackoverflow.com/q/50992405
type: Question
answer count: 2
has body: I am developping a module to use a custom formula for the amount calculation method in invoices and sales orders. The line amount formula should be : nbJours * price_unit * quantity instead of the default formula : price_unit * quantity I added a custom field to AccountInvoiceLine class by inheriting it as following : class AccountInvoiceLine(models.Model): _inherit = "account.invoice.line" # Nombre de jours de location nombreJours = fields.Integer("Nombre de jours",default=1,required=True) @api.multi @api.depends('nombreJours','price_unit', 'discount', 'invoice_line_tax_ids', 'quantity', 'product_id', 'invoice_id.partner_id', 'invoice_id.currency_id', 'invoice_id.company_id', 'invoice_id.date_invoice', 'invoice_id.date') def _compute_price(self): ... ... if self.invoice_line_tax_ids: taxes = self.invoice_line_tax_ids.compute_all(self.nombreJours, price, currency, self.quantity, product=self.product_id, partner=self.invoice_id.partner_id) # Calcul du sous-total de la ligne self.price_subtotal = price_subtotal_signed = taxes['total_excluded'] if taxes else self.quantity * price * self.nombreJours self.price_total = taxes['total_included'] if taxes else self.price_subtotal ... ... And I also need to set the custom formula in the AccountTax class. I tried to override the compute_all() method : # Modification du modèle de Taxes class AccountTax(models.Model): _inherit = 'account.tax' @api.multi def compute_all(self, nbJrs=1, price_unit=1, currency=None, quantity=1.0, product=None, partner=None): ... ... if not base_values: odooAmount = price_unit * quantity customAmount = nbJrs * odooAmount total_excluded = total_included = base = round( customAmount , prec) else: total_excluded, total_included, base = base_values ... ... return { 'taxes': sorted(taxes, key=lambda k: k['sequence']), 'total_excluded': currency.round(total_excluded) if round_total else total_excluded, 'total_included': currency.round(total_included) if round_total else total_included, 'base': base, } I've…
favorite count: 0
has answer: http://stackoverflow.com/a/51020199
score: 0
has comment: http://stackoverflow.com/comment/89032999
possible better answer: http://stackoverflow.com/a/51020199
has title: Odoo 11 How to override compute_all() method?
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88981435
has answer: http://stackoverflow.com/a/51051399
upvote count: 1
tagged with: python
downvote count: 1
type: AnsweredQuestion
tagged with: odoo-11
accepted answer: http://stackoverflow.com/a/51051399
tagged with: odoo

http://stackoverflow.com/q/50913464
type: Question
score: 3
has answer: http://stackoverflow.com/a/50913950
has comment: http://stackoverflow.com/comment/88828458
has answer: http://stackoverflow.com/a/66346820
tagged with: sqlalchemy
has title: Flask sqlAlchemy: Creating models for the existing database structure
has body: I am new to sqlAlchemy and I wonder if there is a way create a class that would be mapped to the existing table in DB without specifying any columns of the table (but all columns could be accessed as attributes of the object)?
answer count: 2
downvote count: 0
tagged with: flask-sqlalchemy
favorite count: 0
has comment: http://stackoverflow.com/comment/88827715
tagged with: python
has comment: http://stackoverflow.com/comment/88828005
tagged with: python-3.x
linked to: http://stackoverflow.com/q/17652937
upvote count: 3
type: UnansweredQuestion

http://stackoverflow.com/q/51008666
tagged with: sockets
tagged with: python
has title: How to set host header field in a syslog message?
has body: A third party monitoring app expects the host header to be set to a certain value in order to recognise the message I send it (it defaults to localhost when sending locally). So I need to set it manually. My syslog message is sent via simple python socket connection (socket.send) and I have tried prepending date time followed by host to the message string I pass in as parameter. However the 3rd party system still detects it as localhost, indicating that is not setting the header. How do I set the header of a syslog message via python?
type: Question
tagged with: syslog
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/51008937
type: UnansweredQuestion

http://stackoverflow.com/q/50952937
accepted answer: http://stackoverflow.com/a/54706465
type: Question
tagged with: mqtt
tagged with: mosquitto
has comment: http://stackoverflow.com/comment/89866536
tagged with: python
has title: TLS certificate validation failure
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/89487904
has answer: http://stackoverflow.com/a/54706465
tagged with: ssl
has comment: http://stackoverflow.com/comment/89553486
type: AnsweredQuestion
has body: I set up a Mosquitto broker in a Raspberry Pi and created self-signed TLS server certificate with OpenSSL. Configuration works as I can connect successfully with Moquitto client from terminal, as well as from MQTTBox and MQTT.fx. However when trying to connect with Python and Paho-MQTT following error import paho.mqtt.client as mqtt # SETTINGS &amp; CONSTANTS (...) TLS_CA = "./tls/mqtt.crt" # MQTT CALLBACKS (...) # INIT &amp; CONNECT CLIENT client = mqtt.Client(DEVICE_ID) (...) client.tls_set(TLS_CA) client.username_pw_set(MQTT_USER, MQTT_PSWD) client.connect(MQTT_HOST, MQTT_PORT, MQTT_KEEPALIVE) I get the following error: File "/usr/lib/python3.4/ssl.py", line 804, in do_handshake self._sslobj.do_handshake() ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:600) I've tried many things: 1) Insert self-signed certificate into Raspbian ca-certificates sudo mkdir /usr/local/share/ca-certificates/extra sudo cp mqtt.crt /usr/local/share/ca-certificates/extra/mqtt.crt sudo update-ca-certificates 2) Play with Paho's tls_set() options. I think ca_certs=mqtt.crt and tls_version=ssl.PROTOCOL_TLSv1 should be enough. 3) Use tls_insecure_set(True). I know this is not a valid solution, but I just wanted to try if something happen. Result is still CERTIFICATE_VERIFY_FAILED error 4) Use Python 2.7.9 and Python 3.4.2 I've actually run out of ideas
downvote count: 0
score: 1
favorite count: 0

http://stackoverflow.com/a/50963610
downvote count: 0
type: Answer
score: 2
upvote count: 2
has body: To better illustrate my comment here is an example. This is the image: Performing dilation using a kernel of size 5 x 5: kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5)) dilation = cv2.dilate(img, kernel, iterations = 1) cv2.imshow('dilation', dilation) This is the result:
accepted answer of: http://stackoverflow.com/q/50961110
answers question: http://stackoverflow.com/q/50961110
type: AcceptedAnswer

http://stackoverflow.com/q/51006126
has title: How to Optimize Diagonal Movement Code for Chess Engine?
answer count: 1
downvote count: 1
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89005800
tagged with: python
tagged with: chess
tagged with: loops
has body: I'm currently in the process of building my own chess engine and could really use some suggestions on how to make this segment of code for calculating diagonal moves more efficient. (This is obviously only for diagonals going Up-Right) As of now I'm using "Try-Except" to iterate by 1, and then my return statement filters out any off-board values. However this seems like a very bulky way of doing things. Any comments or advice on how to refactor this code would be greatly appreciated. import argparse, json chessBoard = [[1, 1, 1, 1, 1, 1, 1, 1] for i in range(8)] chess_map_from_alpha_to_index = { "a" : 0, "b" : 1, "c" : 2, "d" : 3, "e" : 4, "f" : 5, "g" : 6, "h" : 7 } chess_map_from_index_to_alpha = { 0: "a", 1: "b", 2: "c", 3: "d", 4: "e", 5: "f", 6: "g", 7: "h" } def getBishopMoves(pos, chessBoard): column, row = list(pos.strip().lower()) row = int(row) - 1 column = chess_map_from_alpha_to_index[column] i,j = row, column solutionMoves = [] #Up-Right Diagonal try: temp = chessBoard[i + 1][j + 1] solutionMoves.append([i + 1, j + 1]) except: pass try: temp = chessBoard[i + 2][j + 2] solutionMoves.append([i + 2, j + 2]) except: pass try: temp = chessBoard[i + 3][j + 3] solutionMoves.append([i + 3, j + 3]) except: pass try: temp = chessBoard[i + 4][j + 4] solutionMoves.append([i + 4, j + 4]) except: pass try: temp = chessBoard[i + 5][j + 5] solutionMoves.append([i + 5, j + 5]) except: pass try: temp = chessBoard[i + 6][j + 6] solutionMoves.append([i + 6, j + 6]) except: pass try: temp = chessBoard[i + 7][j + 7] solutionMoves.append([i + 7, j + 7]) except: pass try: temp = chessBoard[i + 7][j + 7] solutionMoves.append([i + 7, j + 7]) except: pass temp = [i for i in solutionMoves if i[0] &gt;=0 and i[1] &gt;=0] solutionMoves = ["".join([chess_map_from_index_to_alpha[i[1]], str(i[0] + 1)]) for i in temp] solutionMoves.sort() return solutionMoves
type: Question
has comment: http://stackoverflow.com/comment/89005676
has comment: http://stackoverflow.com/comment/89007939
tagged with: optimization
score: 0
tagged with: try-except
upvote count: 1
has answer: http://stackoverflow.com/a/51006220

http://stackoverflow.com/comment/121189017
has text: Never mind! I've figured they're Defined Names. They define ranges in that case
type: AnswerComment
comment on: http://stackoverflow.com/a/50934874
type: Comment
score: 0

http://stackoverflow.com/q/50888847
has answer: http://stackoverflow.com/a/50888880
tagged with: python
has body: I have created agebin column from age column. I had created agebin by using pd.cut() check below: traindata = data.assign(age_bins = pd.cut(data.age, 4, retbins=False,labels=range(1, 5), include_lowest=True)) data['agebin'] = traindata['age_bins'] Now when I see data.info then agebin has dtype category and I want it to be numerical data because I am getting Value error while training model. How can I convert dtype:category to numerical. I am confused how dtype is categorical because when I see data['agebin'].head() all values are 1,2,3 or 4 but in data.info it is showing agebin as categorical. I want to change agebin from categorical to numerical dtype.
type: AnsweredQuestion
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/50888880
type: Question
downvote count: 0
has title: How to convert dtype categorical variable to numerical?
answer count: 2
possible better answer: http://stackoverflow.com/a/50888961
tagged with: pandas
has answer: http://stackoverflow.com/a/50888961
favorite count: 0

http://stackoverflow.com/a/50942967
has body: def clean_word(word): replace_list = [':','.',',','!','?'] new_word = '' for x in word: if x not in replace_list: new_word += x return new_word print(clean_word('Hello!')) Output Hello
score: 0
answers question: http://stackoverflow.com/q/50942814
type: Answer

http://stackoverflow.com/q/51008140
downvote count: 1
has answer: http://stackoverflow.com/a/51008161
answer count: 4
tagged with: function
upvote count: 5
has body: I would like to write a function in which the default value of one argument is a function of some arguments that are being passed to the same function. Something like this: def function(x, y = function2(x)): ##definition of the function Is it possible to write such a function in Python? I came across this answer for c++. But there is no method overloading in Python Thanks in advance.
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51008181
tagged with: arguments
favorite count: 0
type: Question
tagged with: python
linked to: http://stackoverflow.com/q/17978790
score: 4
accepted answer: http://stackoverflow.com/a/51008181
has answer: http://stackoverflow.com/a/51008270
has title: Python - Pass default values for arguments that are function of other arguments of the function
possible better answer: http://stackoverflow.com/a/51008161
has answer: http://stackoverflow.com/a/51008347

http://stackoverflow.com/comment/89018274
type: Comment
type: QuestionComment
has text: tested with the user : 'pi", tested with 'sudo'
comment on: http://stackoverflow.com/q/51008386
score: 0

http://stackoverflow.com/comment/133663168
comment on: http://stackoverflow.com/a/67381701
has text: Very good point! I did not check the under-lying code, in this case it makes no real sense to use the `more_itertools.consume()` to have better performance.
type: AnswerComment
score: 0
type: Comment

list
tags question: http://stackoverflow.com/q/50979600
type: Tag
tags question: http://stackoverflow.com/q/50905050
tags question: http://stackoverflow.com/q/50891043
tags question: http://stackoverflow.com/q/50927952
tags question: http://stackoverflow.com/q/50881526
tags question: http://stackoverflow.com/q/50914381
tags question: http://stackoverflow.com/q/50929995
tags question: http://stackoverflow.com/q/50998417
tags question: http://stackoverflow.com/q/50928229
tags question: http://stackoverflow.com/q/50901552
tags question: http://stackoverflow.com/q/50865164
tags question: http://stackoverflow.com/q/50884248
tags question: http://stackoverflow.com/q/50864868
tags question: http://stackoverflow.com/q/50926411
tags question: http://stackoverflow.com/q/50904444
tags question: http://stackoverflow.com/q/50945517
tags question: http://stackoverflow.com/q/50960343
tags question: http://stackoverflow.com/q/50959718
tags question: http://stackoverflow.com/q/50883894
tags question: http://stackoverflow.com/q/50896944
tags question: http://stackoverflow.com/q/50975022
tags question: http://stackoverflow.com/q/50883576
tags question: http://stackoverflow.com/q/50964622
tags question: http://stackoverflow.com/q/50983773
tags question: http://stackoverflow.com/q/50871840
tags question: http://stackoverflow.com/q/50919887
tags question: http://stackoverflow.com/q/50905021
tags question: http://stackoverflow.com/q/50887460
tags question: http://stackoverflow.com/q/50980264
tags question: http://stackoverflow.com/q/50987777
tags question: http://stackoverflow.com/q/50952758
tags question: http://stackoverflow.com/q/50992584
tags question: http://stackoverflow.com/q/50984179
tags question: http://stackoverflow.com/q/50956456
tags question: http://stackoverflow.com/q/50943979
tags question: http://stackoverflow.com/q/50904470
tags question: http://stackoverflow.com/q/50939121
tag name: list
tags question: http://stackoverflow.com/q/50967329
tags question: http://stackoverflow.com/q/50974811
tags question: http://stackoverflow.com/q/50868960
tags question: http://stackoverflow.com/q/50993064
tags question: http://stackoverflow.com/q/50946655
tags question: http://stackoverflow.com/q/50985836
tags question: http://stackoverflow.com/q/50952086
tags question: http://stackoverflow.com/q/51002266
tags question: http://stackoverflow.com/q/51003118
tags question: http://stackoverflow.com/q/50897520
tags question: http://stackoverflow.com/q/50871688
tags question: http://stackoverflow.com/q/50955782
tags question: http://stackoverflow.com/q/50997898
tags question: http://stackoverflow.com/q/50886409
tags question: http://stackoverflow.com/q/50926951
tags question: http://stackoverflow.com/q/50917398
tags question: http://stackoverflow.com/q/50988918
tags question: http://stackoverflow.com/q/50874350
tags question: http://stackoverflow.com/q/50946298
tags question: http://stackoverflow.com/q/50981037
tags question: http://stackoverflow.com/q/50935165
tags question: http://stackoverflow.com/q/50926669
tags question: http://stackoverflow.com/q/50935495
tags question: http://stackoverflow.com/q/50992407
tags question: http://stackoverflow.com/q/50970824
tags question: http://stackoverflow.com/q/50923069
tags question: http://stackoverflow.com/q/50935910
tags question: http://stackoverflow.com/q/50934086
tags question: http://stackoverflow.com/q/50962666
tags question: http://stackoverflow.com/q/50933895
tags question: http://stackoverflow.com/q/50887066
tags question: http://stackoverflow.com/q/50977801
tags question: http://stackoverflow.com/q/50976797
tags question: http://stackoverflow.com/q/50880165
tags question: http://stackoverflow.com/q/50890405
tags question: http://stackoverflow.com/q/50929265
tags question: http://stackoverflow.com/q/50972571
tags question: http://stackoverflow.com/q/50858477
tags question: http://stackoverflow.com/q/50886076
tags question: http://stackoverflow.com/q/50880762
tags question: http://stackoverflow.com/q/50861252

http://stackoverflow.com/a/50956684
downvote count: 0
has comment: http://stackoverflow.com/comment/88911885
has comment: http://stackoverflow.com/comment/88912062
type: Answer
has comment: http://stackoverflow.com/comment/88911112
upvote count: 3
has body: def combine(some_list): current_group = 0 # starts with 0 g_size = 0 # current group size for elem in some_list: g_size += 1 if elem.startswith('U-') and g_size &gt; 1: g_size = 1 current_group += 1 yield '{}{}'.format(current_group, elem) if elem.startswith(('L-', 'U-')): # each L- or U- also finishes a group g_size = 0 current_group += 1 &gt;&gt;&gt; List = ["B-Guild","I-Guild","I-Guild","L-Guild","B-Gene","L-Gene","U-Car"] &gt;&gt;&gt; print(list(combine(List))) &gt;&gt;&gt; List = ["B-Guild","I-Guild","I-Guild","L-Guild","B-Guild","L-Guild","U-Guild"] &gt;&gt;&gt; print(list(combine(List)))
has comment: http://stackoverflow.com/comment/88911049
has comment: http://stackoverflow.com/comment/88912375
score: 3
has comment: http://stackoverflow.com/comment/88911188
accepted answer of: http://stackoverflow.com/q/50956456
answers question: http://stackoverflow.com/q/50956456
type: AcceptedAnswer

http://stackoverflow.com/q/50941081
type: Question
has title: Extracting pdf links from given list of Links using regular expressions
has answer: http://stackoverflow.com/a/50941276
linked to: http://stackoverflow.com/q/1080411
accepted answer: http://stackoverflow.com/a/50941806
linked to: http://stackoverflow.com/q/1732348
has body: I have a list of links stored as a LIST. But I need to extract only the PDF links. links = [ ' ', ' '] So I need to extract only the link starting from 'https' and and ending with pdf as given below https://www.samplewebsite.com/xml-data/abcdef/higjkl/Thisisthe-required-document-b4df-16t9g8p93808.pdf And store this link in a list. There are many pdf links in the variable 'links'. Need to store all the pdf links in the variable named 'pdf_links' Can anyone suggest me regular expression to extract this pdf link ? I have used the below regular expression but its not working. pdf_regex = r""" (^<a\sclass="tablebluelink"\shref="(.)+.pdf"$)"""
answer count: 3
tagged with: http://stackoverflow.com/tag/pdf
favorite count: 0
tagged with: python-3.x
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/50941482
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50941806
upvote count: 2
score: 1
possible better answer: http://stackoverflow.com/a/50941482
downvote count: 1

http://stackoverflow.com/a/50995646
type: Answer
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/50995612
downvote count: 0
has body: The else line must be indented at the same level as the if statement. Indentation is key in python. Try this: N=8 if N % 2 ==1 and N &gt;= 6 and N &lt;20: print("Weird") else: print ("Not weird")

http://stackoverflow.com/q/50920705
has comment: http://stackoverflow.com/comment/88910089
type: UnansweredQuestion
has body: My Dockerfile is: FROM python:3.5 RUN apt-get update USER root WORKDIR /app ADD . /app RUN pip install -r requirements.txt WORKDIR /app/etalentNET EXPOSE 8000 CMD ["python", "manage.py", "makemigrations"] CMD ["python", "manage.py", "migrate"] CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] My docker-compose.yaml is: version: '3' services: db: image: sqlite3 web: build: image: demo:latest dockerfile: Dockerfile command: python3 manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db When I run docker run -p 8000:8000 demo it doesn't do anything. CONTAINER ID IMAGE COMMAND CREATED STATUS 4829d420c560 demo "python manage.py ru…" 9 minutes ago Exited (0) But when I run docker run -p 8000:8000 -it demo bash and then there python manage.py runserver 0.0.0.0:8000 the servers start running (but can't access it via <host_ip>:8000. I don't know why). I'm running in a Google Cloud Compute Engine virtual machine with Ubuntu 16.04, and Django-2.0.6.
tagged with: django
tagged with: google-compute-engine
tagged with: python
has comment: http://stackoverflow.com/comment/88987538
has comment: http://stackoverflow.com/comment/88840903
has comment: http://stackoverflow.com/comment/88841293
has comment: http://stackoverflow.com/comment/88897427
tagged with: dockerfile
has answer: http://stackoverflow.com/a/50925123
type: Question
has title: Django not running from Docker image, cant access
has comment: http://stackoverflow.com/comment/88840975
tagged with: docker
has comment: http://stackoverflow.com/comment/88841010
score: 0
answer count: 1

http://stackoverflow.com/comment/88757660
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50877755
has text: yes what chepner said (almost) `[link.format(page, 10*(page-1)) for page in range(2, 4)]`

http://stackoverflow.com/comment/88733470
comment on: http://stackoverflow.com/q/50865440
score: 1
type: Comment
type: QuestionComment
has text: @sedders123 It's not quite the same, because `remove` removes just the first instance, not all of them, and it does it in-place, and it raises an exception if nothing was removed, and the simple listcomp answer to that question won't handle any of those.

http://stackoverflow.com/q/50942550
linked to: http://stackoverflow.com/q/50310515
tagged with: oop
has comment: http://stackoverflow.com/comment/88882861
score: 1
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/50943008
answer count: 2
has comment: http://stackoverflow.com/comment/88882745
downvote count: 0
has answer: http://stackoverflow.com/a/50943553
has body: What is the correct way to keep tensorflow session alive between different methods of a class, with variable initialization only at the time of object creation ? If i initialize within the fit method, then i cant use that learned model later for predict method currently i am doing this class AlexNet_model: def __init__(self): self.sess = tf.Session() init = tf.global_variables_initializer() self.sess.run(init) and then withing the same class i am calling the fit method def fit(self, x, y, num_epochs = 20): X, Y = self.create_placeholders() Z = self.AlexNet(X) cost = self.cost_fn(Z, Y) opt = self.optimizer(cost) tot_cost = [] for epoch in range(num_epochs): epoch_cost = 0 mini_batches_X, mini_batches_Y = getRandomMiniBatches(train_x, train_y) for i in range(len(mini_batches_X)): mb_x = mini_batches_X[i] mb_y = np.array(mini_batches_Y[i]) temp_Z, _, temp_cost = self.sess.run([Z, opt, cost], feed_dict = {X:mb_x, Y:mb_y.reshape(-1, 1)}) epoch_cost += temp_cost / len(mini_batches_X) print('epoch : {0} \t cost : {1}'.format(epoch, epoch_cost)) tot_cost.append(epoch_cost) Now when i create and object of this class and call the fit method tf.reset_default_graph() model = AlexNet_model() model.fit(train_x, train_y) I get this error , saying uninitialized variables FailedPreconditionError: Attempting to use uninitialized value beta1_power [[Node: beta1_power/read = Identity[T=DT_FLOAT, _class=["loc:@conv1/bias"], _device="/job:localhost/replica:0/task:0/device:GPU:0"](beta1_power)]] Note: rest of the functions are defined with the class and are working properly
upvote count: 1
has title: Initializing tensorflow session in a class constructor
favorite count: 0
tagged with: jupyter-notebook
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88890610
tagged with: python

http://stackoverflow.com/a/50927153
has comment: http://stackoverflow.com/comment/88866711
type: Answer
has comment: http://stackoverflow.com/comment/88876007
has comment: http://stackoverflow.com/comment/88858238
accepted answer of: http://stackoverflow.com/q/50890686
downvote count: 0
answers question: http://stackoverflow.com/q/50890686
score: 1
has comment: http://stackoverflow.com/comment/88860644
upvote count: 1
type: AcceptedAnswer
has body: Applying approach from below SO thread Export scrapy items to different files I created a sample scraper import scrapy class ExampleSpider(scrapy.Spider): name = 'example' allowed_domains = ['example.com'] start_urls = ['http://example.com/'] def parse(self, response): yield {"type": "unknown item"} yield {"title": "ExampleTitle1", "author": "Username", "score": "11000"} yield {"name": "Username", "karma": "00000"} yield {"name": "Username2", "karma": "00000"} yield {"someothertype": "unknown item"} yield {"title": "ExampleTitle2", "author": "Username2", "score": "12000"} yield {"title": "ExampleTitle3", "author": "Username3", "score": "13000"} yield {"title": "ExampleTitle4", "author": "Username4", "score": "9000"} yield {"name": "Username3", "karma": "00000"} And then in exporters.py from scrapy.exporters import JsonItemExporter from scrapy.extensions.feedexport import FileFeedStorage class JsonMultiFileItemExporter(JsonItemExporter): types = ["topics", "users"] def __init__(self, file, **kwargs): super().__init__(file, **kwargs) self.files = {} self.kwargs = kwargs for itemtype in self.types: storage = FileFeedStorage(itemtype + ".json") file = storage.open(None) self.files[itemtype] = JsonItemExporter(file, **self.kwargs) def start_exporting(self): super().start_exporting() for exporters in self.files.values(): exporters.start_exporting() def finish_exporting(self): super().finish_exporting() for exporters in self.files.values(): exporters.finish_exporting() exporters.file.close() def export_item(self, item): if "title" in item: itemtype = "topics" elif "karma" in item: itemtype = "users" else: itemtype = "self" if itemtype == "self" or itemtype not in self.files: super().export_item(item) else: self.files[itemtype].export_item(item) Add below to the settings.py FEED_EXPORTERS = { 'json': 'testing.exporters.JsonMultiFileItemExporter', } Running the scraper I get 3 files generated example.json [ {"type": "unknown item"}, {"someothertype": "unknown item"} ] topics…

http://stackoverflow.com/a/50892590
type: Answer
answers question: http://stackoverflow.com/q/50892257
has comment: http://stackoverflow.com/comment/88785903
accepted answer of: http://stackoverflow.com/q/50892257
has body: so, your program is perfect, it's just that for some reason the wrong slashes were being used in the path, which python apparently could handle, but explorer.exe could not. i ran your program, and printed out folder_selected and i got C:/Users/Michael/Desktop/test. which contains forward slashes, and windows paths use backslashes. ao i would just replace subprocess.Popen(["C:\\Windows\\explorer.exe"]) to: subprocess.Popen(["C:\\Windows\\explorer.exe", folder_selected.replace('/', '\\')]) which will replace any forward slashes with backslashes, which explorer.exe should be able to handle. hope this works :) windows paths also cant have any kind of slash in them, so the user wont have a directory with any / in it, so replace should be fine
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88785868

http://stackoverflow.com/q/50980800
type: Question
score: 0
has body: Need help, I expected the output like this 1.1.1.1 is server0 1.1.1.2 is server1 1.1.1.3 is server2 1.1.1.4 is server3 But I don't get the output like I expected. Here's my code IP = ['1.1.1.1', '1.1.1.2', '1.1.1.3', '1.1.1.4'] for ip in IP: for i in range(len(IP)): print(ip + ' is ' + 'server'+ str(i)) Output: 1.1.1.1 is server0 1.1.1.1 is server1 1.1.1.1 is server2 1.1.1.1 is server3 1.1.1.2 is server0 1.1.1.2 is server1 1.1.1.2 is server2 1.1.1.2 is server3 1.1.1.3 is server0 1.1.1.3 is server1 1.1.1.3 is server2 1.1.1.3 is server3 1.1.1.4 is server0 1.1.1.4 is server1 1.1.1.4 is server2 1.1.1.4 is server3 Can someone help me?
answer count: 1
has comment: http://stackoverflow.com/comment/88957073
tagged with: python
duplicate of: http://stackoverflow.com/q/522563
accepted answer: http://stackoverflow.com/a/50980816
has title: For Loop generate sequence
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88969568
linked to: http://stackoverflow.com/q/6404129
has answer: http://stackoverflow.com/a/50980816

http://stackoverflow.com/q/50880843
has body: I'm working with PIL and trying to use the median filter on an image in order to de-noise it. But when I try, the result is a black image. What I think is the cause of the problem is the fact that the image is of class 'PIL.Image.Image'. Let me explain what I am doing/the issue in more depth. I had to perform some image manipulations using numpy. In order to do that I first had to cast the PIL image to a numpyArray. I did this with the following code: img = np.array(image) After performing the needed transformations I cast the image back to PIL with the following code: def numpy_to_pil(image): minv = np.amin(image) maxv = np.amax(image) img = Image.fromarray((255 * (image - minv) / (maxv - minv)).astype(np.uint8)) return img When I try to filter 'img' with a median filter, as previously stated, the result is a black image. This is how I use the filter function of PIL: img.filter(ImageFilter.MedianFilter(3)) I tried comparing the results with an image (let's call it 'cat' (literally image of a cat)) that wasn't put through the casting process that 'img' was put through. I tried printing out the types to see what differed. This is the result: cat = &lt;class 'PIL.PngImagePlugin.PngImageFile'&gt; img = &lt;class 'PIL.Image.Image'&gt; Seeing this I wonder if the problem is that 'img' is of type 'PIL.Image.Image' instead of 'PIL.PngImagePlugin.PngImageFile'. Did I do something wrong whilte casting form numpyArray to PIL? Or is it something else. Any help is greatly appreciated! (I tried being as specific as possible) P.S: The type of noise is salt&amp;pepper P.P.S: I tried using img.convert('PIL.PngImagePlugin.PngImageFile') but it outputs the following error: conversion from RGB to PIL.PngImagePlugin.PngImageFile not supported
has comment: http://stackoverflow.com/comment/88795904
upvote count: 1
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50882986
tagged with: python-imaging-library
score: 1
type: Question
tagged with: numpy
downvote count: 0
accepted answer: http://stackoverflow.com/a/50882986
answer count: 1
tagged with: imagefilter
favorite count: 0
linked to: http://stackoverflow.com/q/50897906
has title: Casting images to different class PIL

http://stackoverflow.com/a/50920208
upvote count: 11
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50919752
score: 11
has comment: http://stackoverflow.com/comment/88877106
answers question: http://stackoverflow.com/q/50919752
has body: Try using localhost step by step : 1 - Launch the following command : docker run -p 8888:8888 jupyter/scipy-notebook 2 - Copy/paste the url URL into your browser : http://e6ef92c5e5d6:8888/?token=... 3 - Replace the hostname by localhost : http://localhost:8888/?token=... It worked for me : [I 03:22:51.414 NotebookApp] 302 GET /?token=... (172.17.0.1) 0.97ms
type: AcceptedAnswer

http://stackoverflow.com/comment/88899800
type: Comment
has text: @Tim ok I see, I will have to do some more tests to give a concrete answer.
comment on: http://stackoverflow.com/a/50950931
type: AnswerComment
score: 0

http://stackoverflow.com/comment/88860354
score: 0
type: QuestionComment
has text: The scipy optimize function doesn't quite seem to fit my purposes. What I want to optimize is the number of cases which are correctly ranked, so my function would return an integer. Sci-py optimize seems to require the function return a float.
type: Comment
comment on: http://stackoverflow.com/q/50917864

http://stackoverflow.com/comment/88961667
score: 0
type: AnswerComment
type: Comment
has text: I'm not really sure what slopes other than `0` you expect by 32 lists of constant values, but anyway - your slope calculation doesn't have anything to do with your plots, so you could apply `polyfit` to your x-y-data as before. I'll update...
comment on: http://stackoverflow.com/a/50981429

http://stackoverflow.com/comment/88872572
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50936166
has text: Really down-voting this post? What more do you want from me?
score: 0

pyspark
tags question: http://stackoverflow.com/q/50941529
tags question: http://stackoverflow.com/q/50964011
tags question: http://stackoverflow.com/q/50877182
tags question: http://stackoverflow.com/q/50884060
tags question: http://stackoverflow.com/q/50895691
tags question: http://stackoverflow.com/q/50940607
tags question: http://stackoverflow.com/q/50879009
tags question: http://stackoverflow.com/q/51001480
tags question: http://stackoverflow.com/q/50967223
tags question: http://stackoverflow.com/q/50865803
tags question: http://stackoverflow.com/q/50908888
tags question: http://stackoverflow.com/q/50880303
tags question: http://stackoverflow.com/q/50913834
tags question: http://stackoverflow.com/q/50880579
tags question: http://stackoverflow.com/q/50926624
tags question: http://stackoverflow.com/q/51002997
type: Tag
tags question: http://stackoverflow.com/q/50865236
tags question: http://stackoverflow.com/q/50947780
tags question: http://stackoverflow.com/q/50960404
tags question: http://stackoverflow.com/q/51008489
tags question: http://stackoverflow.com/q/50899723
tags question: http://stackoverflow.com/q/50971964
tags question: http://stackoverflow.com/q/50864788
tags question: http://stackoverflow.com/q/50989747
tags question: http://stackoverflow.com/q/50973090
tags question: http://stackoverflow.com/q/50869255
tags question: http://stackoverflow.com/q/50984812
tags question: http://stackoverflow.com/q/50950170
tags question: http://stackoverflow.com/q/50953930
tags question: http://stackoverflow.com/q/50861016
tags question: http://stackoverflow.com/q/50976043
tags question: http://stackoverflow.com/q/50967032
tags question: http://stackoverflow.com/q/50915749
tags question: http://stackoverflow.com/q/50866057
tags question: http://stackoverflow.com/q/50942685
tags question: http://stackoverflow.com/q/50927957
tags question: http://stackoverflow.com/q/50932126
tags question: http://stackoverflow.com/q/50897978
tags question: http://stackoverflow.com/q/50973317
tags question: http://stackoverflow.com/q/50893788
tags question: http://stackoverflow.com/q/50923055
tags question: http://stackoverflow.com/q/50895070
tags question: http://stackoverflow.com/q/50879438
tags question: http://stackoverflow.com/q/50872574
tags question: http://stackoverflow.com/q/50987944
tags question: http://stackoverflow.com/q/50990350
tags question: http://stackoverflow.com/q/50932283
tags question: http://stackoverflow.com/q/50865093
tags question: http://stackoverflow.com/q/50864196
tag name: pyspark
tags question: http://stackoverflow.com/q/50918033
tags question: http://stackoverflow.com/q/50936676

http://stackoverflow.com/q/50885786
score: 2
downvote count: 0
has title: Python - How to send mail via proxy
has answer: http://stackoverflow.com/a/70461637
type: Question
has comment: http://stackoverflow.com/comment/88775989
has body: Need help to send mail `(smtp.gmail.com)` through proxy settings. Not working even after trying multiple libraries (Including socks) Latest - Using `xsmtplib`.. but getting following error. The HTTP proxy server may not be supported by PySocks (must be a CONNECT tunnel proxy) Any help will be really appreciated. Below code for connecting with SMTP server via Proxy """from xsmtplib import SMTP server = SMTP(proxy_host,proxy_port,host,port,timeout) server.sendmail("aaaa@gmail.com", "bbbb@gmail.com", "Test Msg") server.quit()"""
upvote count: 2
answer count: 1
tagged with: smtp
favorite count: 0
tagged with: proxy
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/50934480
has answer: http://stackoverflow.com/a/55700499
upvote count: 4
answer count: 2
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/50936600
tagged with: python
tagged with: allure
has title: Error after installation of allure pytest adaptor
score: 4
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50936600
has body: I am trying to configure Allure (2.6.0) with Pytest (3.6xx) on a Windows 8 box. I am able to run pytest and generate jUnit xml report file which later I can pass to allure (allure server jUnitXmlFile.xml) and it works fine. What I need is the additional functionality that Allure provides (metadata,attachments, etc), so I downloaded pytest-allure-adaptor. So I have the following packages installed in my venv: allure-pytest==2.4.1 allure-python-commons==2.4.1 pytest-allure-adaptor==1.7.10 ... If I now run py.test.exe, I get the following error: (venv) c:\TestAutomation&gt;py.test.exe Traceback (most recent call last): File "C:\Tools\WinPython\python-3.6.5.amd64\Lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "C:\Tools\WinPython\python-3.6.5.amd64\Lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "c:\TestAutomation\venv\Scripts\py.test.exe\__main__.py", line 9, in &lt;module&gt; File "c:\testautomation\venv\lib\site-packages\_pytest\config.py", line 52, in main config = _prepareconfig(args, plugins) File "c:\testautomation\venv\lib\site-packages\_pytest\config.py", line 163, in _prepareconfig pluginmanager=pluginmanager, args=args) File "c:\testautomation\venv\lib\site-packages\pluggy\__init__.py", line 617, in __call__ return self._hookexec(self, self._nonwrappers + self._wrappers, kwargs) File "c:\testautomation\venv\lib\site-packages\pluggy\__init__.py", line 222, in _hookexec return self._inner_hookexec(hook, methods, kwargs) File "c:\testautomation\venv\lib\site-packages\pluggy\__init__.py", line 216, in &lt;lambda&gt; firstresult=hook.spec_opts.get('firstresult'), File "c:\testautomation\venv\lib\site-packages\pluggy\callers.py", line 196, in _multicall gen.send(outcome) File "c:\testautomation\venv\lib\site-packages\_pytest\helpconfig.py", line 68, in pytest_cmdline_parse config = outcome.get_result() File "c:\testautomation\venv\lib\site-packages\pluggy\callers.py", line 76, in get_result raise ex[1].with_traceback(ex[…
type: Question
tagged with: pytest
possible better answer: http://stackoverflow.com/a/55700499

http://stackoverflow.com/q/50878903
downvote count: 0
has title: Validate new users passwords in Django admin interface
tagged with: django-validation
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88761248
score: 1
has comment: http://stackoverflow.com/comment/88760267
favorite count: 0
has answer: http://stackoverflow.com/a/50882226
type: Question
answer count: 2
tagged with: django
tagged with: python
possible better answer: http://stackoverflow.com/a/50914480
has answer: http://stackoverflow.com/a/50914480
has comment: http://stackoverflow.com/comment/88760926
upvote count: 1
accepted answer: http://stackoverflow.com/a/50882226
has body: There is one interesting moment in Django documentation: By default, validators are used in the forms to reset or change passwords and in the createsuperuser and changepassword management commands. Validators aren’t applied at the model level, for example in User.objects.create_user() and create_superuser(), because we assume that developers, not users, interact with Django at that level and also because model validation doesn’t automatically run as part of creating models. But in my Django app i am using only Django Admin interface with admin.ModelAdmin. When i am trying to create new user i can broke all the validators from AUTH_PASSWORD_VALIDATORS. How can i validate passwords on creating new users in Django admin interface using validators AUTH_PASSWORD_VALIDATORS? admin.py: class UserCreateForm(ModelForm): class Meta: model = User fields = ['username', 'password'] class UserAdmin(admin.ModelAdmin): form = UserCreateForm list_display = ('username') def get_form(self, request, obj=None, change=False, **kwargs): if change: return self.change_form return super(UserAdmin, self).get_form(request, obj, **kwargs) def has_add_permission(self, request): return True def has_delete_permission(self, request, obj=None): return False def has_change_permission(self, request, obj=None): return True def save_model(self, request, obj, form, change): if obj.pk: orig_obj = User.objects.get(pk=obj.pk) if obj.password != orig_obj.password: obj.set_password(obj.password) else: obj.is_superuser = True obj.set_password(obj.password) obj.save() models.py: class User(AbstractBaseUser, PermissionsMixin): USERNAME_FIELD = 'username' username_validator = UnicodeUsernameValidator() username = models.CharField( max_length=150, unique=True, validators=[username_validator] ) objects = UserManager() managers.py: class UserManager(BaseUserManager): def create_user(self, username, password=None): if not username: raise ValueError('Users must have username assigned') user = self.model(username=usern…
has comment: http://stackoverflow.com/comment/88760347
tagged with: django-admin

http://stackoverflow.com/comment/88761733
type: QuestionComment
has text: @Cleb - just posted on Stackexchange as well. Thank you for advise
score: 1
comment on: http://stackoverflow.com/q/50860512
type: Comment

http://stackoverflow.com/comment/88746418
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50871364
has text: @NilsWerner, You are right. You can add an answer. Thank you buddy!

http://stackoverflow.com/q/50885667
has body: Hi i m unable to understand the explanation of isValid method of QSqlQuery in Qt. The query always returns False for isValid() and true for next(),first() etc I checked for lastErrors as well if any, none were there I m new to qt , can anyone explain me what is meant by bool QSqlQuery::isValid () const Returns true if the query is currently positioned on a valid record; otherwise returns false. Code -- query = QtSql.QSqlQuery() query.exec_("select * from test.PG_Details where PG_Id = 1") print("Bool-&gt;",query.isValid()) // Return FALSE print("Next-&gt;",query.next()) // Returns TRUE print("LE-&gt;",query.lastError().text()) //Returns Blank
score: 1
tagged with: pyqt5
upvote count: 1
type: Question
has title: explanation of isValid() in QSqlQuery
has answer: http://stackoverflow.com/a/50885893
tagged with: pyqt
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python-3.x
tagged with: qsqlquery
accepted answer: http://stackoverflow.com/a/50885893
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/51010552
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51010307
has body: Take a look here: plt.bar. Where you have the index you select the keys from your dictionaries. Then the second element after index, 'means_frank' can be the slice (first two values) from the first or n dictionary.
answers question: http://stackoverflow.com/q/51010307
score: 1
type: AcceptedAnswer
upvote count: 1
has comment: http://stackoverflow.com/comment/89014011
type: Answer
has comment: http://stackoverflow.com/comment/89014805

http://stackoverflow.com/a/51021008
type: Answer
answers question: http://stackoverflow.com/q/51009185
score: 4
upvote count: 4
downvote count: 0
has body: Finally, I figure it out. source_ds = ogr.Open("C:/Users/Nathan/Desktop/pl.shp") source_layer = source_ds.GetLayer() pixelWidth = pixelHeight = 0.001 x_min, x_max, y_min, y_max = source_layer.GetExtent() cols = int((x_max - x_min) / pixelHeight) rows = int((y_max - y_min) / pixelWidth) target_ds = gdal.GetDriverByName('GTiff').Create('temp.tif', cols, rows, 1, gdal.GDT_Byte) target_ds.SetGeoTransform((x_min, pixelWidth, 0, y_min, 0, pixelHeight)) band = target_ds.GetRasterBand(1) NoData_value = 0 band.SetNoDataValue(NoData_value) band.FlushCache() gdal.RasterizeLayer(target_ds, [1], source_layer, options = ["ATTRIBUTE=AVG"]) target_ds = None #this is the line that makes the difference gdal.Open('temp.tif').ReadAsArray()

http://stackoverflow.com/a/50879535
score: 0
answers question: http://stackoverflow.com/q/50863152
type: Answer
has body: Should be parent property: ws = wb["Sheet1"] cell = ws.cell(row=15, column=15) print(cell.parent.title)

http://stackoverflow.com/q/50924824
upvote count: 1
has comment: http://stackoverflow.com/comment/88849073
has comment: http://stackoverflow.com/comment/88855466
has comment: http://stackoverflow.com/comment/88859646
type: Question
has answer: http://stackoverflow.com/a/50933101
has comment: http://stackoverflow.com/comment/88856451
tagged with: javascript
has comment: http://stackoverflow.com/comment/88863363
has title: How to split JSON results in to multiple Zapier assets?
answer count: 2
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/50933101
has comment: http://stackoverflow.com/comment/88855970
possible better answer: http://stackoverflow.com/a/57617882
has comment: http://stackoverflow.com/comment/88857566
has answer: http://stackoverflow.com/a/57617882
has comment: http://stackoverflow.com/comment/88856227
tagged with: python
tagged with: zapier
type: AnsweredQuestion
has body: I aim to call Bing News Search via API to get results matching a certain query. I am using Zapier. I am using the Code step, which can take either Python of Javascript. I currently have Python code to call the API as follows... headers = { 'Content-Type': 'text/plain', 'Ocp-Apim-Subscription-Key': 'my_api_key' } r = requests.get('https://api.cognitive.microsoft.com/bing/v7.0/news/search?q=%22Donald%20Trump%22&textDecorations=true&textFormat=HTML&sortBy=Date&freshness=Day', headers=headers) output = [{'assets': r.json()}] This works fine. It successfully calls and gets results. The problem is, when I want to use the content of those results in a subsequent Zapier step, they are all mashed together in the same response object - that is, each equivalent value from multiple returned interior story objects is all placed in the same available Zapier value, separated by comma. Example: the available "category" value is "null, null, null, World, null, Politics, Politics, Politics, null, null", for 10 stories returned in the object - but it should only be ONE of those, for one story. In other words, how do I individualise assets/objects in order to let Zapier process them individually? I'd say this isn't just about parsing out the values, but doing so in a way that Zapier can understand. However, I have done it once before, in a different language... By means of example for this same principle, I have a separate zap for another purpose which does a similar thing. It takes incoming Gmail emails and checks the body (inputData.body) for strings matching a certain pattern. There may be multiple such strings. For each of those, the following Javascript passes each multiple of them to the next Zapier step individually. // stores an array of any length (0 or more) with the matches var matches = inputData.body.match(/\b[\w-]{32}\b/g) if (matches == null) { return { str: "false" } } return matches.map(function (m) { return {str: m} }) This magically allows my subsequent zap steps to …
score: 1
has comment: http://stackoverflow.com/comment/88849581
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/88865146

http://stackoverflow.com/comment/88715008
score: 2
type: Comment
type: QuestionComment
has text: This seems to be an issue with matplotlib 2.2.2. I just ran your script in a 2.1.2 (Python 3.5.2), and the lines were very jittery. Updated matplotlib to 2.2.2, reran, and the lines were no longer jittery.
comment on: http://stackoverflow.com/q/50855834

http://stackoverflow.com/q/50858615
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51328080
downvote count: 0
score: 1
favorite count: 0
tagged with: python
tagged with: pypdf
has answer: http://stackoverflow.com/a/69557516
type: UnansweredQuestion
has body: I have thousands of PDF files like this one. I'm trying to use PyPDF2 to convert them to plain text (code is below). But PyPDF2 apparently only "sees" the watermarks, not the content itself. What could I do here? import os import PyPDF2 path_to_pdfs = '/path/to/pdf/files/' for filename in os.listdir(path_to_pdfs): if '.pdf' in filename.lower(): with open(path_to_pdfs + filename, mode = 'rb') as f: txt = '' pdf_reader = PyPDF2.PdfFileReader(f) num_pages = pdf_reader.numPages for page in range(num_pages): page_obj = pdf_reader.getPage(page) page_text = page_obj.extractText() txt = txt + '\n' + page_text print(txt) I'm using Python 3.5.1 and PyPDF2 1.26.0 on macOS 10.13.14.
upvote count: 1
has title: PyPDF2 ignores content, gets watermark only
linked to: http://stackoverflow.com/q/44024697

http://stackoverflow.com/q/50881647
tagged with: python
has title: Fail to import tensorflow from a program called within a script via ssh
answer count: 0
type: UnansweredQuestion
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/88765660
has body: I want to automate hyperparameter search. So I decided to write a python script that automated that task. Basically it (script.py) looks like: import os parameters = [0.001, 0.002, 0.003] for p in parameters: os.system("python main.py --learning_rate={}".format(p)) While main.py starts with import tensorflow as tf and then does its magic. When I run $ python main.py --learning_rate=0.001 it does its job without problem (both on my computer and on the server). When I try the script on my computer it works fine BUT when I try to run $ python script.py on the server it says Traceback (most recent call last): File "main.py", line 1, in &lt;module&gt; import tensorflow as tf ImportError: No module named tensorflow This is my first question, please let me know if I should make any changes or add/remove information. Thanks. Solution: Thanks for the help! By checking what was suggested in Script running in PyCharm but not from the command line I was able to spot the problem and solve my error. All I had to do in my script was then to change os.system("python main.py --learning_rate={}".format(p)) for os.system("python3.6 main.py --learning_rate={}".format(p)) to get it running.
tagged with: tensorflow
type: Question
downvote count: 0
linked to: http://stackoverflow.com/q/29553668
favorite count: 0
duplicate of: http://stackoverflow.com/q/29553668
tagged with: ssh

http://stackoverflow.com/q/51008334
has comment: http://stackoverflow.com/comment/89009729
has comment: http://stackoverflow.com/comment/89009619
duplicate of: http://stackoverflow.com/q/45621722
downvote count: 1
type: Question
linked to: http://stackoverflow.com/q/1016814
has comment: http://stackoverflow.com/comment/89010132
score: 0
has answer: http://stackoverflow.com/a/51008732
upvote count: 1
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89010114
has body: from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure import io from flask import Flask, render_template, send_file, make_response, request from gpiozero import LED import datetime import gevent import gevent.monkey from gevent.pywsgi import WSGIServer gevent.monkey.patch_all() app = Flask(__name__) import sqlite3 conn=sqlite3.connect('../sensorsData.db') curs=conn.cursor() led = LED(18) def ledOn(): led.blink() return "LED has been turned on" def ledOff(): led.off() return "LED has been turned off" def ledStatus(): if led.is_lit: return 'On' else: return 'Off' @app.route("/readLED/") def readPin(): response = ledStatus() templateData = { 'title' : 'Status of LED: ', 'response' : response } return render_template('index.html', **templateData) @app.route("/writeLED/&lt;status&gt;") def writePin(status): if status == 'On': response = ledOn() else: response = ledOff() templateData = { 'title' : 'Status of LED', 'response' : response } return render_template('index.html', **templateData) # Retrieve LAST data from database def getLastData(): for row in curs.execute("SELECT * FROM DHT_data ORDER BY timestamp DESC LIMIT 1"): time = str(row[0]) temp = row[1] hum = row[2] #conn.close() return time, temp, hum def getHistData (numSamples): curs.execute("SELECT * FROM DHT_data ORDER BY timestamp DESC LIMIT "+str(numSamples)) data = curs.fetchall() dates = [] temps = [] hums = [] for row in reversed(data): dates.append(row[0]) temps.append(row[1]) hums.append(row[2]) return dates, temps, hums def maxRowsTable(): for row in curs.execute("select COUNT(temp) from DHT_data"): maxNumberRows=row[0] return maxNumberRows # define and initialize global variables global numSamples numSamples = maxRowsTable() if (numSamples &gt; 101): numSamples = 100 # main route @app.route("/") def index(): time, temp, hum = getLastData() templateData = { 'time' : time, 'temp' : temp, 'hum' : hum, 'numSamples' : numSamples } return render_templat…
has comment: http://stackoverflow.com/comment/89010407
type: UnansweredQuestion
tagged with: python
has title: Indentation errors on Python
has comment: http://stackoverflow.com/comment/89009618

http://stackoverflow.com/comment/88967497
has text: sorry, I thought its my mistake in python coding . shall i delete the post?
score: 0
comment on: http://stackoverflow.com/q/50986197
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/88766793
comment on: http://stackoverflow.com/q/50882225
type: Comment
score: 2
type: QuestionComment
has text: You should start by printing the dictionary you've built to check what's in it: there'll be at most two values in there.

http://stackoverflow.com/comment/88791904
comment on: http://stackoverflow.com/q/50895461
has text: I do understand your valid point but knowing how it's done is what i am after here not the results.
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/a/50946351
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50944928
answers question: http://stackoverflow.com/q/50944928
type: Answer
score: 0
has body: In tmpdir/tmpdir_factory the file is not actually created until you write to it. changing: for f in flist: test_dir.join(f) to for f in flist: a = test_dir.join(f) a.write('') Causes the file to be created and works as expected

http://stackoverflow.com/q/50949254
has comment: http://stackoverflow.com/comment/88897463
favorite count: 0
has comment: http://stackoverflow.com/comment/88898186
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88897240
tagged with: python
has comment: http://stackoverflow.com/comment/106589484
has comment: http://stackoverflow.com/comment/88899492
answer count: 0
has title: Python compiled .exe classed as virus
has comment: http://stackoverflow.com/comment/88897115
has body: Python 3.65, Windows 7. My antivirus (Avira) says my compiled code is a virus and keeps deleting it. I have white-listed my program, but it worries me that 11 other virus checkers ou t of 60 on VirusTotal also think its a virus. I am confident that it's a false positive but what about when I get to the point of writing something worth distributing? Is this normal? Or is there something in my source code that looks "virusy" to heuristics when compiled? import pyperclip from tkinter import * from ctypes import windll import os import time # default folder for saves "c:\\cb-pastes" #default txt file "c:\\cb-pastes\\saved.txt" #================set up gui======================= root = Tk() #check if "c:\\cb-pastes" exists, if not, create folder check_folder=os.path.isdir("c:\\cb-pastes") if not check_folder: os.makedirs("c:\\cb-pastes") #button functions def call_save(): ct=time.asctime() #get system time and date in ct cb_txt = pyperclip.paste() #store clipboard in cb_txt f = open("c:\\cb-pastes\\saved.txt","a") # open the file: f.write ("\n") #newline f.write (ct) #save date and time with the text f.write ("\n") f.write (cb_txt) #append to text file f.write ("\n") f.write ("-----------------------------") f.close() #Close the file def call_clear(): #clear clipboard if windll.user32.OpenClipboard(None): windll.user32.EmptyClipboard() windll.user32.CloseClipboard() def call_view(): #open text file of saved clips os.startfile('c:\\cb-pastes\\saved.txt') def call_viewcb(): #open text file of current clipboard contents cb_get = pyperclip.paste() f = open("c:\\cb-pastes\\temp.txt","w") f.write (cb_get) f.close() os.startfile('c:\\cb-pastes\\temp.txt') #create window root.title ("CBMan V0.8") root.geometry ("230x132") # create buttons app = Frame(root) app.grid() button1 = Button(app, text = "Save Clipboard",width=13, command=call_save) button1.grid(row=0,column=0) button2 = Button(app, text = "Clear Clipboard",width=13, command=call_clear) button2.grid() button3 = Button(app…
upvote count: 1
has comment: http://stackoverflow.com/comment/88901017
type: Question
score: 1
has comment: http://stackoverflow.com/comment/88896251
has comment: http://stackoverflow.com/comment/88898652
has comment: http://stackoverflow.com/comment/88897830
has comment: http://stackoverflow.com/comment/88898937
has comment: http://stackoverflow.com/comment/88913068
downvote count: 0

http://stackoverflow.com/q/51001858
favorite count: 0
tagged with: seaborn
tagged with: data-visualization
tagged with: python
has body: I have a large pandas dataframe, which is a log of user ids that login in a website: id datetime 130 2018-05-17 19:46:18 133 2018-05-17 20:59:57 133 2018-05-17 21:54:01 142 2018-05-17 22:49:07 114 2018-05-17 23:02:34 136 2018-05-18 06:06:48 136 2018-05-18 12:21:38 180 2018-05-18 12:49:33 ....... 120 2018-05-18 14:03:58 120 2018-05-18 15:28:36 How can I visualize the above pandas dataframe as a time series plot? For example I would like to represent the frequency of logins of each person id as a line of a different color (note that I have about 400 ids). Something like this plot (*): ] I tried to: from datetime import date import matplotlib.dates as mdates import matplotlib.pyplot as plt import pandas as pd # set your data as df # strip only YYYY-mm-dd part from original `datetime` column df3.timestamp = df3.datetime.apply(lambda x: str(x)[:10]) df3.timestamp = df3.datetime.apply(lambda x: date(int(x[:4]), int(x[5:7]), int(x[8:10]))) # plot plt.figure(figsize=(150,10)) plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m')) plt.gca().xaxis.set_major_locator(mdates.DayLocator()) plt.plot(df3.datetime[:800], df3.id[:800], '-') plt.gcf().autofmt_xdate() and import matplotlib.dates as dates df5 = df3.set_index('datetime') df5.plot(x_compat=True) plt.gca().xaxis.set_major_locator(dates.DayLocator()) plt.gca().xaxis.set_major_formatter(dates.DateFormatter('%d\n\n%a')) plt.gca().invert_xaxis() plt.gcf().autofmt_xdate(rotation=0, ha="center") plt.figure(figsize=(150,10)) However, I got something like this: ] Any idea of how to get a plot similar to (*)?
has answer: http://stackoverflow.com/a/51002123
type: AnsweredQuestion
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88997635
accepted answer: http://stackoverflow.com/a/51002123
tagged with: matplotlib
has title: Problems while plotting time series against user logins?
tagged with: pandas
answer count: 1
downvote count: 0
score: 1

http://stackoverflow.com/comment/88819782
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50909876
has text: 1) https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

http://stackoverflow.com/comment/88735022
has text: @Dudnikov For multiple instances you should probably use threading. Then sleep will not be an issue. Either that or perform a function where you know how long it takes to calculate and repeat that as many times as you need (bit hacky though)
comment on: http://stackoverflow.com/q/50866239
type: Comment
type: QuestionComment
score: 2

scatter
tags question: http://stackoverflow.com/q/50930889
tags question: http://stackoverflow.com/q/50961057
tag name: scatter
tags question: http://stackoverflow.com/q/50938103
tags question: http://stackoverflow.com/q/50981960
tags question: http://stackoverflow.com/q/50939270
type: Tag
tags question: http://stackoverflow.com/q/51010201

http://stackoverflow.com/a/50954637
has comment: http://stackoverflow.com/comment/106647354
score: 5
has body: def my_bool(s): return s != 'False' parser.add_argument('-data',default=True,type=my_bool)
upvote count: 5
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50954491

http://stackoverflow.com/comment/88813246
has text: place this line before your: "for file in files":
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50900050
type: Comment

http://stackoverflow.com/a/50918770
upvote count: 2
answers question: http://stackoverflow.com/q/50865739
has body: As pointed out by Chiefir, I had indeed forgotten to add the 'mail_admins' handler to the 'django' logger. There was also another issue, however, with the SERVER_EMAIL setting. This was not specified and therefore defaulted to root@localhost, but Mailgun only allows you to send emails from validated domains. After making these two changes, the emails to ADMINS are received correctly.
downvote count: 0
has comment: http://stackoverflow.com/comment/125971295
type: Answer
score: 2

http://stackoverflow.com/comment/88782024
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50867122
has text: @rajansthapit Have you tried upgrading to the latest `grpcio` package?
score: 0

http://stackoverflow.com/comment/89050367
type: QuestionComment
comment on: http://stackoverflow.com/q/50954795
has text: Also try waiting for that element instead of finding it, may just be loading slower on another environment
score: 0
type: Comment

http://stackoverflow.com/q/51007558
has body: I've written a python script that looks up the recommended server at nordvpn.com and starts the according vpn. There is a part in this script where I assure there is internet access. When I run the script from a terminal, I cannot interrupt this loop by pressing ^C if there is no connection. How can I adapt the code so that the loop is interruptible? Here is relevant part of the code: #!/usr/bin/env python3 import re import os from selenium import webdriver if __name__ == '__main__': # ... # wait for internet connection and load geckodriver while True: try: browser = webdriver.Firefox( executable_path=r'/home/maddin/bin/.vpn/geckodriver', log_path='/dev/null') break except: print("not connected yet, trying again....") # ...
has answer: http://stackoverflow.com/a/51007715
has answer: http://stackoverflow.com/a/51007751
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51007751
score: 1
upvote count: 1
tagged with: sigint
type: Question
linked to: http://stackoverflow.com/q/18982610
accepted answer: http://stackoverflow.com/a/51007715
has comment: http://stackoverflow.com/comment/89008350
has comment: http://stackoverflow.com/comment/89008159
has comment: http://stackoverflow.com/comment/89008202
answer count: 2
downvote count: 0
linked to: http://stackoverflow.com/q/40280776
has comment: http://stackoverflow.com/comment/89008248
tagged with: unix
favorite count: 0
has title: How to make python loop interruptible by ^C on unix?

http://stackoverflow.com/comment/88962792
score: 0
type: Comment
type: QuestionComment
has text: could you paste the full stack trace
comment on: http://stackoverflow.com/q/50971229

http://stackoverflow.com/comment/88749371
comment on: http://stackoverflow.com/q/50873976
has text: are you worried about key's in result dictionary?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/96247188
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50866635
has text: Ok, thanks for the ref. to Nyquist. Let us say the x points are equidistant. How your sin(x)/x solves the graph integration?
score: 0

http://stackoverflow.com/a/50968571
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/50968259
has body: It is not 100% clear if your question is about the Firebase Real Time database (as the tags of your question show) or about Firebase Storage (https://firebase.google.com/docs/storage/). If your question is about the Realtime Database, you could use the Realtime Database REST API, which returns data from the database in JSON format. The documentation for retrieving data is here: https://firebase.google.com/docs/database/rest/retrieve-data
downvote count: 0
type: Answer

http://stackoverflow.com/a/50970607
has comment: http://stackoverflow.com/comment/88937702
answers question: http://stackoverflow.com/q/50970550
upvote count: 4
downvote count: 0
score: 4
has comment: http://stackoverflow.com/comment/88937593
type: Answer
has body: os.walk() can't continue because an exception was raised. Either don't call max() with an empty list, catch the exception, or tell max() to return a default value if the list is empty. You can trivially skip testing for the largest if there are no excel files; if list_of_files: will be false if the list is empty: for root, dirs, files in os.walk(path): list_of_files = [] for file in files: if file.endswith(".xlsx"): list_of_files.append(file) largest = None if list_of_files: largest = max(list_of_files) print(largest or 'No Excel files in this directory') If you are using Python 3.4 or newer, you can also tell the max() function to return a default value if your input list is empty: for root, dirs, files in os.walk(path): list_of_files = [] for file in files: if file.endswith(".xlsx"): list_of_files.append(file) largest = max(list_of_files, None) # None is the default value print(largest or 'No Excel files in this directory') Last but not least, you can use try...except ValueError: to handle the exception thrown: for root, dirs, files in os.walk(path): list_of_files = [] for file in files: if file.endswith(".xlsx"): list_of_files.append(file) try: largest = max(list_of_files) print(largest) except ValueError: print('No Excel files in this directory') You can simplify your code by using the fnmatch.filter() function to filter out matching files: import fnmatch import os for root, dirs, files in os.walk(path): excel_files = fnmatch.filter(files, '*.xlsx') largest = max(list_of_files, None)
has comment: http://stackoverflow.com/comment/88937737
has comment: http://stackoverflow.com/comment/88938273

http://stackoverflow.com/q/50883519
downvote count: 0
type: UnansweredQuestion
tagged with: cpython
tagged with: python
has title: Python Buffers, How Do They Work?
type: Question
score: 5
has body: I'm currently surveying the Python buffer interface to see if it would help with optimizing my project. My project deals with large binary data files that both take an infeasible amount of memory to keep in memory (they can be multiple gigs when unpacked into Python data structures) and take too much time to unpack on demand (20-30 sec to fully or iteratively unpack). In contrast, the files are small enough (dozens or hundreds of megs) to store completely in memory in binary form (or page in via memory-mapping if necessary), and structured so they require minimal unpacking to use in place from e.g. C. I've been reading some about buffers e.g. in the PEP, but there were a couple things that were not clear to me regarding using them to store structures in native form: I know buffers have associated Struct-style format definitions, but where exactly do they get converted to Python versions on access? Does Python do this automatically based on the format definition, or does the buffer exporter do this via getitem or some such? How much performance can you get out of using a buffer exporter to store large arrays of C structures? Would e.g. iterating over the entire file take the same amount of time as unpacking the entire file with Struct.unpack, or is it more efficient by various optimizations (e.g. if it were to only unpack a single structure element if you didn't access others within that structure)? Is it possible to do auto-conversion of odd data types during element access? Specifically, some of these file formats are fond of using odd-length integers (e.g. 5 bytes long) to avoid using a fixed-size larger integer type. Could this by transparently and efficiently converted, or would I have to convert this to a fixed size in the exporter when allocating the actual buffer to conform to the Struct definition?
favorite count: 0
tagged with: python-3.x
upvote count: 5
answer count: 0

http://stackoverflow.com/q/50963180
tagged with: python
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/50963326
tagged with: dataframe
has body: import pandas as pd data = {0: {'ID': 'A', 'Qty': 1, 'Type': 'SVGA'}, 1: {'ID': 'B', 'Qty': 2, 'Type': 'SVGA'}, 2: {'ID': 'B', 'Qty': 2, 'Type': 'XGA'}, 3: {'ID': 'C', 'Qty': 3, 'Type': 'XGA'}, 4: {'ID': 'D', 'Qty': 4, 'Type': 'XGA'}, 5: {'ID': 'A', 'Qty': 1, 'Type': 'LED'}, 6: {'ID': 'C', 'Qty': 3, 'Type': 'LED'}} df = pd.DataFrame.from_dict(data, orient='index') Is it possible to transform this dataframe to a duplicated matrix in sum. Expected output: LED SVGA XGA LED 4 1 3 SVGA 1 3 2 XGA 3 2 9
tagged with: pandas
has answer: http://stackoverflow.com/a/50963326
has title: Pandas dataframe to duplicated matrix in sum of quantities
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/88912750
comment on: http://stackoverflow.com/q/50957627
has text: When `health` reaches zero, your `while` condition becomes false, and the loop ends. Not sure why you expect anything else to happen.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89013021
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51009155
has text: I have just removed the std and scaled the lyrical data using **(X_train)/ mean_on_train** and it works. Is it alright?

http://stackoverflow.com/q/50962895
has comment: http://stackoverflow.com/comment/88926186
has title: iplot() is not working. Why ? If it need account?
has body: I just tried the code from https://plot.ly/python/gauge-charts/ but even though its not working. can u please guide me where i am going wrong ? I am new bee to python and plotly as well. Here's the code : import plotly.plotly as py import plotly.graph_objs as go from plotly.offline import * base_chart = { "values": [40, 10, 10, 10, 10, 10, 10], "labels": ["-", "0", "20", "40", "60", "80", "100"], "domain": {"x": [0, .48]}, "marker": { "colors": [ 'rgb(255, 255, 255)', 'rgb(255, 255, 255)', 'rgb(255, 255, 255)', 'rgb(255, 255, 255)', 'rgb(255, 255, 255)', 'rgb(255, 255, 255)', 'rgb(255, 255, 255)' ], "line": { "width": 1 } }, "name": "Gauge", "hole": .4, "type": "pie", "direction": "clockwise", "rotation": 108, "showlegend": False, "hoverinfo": "none", "textinfo": "label", "textposition": "outside" } meter_chart = { "values": [50, 10, 10, 10, 10, 10], "labels": ["Log Level", "Debug", "Info", "Warn", "Error", "Fatal"], "marker": { 'colors': [ 'rgb(255, 255, 255)', 'rgb(232,226,202)', 'rgb(226,210,172)', 'rgb(223,189,139)', 'rgb(223,162,103)', 'rgb(226,126,64)' ] }, "domain": {"x": [0, 0.48]}, "name": "Gauge", "hole": .3, "type": "pie", "direction": "clockwise", "rotation": 90, "showlegend": False, "textinfo": "label", "textposition": "inside", "hoverinfo": "none" } layout = { 'xaxis': { 'showticklabels': False, 'autotick': False, 'showgrid': False, 'zeroline': False, }, 'yaxis': { 'showticklabels': False, 'autotick': False, 'showgrid': False, 'zeroline': False, }, 'shapes': [ { 'type': 'path', 'path': 'M 0.235 0.5 L 0.24 0.65 L 0.245 0.5 Z', 'fillcolor': 'rgba(44, 160, 101, 0.5)', 'line': { 'width': 0.5 }, 'xref': 'paper', 'yref': 'paper' } ], 'annotations': [ { 'xref': 'paper', 'yref': 'paper', 'x': 0.23, 'y': 0.45, 'text': '50', 'showarrow': False } ] } # we don't want the boundary now base_chart['marker']['line']['width'] = 0 fig = {"data": [base_chart, meter_chart], "layout": layout} # fig.show() py.iplot(fig, filename='gauge-meter-chart') Error message is : Aw, s…
score: 0
answer count: 1
favorite count: 0
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
downvote count: 2
linked to: http://stackoverflow.com/q/42771076
tagged with: python
duplicate of: http://stackoverflow.com/q/42771076
has answer: http://stackoverflow.com/a/50966009
tagged with: plotly
has comment: http://stackoverflow.com/comment/88923214
type: Question

http://stackoverflow.com/q/50876784
has title: Unable to create file inside docker container using Python SDK
score: 0
answer count: 2
type: UnansweredQuestion
has body: I am unable to create a file inside a Docker container, using latest Python SDK on Ubuntu 16.04LTS. Here is what I do: I use the Docker CLI to create a container based on Ubuntu, on a Ubuntu 16.04LTS host machine; I create a createfile.py script which looks like this: import docker client = docker.from_env() container = client.containers.get('fbb206330c24') print container.exec_run(['echo', '123', '&gt;', '/var/abc.txt']) with fbb206330c24 being the id of the container. The output is: ExecResult(exit_code=0, output='123 &gt; /var/abc.txt\n') which looks OK to me. I then run the following command on the host machine to SSH to the container: docker exec -it fbb206330c24 bash then I try to look inside the /var directory, I expect there is an abc.txt file there. But there is none. What is the problem here?
tagged with: python
has answer: http://stackoverflow.com/a/71762684
has answer: http://stackoverflow.com/a/50877082
type: Question
tagged with: docker

http://stackoverflow.com/a/62538788
has body: This answer shows the python perspective. Jupyter supports various languages besides python. Both Jupyter Notebook and Jupyterlab are browser compatible interactive python (i.e. python ".ipynb" files) environments, where you can divide the various portions of the code into various individually executable cells for the sake of better readability. Both of these are popular in Data Science/Scientific Computing domain. I'd suggest you to go with Jupyterlab for the advantages over Jupyter notebooks: In Jupyterlab, you can create ".py" files, ".ipynb" files, open terminal etc. Jupyter Notebook allows ".ipynb" files while providing you the choice to choose "python 2" or "python 3". Jupyterlab can open multiple ".ipynb" files inside a single browser tab. Whereas, Jupyter Notebook will create new tab to open new ".ipynb" files every time. Hovering between various tabs of browser is tedious, thus Jupyterlab is more helpful here. I'd recommend using PIP to install Jupyterlab. If you can't open a ".ipynb" file using Jupyterlab on Windows system, here are the steps: Go to the file --> Right click --> Open With --> Choose another app --> More Apps --> Look for another apps on this PC --> Click. This will open a file explorer window. Now go inside your Python installation folder. You should see Scripts folder. Go inside it. Once you find jupyter-lab.exe, select that and now it will open the .ipynb files by default on your PC.
answers question: http://stackoverflow.com/q/50982686
score: 11
downvote count: 0
type: Answer
upvote count: 11

http://stackoverflow.com/q/50912070
type: Question
has comment: http://stackoverflow.com/comment/88824470
has answer: http://stackoverflow.com/a/50912185
tagged with: race-condition
answer count: 1
has body: I'm trying to demo a race condition in Python with following code but always get expected value 0. Is there something wrong with my code just it's just not "intensive" enough to trigger the race condition? Thank you. import threading import time def race_cond(): foo = 0 flag = threading.Event() def mutator(): flag.wait() nonlocal foo foo += 1 foo -= 1 foo += 1 ts = [threading.Thread(target=mutator) for i in range(10000)] [t.start() for t in ts] flag.set() [t.join() for t in ts] return foo for i in range(100): print(f'Expecting 10000, actual: {race_cond()}')
has comment: http://stackoverflow.com/comment/88825241
has title: Can't make race condition, is my code running sequentially?
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/88827514
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88829590
type: UnansweredQuestion
tagged with: multithreading

http://stackoverflow.com/a/50943026
score: 1
upvote count: 1
downvote count: 0
has body: I can't comment the response from @ajxs, but as additional information to his repsonse: You can change the default python interpreter like this in your MAC terminal: nano ~/.bash_profile Add this to the file: alias python=python3 exit the the bashrc file and run the following command: source ~/.bash_profile Now you can check the defaul python version with: python --version Maybe this helps you.
type: Answer
answers question: http://stackoverflow.com/q/50940411

http://stackoverflow.com/q/50963189
has comment: http://stackoverflow.com/comment/88923627
has answer: http://stackoverflow.com/a/50964328
tagged with: arrays
answer count: 2
has comment: http://stackoverflow.com/comment/88924387
has answer: http://stackoverflow.com/a/50964603
downvote count: 0
has body: I have some hard times learning Python array handling with numpy. I have a .csv file which contains in one column unsigned integer data which represents binary values from an analog digital converter. I would like to convert this unsigned integer values in 12 bit binary representation using Python inside a jupyter notebook. I tried several ways of implementing it, but I still fail... here is my code: import pandas as pd df = pd.read_csv('my_adc_values.csv', delimiter ='\s+', header=None, usecols=[19]) decimalValues = df.values print(decimalValues.shape) so far so good... I have all my adc data column values in the decimalValues numpy array. Now, I would like to iterate through the array and convert the integers in the array to a binary representation: import numpy as np # destination array of shape of source array binaryValues = np.zeros(decimalValues.shape) for i in range(len(decimalValues)): print(decimalValues[i]) binaryValues[i]=(bin(decimalValues[i])) print(binaryValues) With this code I get the error message --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-10-890444040b2e&gt; in &lt;module&gt;() 6 for i in range(len(decimalValues)): 7 print(decimalValues[i]) ----&gt; 8 binaryValues[i]=(bin(decimalValues[i])) 9 10 print(binaryValues) TypeError: only integer scalar arrays can be converted to a scalar index I tried several different solutions, but none of them worked. It seems as if I have a massive misunderstanding of numpy arrays. I'm looking for a tip on how to solve my described problem. I found some threads, describing the the mentioned error message. I suspected, it had something to do with the shape of the source/destination arrays. therefore, I initialized the destination array with the same shape as the source. It did not help... Thank you, Maik
favorite count: 0
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50964603
has title: Python numpy array operations
score: 1
upvote count: 1
possible better answer: http://stackoverflow.com/a/50964328
type: Question
tagged with: numpy

http://stackoverflow.com/comment/88727135
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/50862266
has text: word boundary doesn't rely on spaces. It relies on non-letters/non-digits/non-underscore/start or end of string.
type: Comment

http://stackoverflow.com/comment/88798554
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50899158
score: 0
has text: Imanol you're right. I'm trying to use matplotlib and pandas to write the code. Still don't know where to start. I know how to write a code for two datasets (such as two columns of X and Y) but here I have a trend of more than 2 datasets for each number.

http://stackoverflow.com/q/50998391
has body: Has anyone tried to use Python libraries in Swift with Xcode 10? Can they be used inside ios projects?
favorite count: 0
type: UnansweredQuestion
downvote count: 2
upvote count: 1
tagged with: python
tagged with: swift
has answer: http://stackoverflow.com/a/51016235
type: Question
score: -1
has title: Using Python libraries in Swift 4.2 and Xcode 10 for iOS projects
tagged with: xcode
answer count: 1

http://stackoverflow.com/a/55892589
has body: A bit late I know, but it might be that you are missing model.to(cuda)
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50965291

http://stackoverflow.com/comment/88809184
type: AnswerComment
comment on: http://stackoverflow.com/a/50904695
type: Comment
has text: One line: `np.split(list_2, np.cumsum(list_1)[:-1])`
score: 1

http://stackoverflow.com/comment/120479789
type: AnswerComment
has text: What is a word character? Is it a word or a char?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50932003

http://stackoverflow.com/comment/88721852
type: Comment
has text: @Guy.D the `after()` method only adds an command to the event list and will tell tkinter to not execute said command until a set amount of time has passed. It will not guarantee this will go of in exactly the time you mention but it will guarantee it will not go off before the time mentioned.
type: AnswerComment
comment on: http://stackoverflow.com/a/50859546
score: 0

http://stackoverflow.com/comment/88833540
comment on: http://stackoverflow.com/a/50916363
score: 0
type: AnswerComment
type: Comment
has text: An even nicer way to do this would be with `namedtuple` or `dataclass`, so you don't have to define those `__init__` and `__repr__` methods. Also, maybe a check to prevent you from meaninglessly adding two points (the same way `datetime + timedelta` and `timedelta + timedelta` are legal but `datetime + datetime` is not). But I think you've explained enough here that you don't need to go into even more detail…

http://stackoverflow.com/comment/88854876
has text: I wan to skip just ;foo. By the way, I have only one `[ word ]` line in the file.
score: 0
comment on: http://stackoverflow.com/q/50927581
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51007852
tagged with: function
accepted answer: http://stackoverflow.com/a/51007865
tagged with: dataframe
score: 0
has title: Pandas method to apply a function on the entire DataFrame
tagged with: pandas
answer count: 1
favorite count: 0
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/51007865
downvote count: 1
type: AnsweredQuestion
has body: I have created a function where I need to pass data frame I get shape and return me df.head() def shape_of_df(df): tup = df.shape print('Shape of df is Rows :{0[0]},column:{0[1]}'.format(tup)) return df.head() Now when I call function with items.apply(shape_of_df) I get error however if I call function and pass df as parameter it works fine. Please let me know I am missing something very basic when I use df.apply() couldn't figure out in docs shape_of_df(items) # this works fine prints shape and df.head()
tagged with: apply
type: Question

http://stackoverflow.com/comment/89012262
has text: why do you put 0 in {0}?
score: 0
comment on: http://stackoverflow.com/q/51009719
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50943214
type: Answer
has body: Your actual output and your expected output are in all important respects the same. &gt;&gt;&gt; a = ['Hi. How are you?', 'I am fine. What about you?', 'I am also good.', 'Good to hear that.', "Let's discuss last night's party.", "No. I don't think that will be healthy.", 'I agree with him.', "I don't think we are on the same page.", 'I think we should actually discuss it so that things get cleared.', 'Things may get messed up even more.', "It's better to sort out things.", 'Ya otherwise there will be a lot of misunderstanding..', 'Okay fine.', "That's the spirit!", "Same here. I think it's fine.", 'Finally we are all on the same page.', 'I am just happy we are all still friends.', "I don't want to lose you guys.", 'We will be friends forever.', 'Yeah'] &gt;&gt;&gt; b = ["Hi. How are you?","I am fine. What about you?", "I am also good.", "Good to hear that.", "Let's discuss last night's party.", "No. I don't think that will be healthy.", "I agree with him.", "I don't think we are on the same page.", "I think we should actually discuss it so that things get cleared.", "Things may get messed up even more.", "It's better to sort out things.", "Ya otherwise there will be a lot of misunderstanding..", "Okay fine.", "That's the spirit!", "Same here. I think it's fine.", "Finally we are all on the same page.", "I am just happy we are all still friends.", "I don't want to lose you guys.", "We will be friends forever.", "Yeah"] &gt;&gt;&gt; a == b True When you do print(Messages) you are relying on Python's built-in representation of lists of strings. It chooses to prefer ' over " in simple cases. It uses double quotes only in cases like "No. I don't think that will be healthy." If you want to see the list of strings in a different format on the screen then you have to do your own formatting. But there is really no need to do that. If you are planning to do further processing, what matters is the data structure and what is in it, not how its default representation appears on…
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/50942996
has comment: http://stackoverflow.com/comment/88885301
accepted answer of: http://stackoverflow.com/q/50942996
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88886026
has comment: http://stackoverflow.com/comment/88885722
has comment: http://stackoverflow.com/comment/88885923
upvote count: 1

tensorflow
tags question: http://stackoverflow.com/q/50970060
tags question: http://stackoverflow.com/q/50901159
tags question: http://stackoverflow.com/q/50995404
tags question: http://stackoverflow.com/q/50975389
tags question: http://stackoverflow.com/q/50860285
tags question: http://stackoverflow.com/q/50960970
tags question: http://stackoverflow.com/q/50902067
tags question: http://stackoverflow.com/q/50977818
tags question: http://stackoverflow.com/q/50953575
tags question: http://stackoverflow.com/q/50889192
tags question: http://stackoverflow.com/q/50940014
tags question: http://stackoverflow.com/q/50999880
tags question: http://stackoverflow.com/q/50986886
tags question: http://stackoverflow.com/q/50882282
tags question: http://stackoverflow.com/q/50903350
tags question: http://stackoverflow.com/q/50939425
tags question: http://stackoverflow.com/q/50858572
tags question: http://stackoverflow.com/q/50983008
tags question: http://stackoverflow.com/q/50911052
tags question: http://stackoverflow.com/q/50955127
tags question: http://stackoverflow.com/q/50953190
tags question: http://stackoverflow.com/q/50956392
tags question: http://stackoverflow.com/q/50864404
tags question: http://stackoverflow.com/q/50977844
tags question: http://stackoverflow.com/q/50917405
tags question: http://stackoverflow.com/q/50899488
tags question: http://stackoverflow.com/q/50997477
tags question: http://stackoverflow.com/q/51008505
tags question: http://stackoverflow.com/q/50967071
tags question: http://stackoverflow.com/q/50891957
tags question: http://stackoverflow.com/q/50975255
tags question: http://stackoverflow.com/q/51003745
tags question: http://stackoverflow.com/q/50948158
tags question: http://stackoverflow.com/q/50986580
tags question: http://stackoverflow.com/q/50880399
tags question: http://stackoverflow.com/q/50872501
tags question: http://stackoverflow.com/q/50955454
tags question: http://stackoverflow.com/q/50865774
tags question: http://stackoverflow.com/q/50863275
tags question: http://stackoverflow.com/q/50867992
tags question: http://stackoverflow.com/q/50913045
tags question: http://stackoverflow.com/q/50882259
tags question: http://stackoverflow.com/q/50961779
tags question: http://stackoverflow.com/q/50988466
tags question: http://stackoverflow.com/q/50919390
tags question: http://stackoverflow.com/q/50927890
tags question: http://stackoverflow.com/q/51004123
tags question: http://stackoverflow.com/q/50890836
tags question: http://stackoverflow.com/q/51003887
tags question: http://stackoverflow.com/q/50982287
tags question: http://stackoverflow.com/q/50987893
tags question: http://stackoverflow.com/q/51000885
tags question: http://stackoverflow.com/q/50974629
tags question: http://stackoverflow.com/q/50940768
tags question: http://stackoverflow.com/q/50895110
tags question: http://stackoverflow.com/q/50897646
tags question: http://stackoverflow.com/q/50996511
tags question: http://stackoverflow.com/q/50934465
tags question: http://stackoverflow.com/q/50911337
tags question: http://stackoverflow.com/q/50964833
tags question: http://stackoverflow.com/q/50874596
tags question: http://stackoverflow.com/q/50953092
tags question: http://stackoverflow.com/q/50975472
tags question: http://stackoverflow.com/q/50961821
tags question: http://stackoverflow.com/q/50862101
tags question: http://stackoverflow.com/q/51003207
tags question: http://stackoverflow.com/q/50916939
tags question: http://stackoverflow.com/q/50992771
tags question: http://stackoverflow.com/q/50975586
tags question: http://stackoverflow.com/q/50987530
tags question: http://stackoverflow.com/q/51004961
tags question: http://stackoverflow.com/q/50988462
tag name: tensorflow
tags question: http://stackoverflow.com/q/50884631
tags question: http://stackoverflow.com/q/50855256
tags question: http://stackoverflow.com/q/50858360
tags question: http://stackoverflow.com/q/50980113
tags question: http://stackoverflow.com/q/51010312
tags question: http://stackoverflow.com/q/50936396
tags question: http://stackoverflow.com/q/50919824

http://stackoverflow.com/a/50950856
score: 0
answers question: http://stackoverflow.com/q/50949238
has comment: http://stackoverflow.com/comment/88901812
type: Answer
has comment: http://stackoverflow.com/comment/88900495
has body: As noted in the comments, it looks like csv may not be the best format for what you are trying to do. If you already have an excel file with this information, perhaps consider python libraries that have been built for excel, like pandas. The answer to this question references arguments (i.e. sheet_name) that can be passed to the pandas read_excel function to make sure you are only using a specific sheet. import pandas as pd def QuestionGenerator(): questionlist_file = pd.ExcelFile('StudentNames.csv') sheet_of_interest = pd.read_excel(questionlist_file, 'Questions') ...

http://stackoverflow.com/comment/88726760
comment on: http://stackoverflow.com/q/50860869
score: 0
has text: thanks @hpaulj, the line is : emaInertia[i] = lambda_ * size + (1 - lambda_) * emaInertia[i-1]
type: QuestionComment
type: Comment

http://stackoverflow.com/q/50977442
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88951179
tagged with: hash
type: Question
tagged with: python
upvote count: 1
tagged with: checksum
has body: I'd like to be able to check for equality of two python codebases. I need to check imports (recursively) in case any of them are different, including differences in stdlib versions (although I don't care about differences of the Python interpreter itself). I have nixed the idea of simply walking my /source/ directory and computing the checksum of each file, because there may be source files that are unused. I can use the ast lib to walk all the import declarations, but I don't know how to get the AST of a stdlib, even if I do (dangerously) resolve the lib names to their respective filenames. What are my options?
type: UnansweredQuestion
has title: Compute checksum of python script/module and all recursive imports, including standard libs
answer count: 0
downvote count: 0
score: 1

http://stackoverflow.com/q/51000927
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89010078
tagged with: python
has comment: http://stackoverflow.com/comment/88995725
has body: I've got a string with multiple ip addresses together with some random stuff. For example like this one: 21/Jun/2018:01:15:38 +0000 188.79.169.152 157.52.69.50 443 - - GET / 157.52.69.30 157.52.69.10 And got this regex: [0-9]+(?:\.[0-9]+){3} Problem is that this matches multiple times, but I don't need that. What is missing with this regex so it will only match once? Thanks,
linked to: http://stackoverflow.com/q/17466927
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88995644
has comment: http://stackoverflow.com/comment/88996628
has title: Regex: match only once
score: -1
tagged with: python-2.7
has answer: http://stackoverflow.com/a/51001662
upvote count: 0
answer count: 1

http://stackoverflow.com/q/50948075
has body: I have millions of domains which I will send WHOIS query and record WHOIS response on some .txt file. I would like to set maximum capacity for a single .txt output file. For example, let's say I started recording responses on out0.txt. I want to switch to out1.txt if out0.txt is >= 100mb. Same thing goes for out1.txt, if out1.txt>=100mb then start writing to out2.txtand so on. I know that I can do if checks after each insertion, but I want my code to be fast: i.e. I thought if checks at each domain can slow down my code. (It will asynchronously query millions of domains). I imagined a try-except block could solve my issue here, like this: folder_name = "out%s.txt" folder_number = 0 folder_name = folder_name % folder_number f = open(folder_name, 'w+') for domain in millions_of_domains: try: response_json = send_whois_query(domain) f.write(response_json) except FileGreaterThan100MbException: folder_number += 1 folder_name = folder_name % folder_number f = open(folder_name, 'w+') f.write(response_json) Any suggestions will be appreciated. Thank you for your time.
has comment: http://stackoverflow.com/comment/88894099
has title: writing to files: switch to new file after X MB file capacity
has comment: http://stackoverflow.com/comment/88894219
score: 0
accepted answer: http://stackoverflow.com/a/50948419
tagged with: exception
has comment: http://stackoverflow.com/comment/88894382
tagged with: io
answer count: 1
linked to: http://stackoverflow.com/q/12451431
has comment: http://stackoverflow.com/comment/88897776
has answer: http://stackoverflow.com/a/50948419
tagged with: file
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88894168
has comment: http://stackoverflow.com/comment/88897992
has comment: http://stackoverflow.com/comment/88894291
has comment: http://stackoverflow.com/comment/88894147
type: Question

http://stackoverflow.com/comment/88990388
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50998118
has text: if your condition is ( if random() < mutation_rate:) its false you try assing "b" value, but "b" is not created, you must be defined it previously
type: Comment

http://stackoverflow.com/a/51038249
answers question: http://stackoverflow.com/q/50984829
has body: Finally I was able to figure out the problem was with the mistral-server service running on the stackstorm host. The problem was that the mistral-server service was not able to connect to rabbitmq service due to a misconfiguration during stackstorm installation.But the misleading error message "AccessRefused: 403" did not pin point towards an issue with rabbitmq connection issue. So here is what I found in the logs. The error message in the mistral logs (/var/log/mistral/): 2018-06-25 15:30:19.309 10767 ERROR oslo_service.service AccessRefused: (0,0): (403) ACCESS_REFUSED - Login was refused using authentication mechanism AMQPLAIN. For details see the broker logfile. On digging the rabbitmq logs (/var/log/rabbitmq/): =ERROR REPORT==== 25-Jun-2018::16:34:23 === closing AMQP connection &lt;0.5118.0&gt; (127.0.0.1:41248 -&gt; 127.0.0.1:5672): {handshake_error,starting,0, {amqp_error,access_refused, "AMQPLAIN login refused: user 'st2' - invalid credentials", 'connection.start_ok'}} Clearly the st2 user credentials were wrongly configured during installation and that led to this whole issue. Hope this helps somebody in future.
type: Answer
score: 0

http://stackoverflow.com/comment/88793488
comment on: http://stackoverflow.com/q/50896798
type: QuestionComment
type: Comment
has text: It accepts the following; batch, data1, data2, data3
score: 0

http://stackoverflow.com/comment/88871518
comment on: http://stackoverflow.com/q/50867489
score: 0
type: QuestionComment
has text: @CristiFati: Sure, here: https://github.com/swig/swig/blob/master/Lib/python/pybuffer.i
type: Comment

http://stackoverflow.com/q/50987446
downvote count: 0
favorite count: 0
tagged with: python
score: 2
has title: Is it wrong practice to modify self inside functions (8-puzzle game)?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88969415
has comment: http://stackoverflow.com/comment/88969438
has comment: http://stackoverflow.com/comment/88969557
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/50997053
accepted answer: http://stackoverflow.com/a/50997053
has body: I was trying to make my own solution for 8 puzzle game. Online I found mostly solutions with return statements. Is it wrong practice to code this way ? import numpy as np class Game(object): def __init__(self, n, config): array = np.array(config) self.board = array.reshape((n, n)) blank = np.where(self.board == 0) self.blanky = int(blank[0]) self.blankx = int(blank[1]) self.n = n def move_up(self): if self.blanky - 1 &lt; 0: return None ay, ax = self.blanky, self.blankx by, bx = self.blanky - 1, self.blankx self.board[ay, ax], self.board[by, bx] = self.board[by, bx], self.board[ay, ax] self.blanky = self.blanky - 1 def move_down(self): if self.blanky + 1 &gt; n: return None ay, ax = self.blanky, self.blankx by, bx = self.blanky + 1, self.blankx self.board[ay, ax], self.board[by, bx] = self.board[by, bx], self.board[ay, ax] self.blanky = self.blanky + 1 def move_left(self): if self.blankx - 1 &lt; 0: return None ay, ax = self.blanky, self.blankx by, bx = self.blanky, self.blankx - 1 self.board[ay, ax], self.board[by, bx] = self.board[by, bx], self.board[ay, ax] self.blankx = self.blankx - 1 def move_right(self): if self.blankx - 1 &lt; 0: return None ay, ax = self.blanky, self.blankx by, bx = self.blanky, self.blankx + 1 self.board[ay, ax], self.board[by, bx] = self.board[by, bx], self.board[ay, ax] self.blankx = self.blankx + 1 def visualise(self): return(self.board)
tagged with: sliding-tile-puzzle
answer count: 1

http://stackoverflow.com/comment/88893856
type: QuestionComment
has text: You could collect all the `dfslice` into a list. And call `np.concatenate` on this list once outside the loop.
comment on: http://stackoverflow.com/q/50946636
score: 1
type: Comment

http://stackoverflow.com/q/50918660
has answer: http://stackoverflow.com/a/50918847
upvote count: 0
has comment: http://stackoverflow.com/comment/88837374
type: Question
has comment: http://stackoverflow.com/comment/88837486
has comment: http://stackoverflow.com/comment/88837460
tagged with: if-statement
score: -1
answer count: 2
has comment: http://stackoverflow.com/comment/88837317
has body: Here is my code: def midterm_1(): print("Midterm 1:") weight_1=int(input("Weight 0-100?")) score_earned=int(input("Score earned?")) score_shift=int(input("Were scores shifted (1=yes 2=no)?")) if (score_shift==1): shift_amount=int(input("What was the shift amount?")) score_earned=int(shift_amount)+int(score_earned) if (score_earned &gt;100): score_earned=100 print("Total points = "+str(score_earned)+str("/100")) weighted_score=int((score_earned/100)*weight_1) print("Your weighted score = "+str(weighted_score)+"/"+str(weight_1)) This code is supposed to be apart of a larger code to compute grade. When the weighted score is printed it only regards score_earned as a 100 or 0. How should I fix this? Here is an example output when there is not score shift: Midterm 1: Weight 0-100? 50 Score earned? 78 Were scores shifted (1=yes 2=no)? 2 Total points = 78/100 Your weighted score = 0/50 When there is a score shift and score_earned is over 100: Midterm 1: Weight 0-100? 89 Score earned? 89 Were scores shifted (1=yes 2=no)? 1 What was the shift amount? 90 Total points = 100/100 Your weighted score = 89/89
downvote count: 1
has comment: http://stackoverflow.com/comment/88837345
has answer: http://stackoverflow.com/a/50918809
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has title: python ignoring if statement in grade calculator

pygobject
type: Tag
tags question: http://stackoverflow.com/q/50857102
tag name: pygobject

http://stackoverflow.com/q/50912978
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/88826337
has title: Different pixel information in PIL and cv2
has comment: http://stackoverflow.com/comment/88826423
tagged with: python
has answer: http://stackoverflow.com/a/50913155
has body: I have load the same image using both PIL and cv2, but the pixel information is different for the same index. Here is my code: import cv2 from PIL import Image img = cv2.imread('Fruits1.jpg') # Can be many different formats. print(img[100, 200]) img = Image.open('Fruits1.jpg') pixel_img = img.load() print(pixel_img[100, 200]) Output: [191 212 209] (255, 255, 255) Shouldn't the numbers of RGB channels be the same both cases? This is the image I used.
type: AnsweredQuestion
upvote count: 3
type: Question
tagged with: opencv
score: 3
tagged with: python-imaging-library
accepted answer: http://stackoverflow.com/a/50913155

http://stackoverflow.com/comment/88713667
comment on: http://stackoverflow.com/a/50855377
type: Comment
has text: @CristiFati...its just an example :)
score: 0
type: AnswerComment

http://stackoverflow.com/q/50973529
score: 0
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/88943720
favorite count: 0
has comment: http://stackoverflow.com/comment/88943648
type: UnansweredQuestion
tagged with: python
has title: updating the dataset file in python
has body: I want to update the values of Data.csv with the new values of x and y. How can I update this dataset? import numpy as np import matplotlib.pyplot as plt import pandas as pd dataset= pd.read_csv('Data.csv') x=dataset.iloc[: , :-1].values y=dataset.iloc[:, 3].values from sklearn.preprocessing import Imputer imputer = Imputer(missing_values='NaN', strategy='mean', axis=0) imputer = imputer.fit(x[ : , 1:3]) x[:, 1:3]= imputer.transform(x[:, 1:3])
has answer: http://stackoverflow.com/a/50975719
upvote count: 2
downvote count: 2
type: Question
has comment: http://stackoverflow.com/comment/88943392

http://stackoverflow.com/q/50995733
downvote count: 0
favorite count: 0
has body: My dataframe sort of: Date AAPL NFLX INTC 0 2008-01-02 27.834286 3.764286 25.350000 1 2008-01-03 27.847143 3.724286 24.670000 2 2008-01-04 25.721428 3.515714 22.670000 3 2008-01-07 25.377142 3.554286 22.879999 4 2008-01-08 24.464285 3.328571 22.260000 I want to run .pct_change(1) to each of the stocks in each column, and append the 3 columns to the end of the df. I know how to do it when I already know the name of the column, say AAPL. With that prior knowledge, I can do df['AAPL_Ret'] = df.AAPL.pct_change(1) But eventually, I will have 100s of stocks in the file and the goal is to automate the calculations without having to individually type each stock ticker in the code. So I would have to iterate through all the columns and then run the .pct_change somehow. Any ideas? Many thanks.
accepted answer: http://stackoverflow.com/a/50995869
tagged with: python
has answer: http://stackoverflow.com/a/50995756
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50995757
upvote count: 3
has answer: http://stackoverflow.com/a/50995869
type: Question
score: 3
tagged with: dataframe
possible better answer: http://stackoverflow.com/a/50995756
has title: Iterating over columns in a dataframe to run/append calculation
answer count: 3
tagged with: pandas

http://stackoverflow.com/comment/88858982
score: 0
comment on: http://stackoverflow.com/q/50929968
type: Comment
type: QuestionComment
has text: Are you writing this in Python3 or Python2?

http://stackoverflow.com/q/50918185
answer count: 1
accepted answer: http://stackoverflow.com/a/50918226
favorite count: 0
upvote count: 2
tagged with: python
score: 2
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/50918226
type: Question
has title: Convert sql table to json
tagged with: pandas
tagged with: sql
has body: I am trying to fetch data from mysql server, and to save it as json. BUT somehow when transforming to json, date format gets lost. Look at start &amp; end in data and output. Making connection: import pandas as pd import pymysql from pandas import * con='mysql+pymysql://username:password@host/table' data=pd.read_sql_query('SELECT * FROM calendar_table',con) data i get looks like: id title start end client 0 1 somethinginterestin 2018-06-21 12:00:00 2018-06-21 16:20:00 suja 1 2 vusce 2018-06-21 15:00:00 2018-06-22 08:00:00 vuscec then i used pandas to create json file x = data.to_json(orient='records') f = open("sqltable.json","w+") f.write(x) f.close() the file output [{"id":1,"title":"somethinginterestin","start":1529582400000,"end":1529598000000,"client":"suja"}, {"id":2,"title":"vusce","start":1529593200000,"end":1529654400000,"client":"vuscec"}]
downvote count: 0

http://stackoverflow.com/q/50926474
answer count: 0
has body: I have trained the face API using person_group.train() method. Then I have used person_group.status() to get the status of training but it showed: {'status': 'failed', 'createdDateTime': '6/19/2018 10:34:40 AM', 'lastActionDateTime': '06/19/2018 10:34:40', 'message': 'There is no persisted faces of person in group 22'} What could be the problem?
type: Question
has comment: http://stackoverflow.com/comment/89455546
has comment: http://stackoverflow.com/comment/89370278
score: 0
tagged with: face-api
has title: Python - Face Api by microsoft - there is no persisted faces of person
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/88971255
has text: with `POINTER(c_char) * MAX_PARAM_NAME` I get an error `TypeError: cast() argument 2 must be a pointer type, not LP_c_char_Array_10`. do you mind to include the correct version into your answer, so I can tick it solved?
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50988051

http://stackoverflow.com/comment/88768734
comment on: http://stackoverflow.com/a/50883285
has text: you might want to make your regex a bit more generalized to allow it to be truly more advantageous to a substring approach. eg: allow it to process `Face book`, `face book` and `Face Book` . :)
type: Comment
score: 3
type: AnswerComment

http://stackoverflow.com/a/50891049
type: Answer
answers question: http://stackoverflow.com/q/50890836
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50890836
type: AcceptedAnswer
has body: Let's try to break it down and I'll cover only Keras specific bits: How does Keras update weights? Using an Optimiser which is a base class for different optimisers. Each optimiser calculates the new weights, under a function get_updates which returns a list of functions when run applies the updates. Back-propagation? Yes, but Keras doesn't implement it directly, it leaves it for the backend tensor libraries to perform automatic differentiation. For example K.gradients calls tf.gradients in the Tensorflow backend. SGD algorithm? It is implemented as expected on Wikipedia in the SGD class with the basic extensions such as momentum. You can follow the code easily and how it calculates the updates. How gradient is calculated? Using back-propagation.
downvote count: 0
has comment: http://stackoverflow.com/comment/88783254

http://stackoverflow.com/a/50923959
has comment: http://stackoverflow.com/comment/102978157
downvote count: 0
score: 16
has body: To show video streaming inside frame in tkinter, I feel the easiest way is using PIL library.... from Tkinter import * from PIL import ImageTk, Image import cv2 root = Tk() # Create a frame app = Frame(root, bg="white") app.grid() # Create a label in the frame lmain = Label(app) lmain.grid() # Capture from camera cap = cv2.VideoCapture(0) # function for video streaming def video_stream(): _, frame = cap.read() cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA) img = Image.fromarray(cv2image) imgtk = ImageTk.PhotoImage(image=img) lmain.imgtk = imgtk lmain.configure(image=imgtk) lmain.after(1, video_stream) video_stream() root.mainloop() You can install PIL using pip - pip install Pillow
has comment: http://stackoverflow.com/comment/139353342
answers question: http://stackoverflow.com/q/50922175
upvote count: 16
type: Answer

http://stackoverflow.com/q/50959006
has comment: http://stackoverflow.com/comment/88915492
has comment: http://stackoverflow.com/comment/88915548
has title: Best way to scrape a list of data from a website with python
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/50960762
has body: I'm scraping data from a web page for use in an API and looking for the most pythonic / appropriate way to do it - The page source has a list of dictionaries titled 'markerData' and I need to grab the lat and lng values. Data Sample: "markerData": [{"docEl":null,"lid":0,"clickable":true,"lat":34.0489281,"lng":-111.0937311,"title":"","iconURL":"//assets.bankofamerica.com/images/mapmarker2.png","info":"&lt;/div>View all locations in Arizona&lt;/a>&lt;/div>&lt;/div>&lt;/div>&lt;/div>&lt;/div>"}, {"docEl":null,"lid":1,"clickable":true,"lat":35.20105,"lng":-91.8318334,"title":"","iconURL":"//assets.bankofamerica.com/images/mapmarker2.png","info":"&lt;/div>View all locations in Arkansas&lt;/a>&lt;/div>&lt;/div>&lt;/div>&lt;/div>&lt;/div>"}, I've used python's lxml module a few times in the past for this kind of task, however seeing as my 'markerData' isn't an obvious html structure I'm trying to figure out the best way to proceed. Specifically, in the function below, I am stuck attempting to define the tree.xpath for each of my lat and lng values. lats = [] lngs = [] def get_coordinates(): i = 0 while i &lt; 35: page = requests.get('https://locators.bankofamerica.com/&amp;check_list=4429#') tree = html.fromstring(page.content) lat = tree.xpath('//div[@id=mapWrap/markerData/lat/text()'.format(i)) lng = tree.xpath('//div[@id=mapWrap/markerData/lng/text()'.format(i)) str1 = ''.join(lat) str2 = ''.join(lng) lats.append(str1) lngs.append(str2) i += 1 return lats, lngs I also can't fight the feeling there might be an easier way to do this such as reading the entire page-source into a text file and trying to grab just the 'markerData' list. I would appreciate any help in defining an xpath for my lat and lng values, or any alternative ideas on how to isolate and capture this data.
favorite count: 0
tagged with: lxml
tagged with: http://stackoverflow.com/tag/html
tagged with: python
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/88915722
accepted answer: http://stackoverflow.com/a/50960762
tagged with: web-scraping
tagged with: python-requests
has comment: http://stackoverflow.com/comment/88915487
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88915556
has comment: http://stackoverflow.com/comment/88915499
type: Question

state
tag name: state
tags question: http://stackoverflow.com/q/50899563
type: Tag

http://stackoverflow.com/q/50989592
downvote count: 0
has body: When I start Visual Studio Code with a python file I started getting the following error The environment variable 'Path' seems to have some paths containing characters (';', '"' or ';;'). The existence of such characters are known to have caused the Python extension to not load. If the extension fails to load please modify your paths to remove these characters. I checked my path and I did indeed have a ;; appearing. I removed it but, I'm still getting the error. Here is my current path. PATH=C:\ProgramData\Oracle\Java\javapath;C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files (x86)\Common Files\Lenovo;C:\SWTOOLS\ReadyApps;C:\Program Files\Calibre2\;c:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\;c:\Program Files (x86)\Microsoft SQL Server\100\DTS\Binn\;C:\Program Files (x86)\Skype\Phone\;C:\Program Files\IDM Computer Solutions\UltraEdit;C:\Users\Dave\.dnx\bin;C:\Program Files\Microsoft DNX\Dnvm\;C:\Program Files\Git\cmd;C:\WINDOWS\System32\OpenSSH\;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\Program Files (x86)\Sophos\Sophos SSL VPN Client\bin;C:\Users\Dave\AppData\Local\atom\bin;C:\Users\Dave\AppData\Local\Microsoft\WindowsApps;C:\sqlite;C:\Python36\Scripts;C:\Program Files\Microsoft VS Code\bin;C:\Python36;
linked to: http://stackoverflow.com/q/41454769
has answer: http://stackoverflow.com/a/53037094
favorite count: 0
has answer: http://stackoverflow.com/a/75390697
has answer: http://stackoverflow.com/a/51028752
answer count: 9
has answer: http://stackoverflow.com/a/71404731
type: UnansweredQuestion
tagged with: windows
tagged with: path
has answer: http://stackoverflow.com/a/65025125
has comment: http://stackoverflow.com/comment/88989951
tagged with: python
has title: VS Code python extension recently started complaining about a Path error on Win10
upvote count: 14
linked to: http://stackoverflow.com/q/26386697
has answer: http://stackoverflow.com/a/71741654
type: Question
score: 14
has answer: http://stackoverflow.com/a/78569362
has answer: http://stackoverflow.com/a/78510112
has answer: http://stackoverflow.com/a/54273454
tagged with: visual-studio-code

http://stackoverflow.com/q/50989767
upvote count: 2
has comment: http://stackoverflow.com/comment/88974239
has comment: http://stackoverflow.com/comment/88974764
score: 1
tagged with: matplotlib
downvote count: 1
type: Question
linked to: http://stackoverflow.com/q/32185411
has body: I am drawing x-y plots and say my x-axis ranges from 0-2000. I am more interested in showing the behavior from x = say 0-10 and then x = 1500 - 2000. And x = 11-1499 is not of much interest to me. However, I still want to keep that in the figure. So I want that if I can have more ticks(and widened axis) for x = 0 - 10 and and 1500-2000 and x = 11-1499 just a normal axis. I could think of two ways -- Make x-axis logscale. This helps me elaborate only 0-10. Introduce break in the x-axis as suggested here. However, this removes middle part and I don't want that too.
has comment: http://stackoverflow.com/comment/88974828
favorite count: 0
has title: Widen extremes of x-axis and compress lower part
type: UnansweredQuestion
tagged with: python
answer count: 0

http://stackoverflow.com/a/51007243
answers question: http://stackoverflow.com/q/51007157
has comment: http://stackoverflow.com/comment/89007724
downvote count: 0
type: Answer
has body: Try this. I also left some comments in the code. import io # just for testing from operator import itemgetter # just for testing file_content = """Name #3 is Bob Name #7 is Marie Name #8 is Kate Name #2 is George """ # replace io.StringIO with open("Sentences.dat","r") file = io.StringIO(file_content) # just for testing names = dict() ig = itemgetter(1, 3) with file: # make sure file is closed after parsing using with for line in file: line = line.strip() # skip empty lines if not line: continue # itemgetter is optional but fast and worth knowing hash_number, name = ig(line.split()) number = int(hash_number[1:]) names[number] = name print(names) # just for testing Result: {3: 'Bob', 7: 'Marie', 8: 'Kate', 2: 'George'}
score: 1
upvote count: 1

http://stackoverflow.com/comment/88735837
comment on: http://stackoverflow.com/q/50866754
score: 1
type: Comment
type: QuestionComment
has text: I already answered but I have a question. Don't your cards also need suites?

http://stackoverflow.com/q/50918102
has title: invalid header error using DataStax cassandra driver within docker
has comment: http://stackoverflow.com/comment/88861581
has comment: http://stackoverflow.com/comment/88837721
tagged with: docker
type: Question
tagged with: datastax
has comment: http://stackoverflow.com/comment/88870081
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/88862992
tagged with: cassandra
tagged with: python
score: 2
answer count: 0
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88870569
has body: We have a python application which makes a connection to a cassandra cluster. The python application runs within docker and we are using the datastax driver to make an attempt to connect to our cassandra cluster. This is what we are getting: ValueError('Invalid size in header: 0x0',)

http://stackoverflow.com/q/50913866
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50914030
possible better answer: http://stackoverflow.com/a/59721910
type: Question
has comment: http://stackoverflow.com/comment/88828649
has comment: http://stackoverflow.com/comment/88828476
answer count: 6
favorite count: 0
has comment: http://stackoverflow.com/comment/88828675
has answer: http://stackoverflow.com/a/50913984
tagged with: glob
has comment: http://stackoverflow.com/comment/88828610
has answer: http://stackoverflow.com/a/50913962
has title: Getting file names without file extensions with glob
has body: I'm searching for .txt files only from glob import glob result = glob('*.txt') &gt;&gt; result ['text1.txt','text2.txt','text3.txt'] but I'd like result without the file extensions &gt;&gt; result ['text1','text2','text3'] Is there a regex pattern that I can use with glob to exclude the file extensions from the output, or do I have to use a list comprehension on result?
upvote count: 3
has answer: http://stackoverflow.com/a/50913922
has comment: http://stackoverflow.com/comment/88828584
tagged with: python
has answer: http://stackoverflow.com/a/50914030
downvote count: 1
has answer: http://stackoverflow.com/a/50914106
has answer: http://stackoverflow.com/a/59721910

http://stackoverflow.com/comment/88760190
type: QuestionComment
has text: Try upgrading to the latest tf.js version (0.11.6). If it still doesn't work, your saved model is using a Lamba layer, which isn't implemented in tfjs yet.
comment on: http://stackoverflow.com/q/50878885
type: Comment
score: 0

http://stackoverflow.com/comment/88819843
type: Comment
has text: I will carefully consider your comment.
comment on: http://stackoverflow.com/a/50899421
score: 0
type: AnswerComment

http://stackoverflow.com/comment/96470808
type: AnswerComment
has text: You are right. Seems that `pip` is designed not deleting files that generated during runtime. The word `Would not remove (might be manually added)` in the source code implies this design manner.
type: Comment
comment on: http://stackoverflow.com/a/54739807
score: 1

http://stackoverflow.com/q/50959533
tagged with: matplotlib
has title: How can I display and update two matplotlib plots in the same window at the same time? (Part 2)
linked to: http://stackoverflow.com/q/50943483
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/50965586
score: 0
has body: Continuation from this question: How can I display and update two matplotlib plots in the same window at the same time? Previous solution hasn't fixed all plot updating issues. Though "plt" can be replaced with self.comparison_figure1 when using tight_layout(), the same cannot be done when using cla() to clear the plot. As a result my second graph will be cleared and updated when I choose other options from the dropdown menu, but the first graph won't be cleared and updated because "plt" no longer references to the first graph. Portion of Code where I'm using cla(): sns.set(style="whitegrid") plt.cla() ax = self.comparison_figure2.add_subplot(111) ..... I can post more code if you need it!
tagged with: python
possible better answer: http://stackoverflow.com/a/50960448
has answer: http://stackoverflow.com/a/50960448
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50965586

http://stackoverflow.com/a/50975824
type: Answer
downvote count: 0
has body: The problem with using Label() on the canvas is the label itself has its own background and will always be at the same level as the text so you cannot overlap your canvas image behind the text. However canvas has a method called create_text that will draw the text directly on the canvas instead of using a label. Here is an example using create_text for canvas. In the create_text method the first 2 arguments are coordinates then all you need is the text font and fill is the color. import tkinter as tk root = tk.Tk() canvas = tk.Canvas(root, width=800, height=650, bg="darkgrey") canvas.create_oval(-300, 1600, 4000, 200, fill="gray38", outline="gray38", width=4) canvas.create_text(400,325, text="FITNESS FIRST", font=("Purisa", 60),fill="white") canvas.pack() root.mainloop() Results:
score: 1
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88948478
accepted answer of: http://stackoverflow.com/q/50973137
has comment: http://stackoverflow.com/comment/88948437
answers question: http://stackoverflow.com/q/50973137

http://stackoverflow.com/q/50994565
downvote count: 0
favorite count: 0
has title: How to use Mobilenium python module with selenium
has body: I am trying to use the mobilenium python package with selenium but am getting ImportError: cannot import name 'mobidriver' I installed using pip install mobilenium and there was no errors. My python code is as follows: from mobilenium import mobidriver
linked to: http://stackoverflow.com/q/15796855
tagged with: python
accepted answer: http://stackoverflow.com/a/50994788
tagged with: selenium
upvote count: 1
type: AnsweredQuestion
score: 1
type: Question
has answer: http://stackoverflow.com/a/50994788
answer count: 1

http://stackoverflow.com/a/50894132
answers question: http://stackoverflow.com/q/50894078
score: 4
has comment: http://stackoverflow.com/comment/88788761
upvote count: 4
accepted answer of: http://stackoverflow.com/q/50894078
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88789669
has comment: http://stackoverflow.com/comment/88789456
has body: There is no need of try-except blocks. Check if user input is a number in list and if so, exit the infinite loop: def gettriptime(): lst = [1000, 1100, 1200, 1300 , 1400, 1500, 1600, 1700] while True: ch = int(input(""" Trip Times: 1000 1100 1200 1300 1400 1500 1600 1700 Please enter trip time: """)) if ch in lst: return ch ch = gettriptime() Or even better (without creating a list of your own) take advantage of range: def gettriptime(): while True: ch = int(input(""" Trip Times: 1000 1100 1200 1300 1400 1500 1600 1700 Please enter trip time: """)) if ch in range(1000, 1800, 100): return ch ch = gettriptime() Also you may note to get the returned value to a variable, otherwise it's wasted. gettriptime() -> ch = gettriptime()
type: Answer

http://stackoverflow.com/comment/88836969
type: QuestionComment
score: 1
has text: What happens when you run this code and how does it differ from your expected result?
comment on: http://stackoverflow.com/q/50918419
type: Comment

http://stackoverflow.com/a/57292987
answers question: http://stackoverflow.com/q/50992713
downvote count: 0
score: 30
upvote count: 30
type: Answer
has comment: http://stackoverflow.com/comment/129189938
has body: df = spark.createDataFrame([(1, float('nan')), (None, 1.0)], ("a", "b")) df.show() +----+---+ | a| b| +----+---+ | 1|NaN| |null|1.0| +----+---+ df = df.replace(float('nan'), None) df.show() +----+----+ | a| b| +----+----+ | 1|null| |null| 1.0| +----+----+ You can use the .replace function to change to null values in one line of code.

http://stackoverflow.com/a/50999309
has comment: http://stackoverflow.com/comment/88992683
has comment: http://stackoverflow.com/comment/88993078
has comment: http://stackoverflow.com/comment/88992865
upvote count: 1
has comment: http://stackoverflow.com/comment/88992894
has comment: http://stackoverflow.com/comment/88992892
has comment: http://stackoverflow.com/comment/88992851
type: Answer
has body: You can use a dictionary instead. There's a few steps here: We want to map every number to a character, so we can create a dictionary with the input characters as keys and the output characters as values. You can't iterate a numerical input, so we have to convert it to a string to access each character in turn. In your example the value is already a string ('123') but there's no reason you can't make the function accept both numerical and string inputs. The replacement is done in a list comprehension, which naturally returns a list. So you need to call join() to join all of the characters back together into a single string. One approach is as follows: def number2char(number): search_array = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"] replace_array = ["a", "b", "c", "d", "d", "e", "f", "g", "h", "i"] replace_dict = dict(zip(search_array, replace_array)) num_2_char = ''.join([replace_dict.get(char, '_') for char in str(number)]) return num_2_char a = number2char(123) In this case I've used replace_dict.get(str(item), '_') so that the code doesn't crash if someone gives an input that isn't in the replace_dict; instead they just get back underscores. There's probably better ways to handle that, but it's safer than just trying to access the dictionary as replace_dict[item].
has comment: http://stackoverflow.com/comment/88992796
has comment: http://stackoverflow.com/comment/88993035
has comment: http://stackoverflow.com/comment/88992773
downvote count: 0
has comment: http://stackoverflow.com/comment/88992743
has comment: http://stackoverflow.com/comment/88992887
has comment: http://stackoverflow.com/comment/88993175
has comment: http://stackoverflow.com/comment/88992866
has comment: http://stackoverflow.com/comment/88992728
has comment: http://stackoverflow.com/comment/88992754
answers question: http://stackoverflow.com/q/50999282
score: 1
has comment: http://stackoverflow.com/comment/88992697

http://stackoverflow.com/a/50897569
accepted answer of: http://stackoverflow.com/q/50897552
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/50897552
has body: Given: x = [1,2,3,4,5,6,7] y = [2,1,4,5,8,10] z = [7,1,3,6,0] Try: x = set([1,2,3,4,5,6,7]) y = set([2,1,4,5,8,10]) z = set([7,1,3,6,0]) Then you can find the intersections by: xy = x.intersection(y) xyz = x.intersection(y).intersection(z) # and xyz = x &amp; y &amp; z See also: https://docs.python.org/2/library/sets.html#set-objects All the deltas : I have used the convention 'x_' for 'NOT in x' x_y_z = z.difference(x).difference(y) x_yz_ = y.difference(x).difference(z) x_yz = y.intersection(z).difference(x) xy_z_ = x.difference(y).difference(z) xy_z = x.difference(y).intersection(z) xyz_ = x.intersection(y).difference(z) xyz = x.intersection(y).intersection(z)
downvote count: 0
has comment: http://stackoverflow.com/comment/88794961
has comment: http://stackoverflow.com/comment/88794842
has comment: http://stackoverflow.com/comment/88794933
score: 4
type: AcceptedAnswer

http://stackoverflow.com/q/50943935
score: 1
has body: Actually, I am not clear that fig_1 = plt.figure() plt.subplot(2,2,1) ... Is the ploting like plt.subplot(2,2,1) and other plt. plot on the fig_1 or system will automatically create a new empty figure? Then how to plot something in a specific figure, for example: fig_1 = plt.figure() fig_2 = plt.figure() plt.subplot(2,2,1) I want to subplot on fig_2.
favorite count: 0
has answer: http://stackoverflow.com/a/50944273
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/50944280
has comment: http://stackoverflow.com/comment/88887270
upvote count: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/50944273
has comment: http://stackoverflow.com/comment/88886465
tagged with: matplotlib
has answer: http://stackoverflow.com/a/50944280
linked to: http://stackoverflow.com/q/50834216
type: AnsweredQuestion
has title: plot graph in a specific figure in python
downvote count: 0
has comment: http://stackoverflow.com/comment/88886131

dataframe
tags question: http://stackoverflow.com/q/50947684
tags question: http://stackoverflow.com/q/50995733
tags question: http://stackoverflow.com/q/50934089
tags question: http://stackoverflow.com/q/50986448
tags question: http://stackoverflow.com/q/50944268
tags question: http://stackoverflow.com/q/50862793
tags question: http://stackoverflow.com/q/50938988
tags question: http://stackoverflow.com/q/50927787
tags question: http://stackoverflow.com/q/51005199
tags question: http://stackoverflow.com/q/50923055
tags question: http://stackoverflow.com/q/50883303
tags question: http://stackoverflow.com/q/50952907
tags question: http://stackoverflow.com/q/51002540
tags question: http://stackoverflow.com/q/50998547
tags question: http://stackoverflow.com/q/50970476
tags question: http://stackoverflow.com/q/50923707
tags question: http://stackoverflow.com/q/50966042
tags question: http://stackoverflow.com/q/50992000
tags question: http://stackoverflow.com/q/50932651
tags question: http://stackoverflow.com/q/50861802
tags question: http://stackoverflow.com/q/50881789
tags question: http://stackoverflow.com/q/50963534
tags question: http://stackoverflow.com/q/50963629
tags question: http://stackoverflow.com/q/50865899
tags question: http://stackoverflow.com/q/50951027
tags question: http://stackoverflow.com/q/50906756
tags question: http://stackoverflow.com/q/50997639
tags question: http://stackoverflow.com/q/50993568
tags question: http://stackoverflow.com/q/50914641
tags question: http://stackoverflow.com/q/50922533
tags question: http://stackoverflow.com/q/50967794
tags question: http://stackoverflow.com/q/50866657
tags question: http://stackoverflow.com/q/50960089
tags question: http://stackoverflow.com/q/50946014
tags question: http://stackoverflow.com/q/50881264
tags question: http://stackoverflow.com/q/50985906
tags question: http://stackoverflow.com/q/50875943
tags question: http://stackoverflow.com/q/51010866
tags question: http://stackoverflow.com/q/50916290
tags question: http://stackoverflow.com/q/50952675
tags question: http://stackoverflow.com/q/51010770
tags question: http://stackoverflow.com/q/50890074
tags question: http://stackoverflow.com/q/50996642
tags question: http://stackoverflow.com/q/50905222
tags question: http://stackoverflow.com/q/50863504
tags question: http://stackoverflow.com/q/50900646
tags question: http://stackoverflow.com/q/50864810
tags question: http://stackoverflow.com/q/50947267
tags question: http://stackoverflow.com/q/50945403
tags question: http://stackoverflow.com/q/50866447
tags question: http://stackoverflow.com/q/50914668
tags question: http://stackoverflow.com/q/50876484
tags question: http://stackoverflow.com/q/50975791
tags question: http://stackoverflow.com/q/50908940
tags question: http://stackoverflow.com/q/50876337
tags question: http://stackoverflow.com/q/50898218
tags question: http://stackoverflow.com/q/50855749
tags question: http://stackoverflow.com/q/50996653
tags question: http://stackoverflow.com/q/50942619
tags question: http://stackoverflow.com/q/50864471
tags question: http://stackoverflow.com/q/50947383
tags question: http://stackoverflow.com/q/50888178
tags question: http://stackoverflow.com/q/50888226
tags question: http://stackoverflow.com/q/50923383
tags question: http://stackoverflow.com/q/50934463
tags question: http://stackoverflow.com/q/50966210
tags question: http://stackoverflow.com/q/50915704
tags question: http://stackoverflow.com/q/50992063
tags question: http://stackoverflow.com/q/50983398
tags question: http://stackoverflow.com/q/50898313
tags question: http://stackoverflow.com/q/50878717
tags question: http://stackoverflow.com/q/51004029
tags question: http://stackoverflow.com/q/50926084
tags question: http://stackoverflow.com/q/50993025
tags question: http://stackoverflow.com/q/50888136
tags question: http://stackoverflow.com/q/50905520
tags question: http://stackoverflow.com/q/50936456
tags question: http://stackoverflow.com/q/50920805
tags question: http://stackoverflow.com/q/50879147
tags question: http://stackoverflow.com/q/50977683

http://stackoverflow.com/a/53999301
downvote count: 0
answers question: http://stackoverflow.com/q/50996574
type: Answer
has body: It seems like that there are some compatibility issue ! (Link) Installing Graphviz and adding it to paths works for me.
score: 1
upvote count: 1

http://stackoverflow.com/q/50877762
answer count: 2
has answer: http://stackoverflow.com/a/50878100
has body: I am trying to solve a system of linear equations. Because there are a lot of them I am using Newton-Krylov method, from scipy.minimize. For those unfamiliar, it takes a set of equations, and an initial guess. However, the definition of the set of equations, is dependent on its own parameters, but there is no way of inputting those into the Newton-Krylov solver. Below is the code that I have written import networkx as nx import scipy as sp import numpy as np import math from scipy.optimize import newton_krylov def gen_r_scores_anderson(): datasets = [ 'WTW_decades/1960wtw.txt' ] z_scores = [] for i in range(1): data = np.genfromtxt(datasets[i], dtype=[('a','|S5'),('b','|S5'),('amount','f8')], usemask=True) #import data binary_edgelist = create_edgelist_binary(data) #create edgelist H = nx.DiGraph() #create graph H.add_edges_from(binary_edgelist) #insert edgelist in graph B = nx.adjacency_matrix(H) #make H into an adjacency matrix n = len(H.nodes()) #define number of nodes n H_nodes = np.asarray(H.nodes()) #define the name of the nodes in an array rec = recip(B.todense(),n) #counts the amount of reciprocating links between i and j onrec = out_non_recip(B.todense(),n) #links going from i to j inrec = in_non_recip(B.todense(),n) #amount of links going from j to i #now we calculate the x and y values using Newtons method u = [0.5]*3*n # initial guess s = newton_krylov(f, u) # &lt;&lt; this is where the problem lies return(t) t_score = gen_r_scores_anderson() print(t_score) where the function f, the input for the newton_krylov method, is defined as follows def f(w, n, onrec, inrec, rec): F = [0]*3*n for i in range(n): F[i] = -onrec[i] F[n+i] = -inrec[i] F[(2*n)+i] = -rec[i] for j in range(n): if i == j: None else: F[i] += (w[i]*w[n+j])/(1+w[i]*w[n+j]+w[j]*w[n+i]+w[2*n+i]*w[2*n+j]) F[n+i] += (w[j]*w[n+i])/(1+w[i]*w[n+j]+w[j]*w[n+i]+w[2*n+i]*w[2*n+j]) F[2*n+i] += (w[(2*n)+i]*w[(2*n)+j])/(1+w[i]*w[n+j]+w[j]*w[n+i]+w[2*n+i]*w[2*n+j]) return(F) I have read about globals, but …
upvote count: 1
has comment: http://stackoverflow.com/comment/88757808
favorite count: 0
possible better answer: http://stackoverflow.com/a/50878100
downvote count: 0
has title: Python scipy function does not take global variables
tagged with: python
has comment: http://stackoverflow.com/comment/88760929
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50877889
accepted answer: http://stackoverflow.com/a/50877889
score: 1
tagged with: global-variables
tagged with: scipy
type: Question

http://stackoverflow.com/q/50945734
type: Question
tagged with: dataframe
score: 0
tagged with: pandas
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50945929
tagged with: python
has body: I am new in Python and Tensorflow. I have created a sample for simple classification using Pandas and an existing CSV file. But In order to normalize the columns in the CSV, I am getting the below error. Debugging IDE: Jupyter Notebook import pandas as pd patients = pd.read_csv("../npushpakaran/TENSORFLOW/Tensorflow-Bootcamp-master/02-TensorFlow-Basics/pima-indians-diabetes.csv") patients.columns Index(['Number_pregnant', 'Glucose_concentration', 'Blood_pressure', 'Triceps', 'Insulin', 'BMI', 'Pedigree', 'Age', 'Class', 'Group'], dtype='object') cols_to_norm =['Number_pregnant', 'Glucose_concentration', 'Blood_pressure', 'Triceps', 'Insulin', 'BMI', 'Pedigree', 'Age', 'Class', 'Group'] patients[cols_to_norm] = patients[cols_to_norm].apply(lambda x: (x- x.min())/(x.max()-x.min())) In the last line, I am getting the below error. --------------------------------------------------------------------------- TypeError Traceback (most recent call last) ~/anaconda3/lib/python3.6/site-packages/pandas/core/ops.py in na_op(x, y) 1008 try: -&gt; 1009 result = expressions.evaluate(op, str_rep, x, y, **eval_kwargs) 1010 except TypeError: ~/anaconda3/lib/python3.6/site-packages/pandas/core/computation/expressions.py in evaluate(op, op_str, a, b, use_numexpr, **eval_kwargs) 204 if use_numexpr: --&gt; 205 return _evaluate(op, op_str, a, b, **eval_kwargs) 206 return _evaluate_standard(op, op_str, a, b) ~/anaconda3/lib/python3.6/site-packages/pandas/core/computation/expressions.py in _evaluate_numexpr(op, op_str, a, b, truediv, reversed, **eval_kwargs) 119 if result is None: --&gt; 120 result = _evaluate_standard(op, op_str, a, b) 121 ~/anaconda3/lib/python3.6/site-packages/pandas/core/computation/expressions.py in _evaluate_standard(op, op_str, a, b, **eval_kwargs) 64 with np.errstate(all='ignore'): ---&gt; 65 return op(a, b) 66 TypeError: unsupported operand type(s) for -: 'str' and 'str' During handling of the above exception, another exception occurred: TypeError Traceback (most re…
type: AnsweredQuestion
upvote count: 1
has title: Normalization error in Pandas, Jupyter Notebook
accepted answer: http://stackoverflow.com/a/50945929
downvote count: 1
tagged with: tensorflow

http://stackoverflow.com/a/51125753
has comment: http://stackoverflow.com/comment/129082765
upvote count: 0
has body: Set proxy settings like this: import telebot **from telebot import apihelper** bot = telebot.TeleBot( tkn ) **apihelper.proxy = { 'https': 'socks5://swcbbabh:зфыыцщкв@ley.vivalaresistance.info:3306' }** @bot.message_handler(commands=['start', 'help']) ... Update gunicorn, requests, and PySocks. Restart the application.
score: -3
type: Answer
answers question: http://stackoverflow.com/q/50988477
downvote count: 3

http://stackoverflow.com/comment/88902251
type: Comment
score: 0
has text: So I have tried this and it's still very slow even when the DataFrames are only 10000 entries. I think @DSM is correct about `apply` just hiding a for loop under the hood?
type: AnswerComment
comment on: http://stackoverflow.com/a/50951825

http://stackoverflow.com/comment/88779041
has text: See also my edits plz, format of the index and an other dataframe, that worked with same code, but separate date time columns before the conversion to_datetime. thnx
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50888568

http://stackoverflow.com/q/50975798
tagged with: python
score: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88948177
possible better answer: http://stackoverflow.com/a/50976304
has comment: http://stackoverflow.com/comment/88949093
has answer: http://stackoverflow.com/a/50976304
downvote count: 1
has comment: http://stackoverflow.com/comment/88949227
type: Question
accepted answer: http://stackoverflow.com/a/50976569
has title: how remove rows in a dataframe that the order of values are not important
upvote count: 5
has comment: http://stackoverflow.com/comment/88947596
tagged with: dataframe
answer count: 2
tagged with: pandas
has body: I have a dataframe like this: source target weight 1 2 5 2 1 5 1 2 5 1 2 7 3 1 6 1 1 6 1 3 6 My goal is to remove the duplicate rows, but the order of source and target columns are not important. In fact, the order of two columns are not important and they should be removed. In this case, the expected result would be source target weight 1 2 5 1 2 7 3 1 6 1 1 6 Is there any way to this without loops?
favorite count: 0
linked to: http://stackoverflow.com/q/23667369
has comment: http://stackoverflow.com/comment/88948000
has answer: http://stackoverflow.com/a/50976569
has comment: http://stackoverflow.com/comment/88949153

http://stackoverflow.com/comment/88818590
has text: Yout solution is very fast, thank you for your update ! I'm trying to get filtration/persistence of a [Rips Complex](https://en.wikipedia.org/wiki/Vietoris%E2%80%93Rips_complex). Here is a [Paper](https://www.math.upenn.edu/~ghrist/preprints/barcodes.pdf)
comment on: http://stackoverflow.com/a/50907222
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/50995596
score: 0
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/50995512
answers question: http://stackoverflow.com/q/50995512
has body: You should be able to simply do: c:\path\to\*exoc* Using your current code would find the latest of any filename containing exoc. If you wanted more fine-grained control you could do: c:\path\to\CC-*exoc* Would only find the latest file starting with CC- containing exoc in the filename.

classification
tags question: http://stackoverflow.com/q/50856769
tags question: http://stackoverflow.com/q/50906123
tags question: http://stackoverflow.com/q/50981714
tags question: http://stackoverflow.com/q/50970073
tag name: classification
tags question: http://stackoverflow.com/q/50934706
tags question: http://stackoverflow.com/q/50978587
tags question: http://stackoverflow.com/q/50910828
tags question: http://stackoverflow.com/q/50918112
tags question: http://stackoverflow.com/q/50892688
tags question: http://stackoverflow.com/q/50937628
tags question: http://stackoverflow.com/q/50964401
type: Tag
tags question: http://stackoverflow.com/q/51004943
tags question: http://stackoverflow.com/q/50968321

http://stackoverflow.com/q/50896344
type: Question
tagged with: nltk
score: 0
has comment: http://stackoverflow.com/comment/88793324
tagged with: nltk-book
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
tagged with: nlp
has body: I was successfully able to install nltk and I have all the prerequisites installed as well. Nonetheless I have been receiving error messages like these while importing nltk. &gt;&gt;&gt; import nltk Traceback (most recent call last): File "&lt;pyshell#9&gt;", line 1, in &lt;module&gt; import nltk File "C:\Users\Saurav\AppData\Local\Programs\Python\Python36-32\lib\site- packages\nltk\__init__.py", line 128, in &lt;module&gt; from nltk.chunk import * File "C:\Users\Saurav\AppData\Local\Programs\Python\Python36-32\lib\site- packages\nltk\chunk\__init__.py", line 157, in &lt;module&gt; from nltk.chunk.api import ChunkParserI File "C:\Users\Saurav\AppData\Local\Programs\Python\Python36-32\lib\site- packages\nltk\chunk\api.py", line 13, in &lt;module&gt; from nltk.parse import ParserI File "C:\Users\Saurav\AppData\Local\Programs\Python\Python36-32\lib\site- packages\nltk\parse\__init__.py", line 79, in &lt;module&gt; from nltk.parse.transitionparser import TransitionParser File "C:\Users\Saurav\AppData\Local\Programs\Python\Python36-32\lib\site- packages\nltk\parse\transitionparser.py", line 21, in &lt;module&gt; from sklearn.datasets import load_svmlight_file File "C:\Users\Saurav\AppData\Local\Programs\Python\Python36-32\lib\site- packages\sklearn\datasets\__init__.py", line 6, in &lt;module&gt; from .base import load_breast_cancer File "C:\Users\Saurav\AppData\Local\Programs\Python\Python36-32\lib\site- packages\sklearn\datasets\base.py", line 20, in &lt;module&gt; from ..utils import Bunch File "C:\Users\Saurav\AppData\Local\Programs\Python\Python36-32\lib\site- packages\sklearn\utils\__init__.py", line 11, in &lt;module&gt; from .validation import (as_float_array, File "C:\Users\Saurav\AppData\Local\Programs\Python\Python36-32\lib\site- packages\sklearn\utils\validation.py", line 23, in &lt;module&gt; from ..externals.joblib import Memory File "C:\Users\Saurav\AppData\Local\Programs\Python\Python36-32\lib\site- packages\sklearn\externals\joblib\__init__.py", line 127…
has comment: http://stackoverflow.com/comment/88793423
has title: Receiving error messages while importing nltk
answer count: 0
has comment: http://stackoverflow.com/comment/88792763

http://stackoverflow.com/comment/88831706
type: QuestionComment
has text: I can see that atleast the `mu` value is similar to three clusters in both approaches. However these values can highly depend on the initialization value
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50915749

http://stackoverflow.com/a/64886892
upvote count: 6
answers question: http://stackoverflow.com/q/50947760
has body: You can use online formatter. I know most of them are throwing error for not having double quotes but below one seems handling it nicely! JSON Formatter
score: 6
downvote count: 0
has comment: http://stackoverflow.com/comment/117669600
type: Answer

http://stackoverflow.com/q/50913589
has comment: http://stackoverflow.com/comment/88896143
score: 3
has comment: http://stackoverflow.com/comment/88903589
tagged with: geoserver
has comment: http://stackoverflow.com/comment/88903540
tagged with: geoalchemy2
downvote count: 0
favorite count: 0
tagged with: python
has title: (psycopg2.ProgrammingError) can't adapt type 'WKBElement'
answer count: 0
upvote count: 3
type: UnansweredQuestion
has body: I am trying to send data from one database table to a separate database and table. To do this I am working with sqlalchemy and geoalchemy2. Here is a snippet of the code. s = sqlalchemy.select([source_table]) with engine.connect() as conn: rp = conn.execute(s) source_results = rp.fetchall() #inserting Data ins = target_table.insert() with target_engine.connect() as conn: target_results = conn.execute(ins, source_results) The error it returns is: ProgrammingError:(psycopg2.ProgrammingError) can't adapt type 'WKBElement'. the column type is: Geometry(srid=4326)
tagged with: sqlalchemy
type: Question

http://stackoverflow.com/comment/88790836
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50895256
has text: as a workaround - in the method_end method why not first delete first (on memory leakage concerns) and assign to None (to avoid missing variable, if it is really source of error)
score: 0

http://stackoverflow.com/comment/88798803
type: Comment
score: 0
has text: I try calling `test2` key-ing syntax in the command promt: `python3 File2.Myclass1.test2` but it returns `[Errno 2] No such file or directory`
comment on: http://stackoverflow.com/q/50898854
type: QuestionComment

http://stackoverflow.com/q/50869957
type: UnansweredQuestion
tagged with: python
has title: How to mesh grid before plottiong any variable in a netCDF file using python
has comment: http://stackoverflow.com/comment/88752376
tagged with: netcdf4
answer count: 0
tagged with: netcdf
type: Question
has comment: http://stackoverflow.com/comment/88741802
score: 0
linked to: http://stackoverflow.com/q/2460627
has body: So I am plotting the column concentration plot and before that i have to make a mesh grid but if I directly write: lons,lats= np.meshgrid(lon,lat) x,y = map(lons,lats) Then it produces the following error: --------------------------------------------------------------------------- MemoryError Traceback (most recent call last) &lt;ipython-input-43-cdc15fcf5910&gt; in &lt;module&gt;() ----&gt; 1 lons,lats= np.meshgrid(lon,lat) 2 3 x,y = map(lons,lats) C:\ProgramData\Anaconda3\lib\site-packages\numpy\lib\function_base.py in meshgrid(*xi, **kwargs) 4696 4697 if copy_: -&gt; 4698 output = [x.copy() for x in output] 4699 4700 return output C:\ProgramData\Anaconda3\lib\site-packages\numpy\lib\function_base.py in &lt;listcomp&gt;(.0) 4696 4697 if copy_: -&gt; 4698 output = [x.copy() for x in output] 4699 4700 return output C:\ProgramData\Anaconda3\lib\site-packages\numpy\ma\core.py in wrapped_method(self, *args, **params) 2573 """ 2574 def wrapped_method(self, *args, **params): -&gt; 2575 result = getattr(self._data, funcname)(*args, **params) 2576 result = result.view(type(self)) 2577 result._update_from(self) MemoryError: But in all tutorial, I see they didn't get this error. Help!!!
tagged with: latitude-longitude
tagged with: python-3.x

http://stackoverflow.com/comment/88989820
comment on: http://stackoverflow.com/a/50994788
has text: Thanks mate, import is working now. I'm just following the documentation example and for the line `mob = mobidriver.Firefox(browsermob_binary=browsermob_path)` I get an error `The Browsermob-Proxy server process failed to start` which asks me to check the the file `server.log` for more detailed info. I checked the file and it says `'java' is not recognized as an internal or external command,operable program or batch file`. Do you know a way around this? Thanks
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/88953637
has text: Yes it works outside of Jenkins fine. It also works fine when I RDP into the Jenkins server and run pytest in a PowerShell console.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50977867
score: 0

http://stackoverflow.com/comment/88940479
score: 0
comment on: http://stackoverflow.com/q/50958972
type: Comment
type: QuestionComment
has text: Another big issue is you're not programming `tkinter` correctly. Something like your `while True:` loop is **not** how they work. In a nutshell, you need always call `.mainloop()` somewhere to get your app running. From that point on, everything must occur inside that loop. Basically what you want to do is animation, so that's what you need to understand how to do (there are many questions related to that here on stackoverflow). This is often accomplished using a callback function with the universal widget method [`after()`](http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/universal.html).

http://stackoverflow.com/comment/88960648
comment on: http://stackoverflow.com/q/50982304
has text: When you call `to_queryset()` you get back a regular Django queryset. It is no longer a `Response` object and so you cannot access any aggregations that were returned by Elasticsearch. If you want to use the aggregations then you need to work with the result object without converting to a queryset.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88794129
type: QuestionComment
has text: @RolandSmith, when I do python --version is 2.7.9. But when I do a dpkg -l python3, there is a python 3.4 installed
comment on: http://stackoverflow.com/q/50897094
score: 0
type: Comment

http://stackoverflow.com/a/50936066
has body: Polytools module is in sympy and sympy is a dependency of symfit. It seems symfit doesn't properly declared dependencies. To install its dependencies clone the repository: git clone https://github.com/tBuLi/symfit.git and run pip install -U -r requirements.txt Report the bug at the symfit issue tracker.
downvote count: 0
has comment: http://stackoverflow.com/comment/88885694
score: 1
upvote count: 1
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/88874841
has comment: http://stackoverflow.com/comment/88873011
accepted answer of: http://stackoverflow.com/q/50934300
answers question: http://stackoverflow.com/q/50934300
has comment: http://stackoverflow.com/comment/88873214

http://stackoverflow.com/comment/88730983
has text: @rth Just for clarity, the OP has explicitly mentioned **python-3.6**, that means your code will throw a `NameError: name 'xrange' is not defined` while the python-2.x will have problems with memory upon allocating all the `range()`-instance(s) memory-blocks **`:o)`** >>> https://tio.run/##K6gsycjPM/7/Py2/SCFTITNPoaIoMS89VUPB0EBB04pLAQgy//8HAA
type: AnswerComment
comment on: http://stackoverflow.com/a/50862063
score: 0
type: Comment

http://stackoverflow.com/a/50914218
answers question: http://stackoverflow.com/q/50911335
score: 0
has body: You can set a property under Post: @property def unfiltered_posts(): return SESSION.query(cls).Join(User).filter(User.archived==False).all()
type: Answer

http://stackoverflow.com/q/50960830
has body: I have installed pytorch and torchvision using: conda install pytorch-cpu -c pytorch pip install torchvision when I try to run the following in spyder: import torch import torchvision import torchvision.transforms as transforms I get: Traceback (most recent call last): File "&lt;ipython-input-2-0bf25e9dac67&gt;", line 2, in &lt;module&gt; import torchvision File "C:\Users\lkoefoed\AppData\Local\Continuum\anaconda3\lib\site-package\torchvision\__init__.py", line 2, in &lt;module&gt; from torchvision import datasets File "C:\Users\lkoefoed\AppData\Local\Continuum\anaconda3\lib\site-packages\torchvision\datasets\__init__.py", line 1, in &lt;module&gt; from .lsun import LSUN, LSUNClass File "C:\Users\lkoefoed\AppData\Local\Continuum\anaconda3\lib\site-packages\torchvision\datasets\lsun.py", line 2, in &lt;module&gt; from PIL import Image File "C:\Users\lkoefoed\AppData\Local\Continuum\anaconda3\lib\site-packages\PIL\Image.py", line 56, in &lt;module&gt; from . import _imaging as core ImportError: DLL load failed: The specified module could not be found.
tagged with: pytorch
score: 6
has comment: http://stackoverflow.com/comment/88918978
tagged with: pip
type: Question
has comment: http://stackoverflow.com/comment/88954261
has answer: http://stackoverflow.com/a/50979533
answer count: 2
has comment: http://stackoverflow.com/comment/88954073
downvote count: 0
favorite count: 0
has title: Cannot load torchvision despite it being installed
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/63184900
tagged with: python
upvote count: 6
has comment: http://stackoverflow.com/comment/88954876

http://stackoverflow.com/q/50935168
score: -2
has body: In my Visual Code Studio running python3.6 - my code is saved as "Langemead12Test.py" w/ lines as: !C:\Users\Bones\Anaconda3\python.exe [1]def readFastq(SRR835775_1.first1000.fastq) Red Error underline def [pylint] E0001:invalid syntax (, line 3). In Anaconda command prompt running python3.6: File "Langmead12Test.py", line 3 def readFastq(SRR835775_1.first1000.fastq) ^ SyntaxError: invalid syntax Question(s): I'm a total newb here but I can't seem to understand why VCS throws an error under def and my anaconda command line prompt throws error at the . within the fastq filename. Are these independent errors or different representations of the same error? All thoughts and hints are welcome. Background: I am attempting to execute exercise in ADS1: Practical: Working with sequencing reads. Ben Langmead's Youtube class on reading fastq files (filename = SRR835775_1.first1000.fastq).
tagged with: visual-studio
has comment: http://stackoverflow.com/comment/88869483
has comment: http://stackoverflow.com/comment/88868940
downvote count: 2
has answer: http://stackoverflow.com/a/50935587
answer count: 1
tagged with: fastq
has title: Python Def Syntax Error with . in file name
type: UnansweredQuestion
upvote count: 0
favorite count: 0
type: Question
tagged with: python

http://stackoverflow.com/comment/88925178
score: 0
has text: How can I validate a IBAN-Number without knowledge of the checksum-algorithmn with AI? Like I said before, I am new to machine learning and AI-Stuff and I want to know how to solve this with python and sklearn.
comment on: http://stackoverflow.com/q/50963187
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88998408
type: Comment
score: 0
type: AnswerComment
has text: What are the values for `right_side.width` and `right_side.height`?
comment on: http://stackoverflow.com/a/50995617

http://stackoverflow.com/comment/88888842
type: AnswerComment
has text: @Ben.T Thanks - How does this work though? Is it saying ffill everything that you can, and then anything leftover fill as 0 and then convert to integer? So was it failing on the conversion to integer rather than the the ffil?
type: Comment
score: 0
comment on: http://stackoverflow.com/a/50929997

http://stackoverflow.com/comment/88933511
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50967803
score: 0
has text: @jpp Yes it is the final one

http://stackoverflow.com/a/50989469
type: AcceptedAnswer
upvote count: 13
has comment: http://stackoverflow.com/comment/88974543
answers question: http://stackoverflow.com/q/50989404
type: Answer
accepted answer of: http://stackoverflow.com/q/50989404
score: 13
downvote count: 0
has comment: http://stackoverflow.com/comment/88974307
has body: Assuming you want to call func a single time: def func(arg1="foo", arg_a= "bar", first_arg=1): print(arg1, arg_a, first_arg) arguments_dictionary = { 'arg1': "foo", 'arg_a': "bar", 'first_arg':42 } func(**arguments_dictionary)

http://stackoverflow.com/a/50861139
accepted answer of: http://stackoverflow.com/q/50860939
has body: You can use OAuth2WebServerFlow: from oauth2client.client import OAuth2WebServerFlow flow_params = { 'access_type': 'offline', 'prompt': 'consent' } flow_scopes = [ "https://www.googleapis.com/auth/calendar.edit", "https://www.googleapis.com/auth/calendar", ] flow = OAuth2WebServerFlow( client_id=client_id, client_secret=client_secret, scope=flow_scopes, redirect_uri='http://www.redirect_uri.com', **flow_params )
score: 1
has comment: http://stackoverflow.com/comment/88759710
answers question: http://stackoverflow.com/q/50860939
upvote count: 1
has comment: http://stackoverflow.com/comment/88748311
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/comment/88987181
type: Comment
type: QuestionComment
has text: @abarnert if you want to put both comments in an answer, I'll mark it. Or, should I just delete the question?
comment on: http://stackoverflow.com/q/50995767
score: 0

http://stackoverflow.com/q/50955422
score: 0
has answer: http://stackoverflow.com/a/50961667
type: AnsweredQuestion
tagged with: async-await
accepted answer: http://stackoverflow.com/a/50961667
has body: I have a handler with the following code: class HelloHandler(RequestHandler): routing_pattern = "/hello" async def get(self): url = 'some_url_here' request = httpclient.HTTPRequest(url=url, streaming_callback=self.on_chunk) result = await downloader.fetch(request) print(result) self.write("done") @gen.coroutine def on_chunk(self, chunk): self.write(chunk) yield self.flush() this code calls an async def function defined like so: async def fetch(request): future = Future() await _qin.put(request) return future I was hoping that inside my handler, things will stop on the await downloader.fetch(request) line until I set a value on the returned future. right now that would never happen so things should have stoped there. However it seems that the future is not actually awaited. The print(result) line shows a "" and things just speed on past that line. What am I doing wrong ? How can i make the function stop there and actually wait for the future to complete ? A side question ... is what I am doing in the on_chunk method correct ? I would like to await for the flush to happen in there but streaming_callback does not take an async function.
tagged with: tornado
type: Question
answer count: 1
has title: Tornado await for Future object to resolve
tagged with: python

http://stackoverflow.com/comment/89048156
has text: That might have to do with how your Python is compiled, but I am not sure.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51000924
type: Comment

http://stackoverflow.com/a/50869551
answers question: http://stackoverflow.com/q/50860397
has body: Try doing it this way. @bot.command(pass_context=True) async def send(ctx): area=ctx.message.channel await bot.send_file(area, r"c:\location\of\the_file_to\send.png",filename="Hello",content="Message test") You can refer to the discord documentation for it here link
downvote count: 0
upvote count: 2
type: Answer
score: 2

http://stackoverflow.com/comment/88842256
comment on: http://stackoverflow.com/a/50921289
score: 0
type: AnswerComment
has text: ususally `isinstance(s, str)` is better than `==` type check
type: Comment

http://stackoverflow.com/q/50945391
has comment: http://stackoverflow.com/comment/88889346
type: AnsweredQuestion
has body: My Objective is to add multiple rows of Data in the Table but I get an error everytime , I tried multiple variations of the code and Sorry for not asking the question earlier , I didn't know how , I don't use much of Stack Overflow . The Updated Code is in the end . Error: Traceback (most recent call last): File "G:/Python/sqlconnector4.py", line 25, in &lt;module&gt; entry_table(number) File "G:/Python/sqlconnector4.py", line 17, in entry_table c.execute("INSERT INTO T1 (NAME , ADDRESS ) VALUES (thelist.split("'',''"))") File "C:\Users\tushar\AppData\Local\Programs\Python\Python36-32\lib\site-packages\mysql\connector\cursor.py", line 559, in execute self._handle_result(self._connection.cmd_query(stmt)) File "C:\Users\tushar\AppData\Local\Programs\Python\Python36-32\lib\site-packages\mysql\connector\connection.py", line 494, in cmd_query result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query)) File "C:\Users\tushar\AppData\Local\Programs\Python\Python36-32\lib\site-packages\mysql\connector\connection.py", line 396, in _handle_result raise errors.get_exception(packet) mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1 Error import mysql.connector my=mysql.connector.connect(host='localhost' , user='root' , password='rootroot' , database='tushar') c=my.cursor() def create_table(): c.execute("CREATE TABLE IF NOT EXISTS T1 (ID INT AUTO_INCREMENT PRIMARY KEY, NAME VARCHAR(30) NOT NULL , ADDRESS VARCHAR(50) NOT NULL)") my.commit() def entry_table(n): thelist = [] for x in range(0,n) : user_name = input("ENTER NAME NUMBER {}: ".format(x+1)) user_state = input("ENTER STATE {} LIVES IN : ".format(user_name)) thelist.append(user_name) thelist.append(user_state) c.execute("INSERT INTO T1 (NAME , ADDRESS ) VALUES (thelist.split("'',''"))") my.commit() for x in range(0,n) : c.execute("SELECT * FROM T1") number = int(inp…
score: -2
has comment: http://stackoverflow.com/comment/88889430
has comment: http://stackoverflow.com/comment/88888579
type: Question
accepted answer: http://stackoverflow.com/a/50946365
has comment: http://stackoverflow.com/comment/88888392
has title: mySQL MULTIPLE ROWS DYNAMIC INSERT PYTHON
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/88888626
favorite count: 0
has answer: http://stackoverflow.com/a/50946365
has comment: http://stackoverflow.com/comment/88889115
has comment: http://stackoverflow.com/comment/88888563
downvote count: 3
tagged with: python
tagged with: python-idle
has comment: http://stackoverflow.com/comment/88888432
has comment: http://stackoverflow.com/comment/88888460
tagged with: mysql

http://stackoverflow.com/q/50877270
has body: I'm trying to use the pycryptodome implementation of Shamir's Secret Sharing. When splitting the shares the output is a list object with tuples of this form: &lt;class 'list'&gt;: [(1, b'\x84\x16H\x92\xaaJ\xf7\x84_\xf9\x02\x03\x86\xff\xb7Z'), (2, b'\x86p\xbe5\xbfP\xe4\x00m\x16\xd3\t\xb3\xc8\xfa\x1f'), (3, b'xR\xecWLY\x15||\xb3\x9c\x0f\xa0\xda&gt;\xa1'), (4, b'\x82\xbdS{\x95d\xc3\x08\x08\xc9q\x1d\xd9\xa6`\x95'), (5, b'|\x9f\x01\x19fm2t\x19l&gt;\x1b\xca\xb4\xa4+')] After hexlify in a for loop the object is much more readable : for idx, share in shares: print ("index #%d: %s" % (idx, hexlify(share))) index #1: b'84164892aa4af7845ff9020386ffb75a' index #2: b'8670be35bf50e4006d16d309b3c8fa1f' index #3: b'7852ec574c59157c7cb39c0fa0da3ea1' index #4: b'82bd537b9564c30808c9711dd9a66095' I have this model: class MyModel(models.Model): user_id = models.ForeignKey(User, on_delete=models.CASCADE, null=True) some_other_id = models.ForeignKey(OtherModel, on_delete=models.CASCADE, null=True) encrypted_share = models.CharField(max_length=200, blank=True) I want somehow to filter MyModel for a specific some_other_id and then for each user_id entry save a single share from the list object enrypted with the user's public_key taken from the user_model. Here's how I create the shares in my views.py: number_of_users = MyModel.objects.filter(some_other_id=self.object.pk).count() minimum_shares = (number_of_users*7)//10 shares = Shamir.split(minimum_shares, number_of_users, key) EDIT: I'm gonna add some more information to make what I want to achieve more clear. Basically MyModel is a list of users participating in polls. my models.py: class Poll(models.Model): question_text = models.CharField(max_length=200) public_key = models.CharField(max_length=30, blank=True) owner = models.ForeignKey(User, on_delete=models.CASCADE, editable=False) class EligibleVoters(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) poll = models.ForeignKey(Poll, on_delete=models.CAS…
tagged with: django-models
type: Question
score: 0
has answer: http://stackoverflow.com/a/50878993
answer count: 1
has comment: http://stackoverflow.com/comment/88757106
tagged with: foreign-keys
tagged with: python
has comment: http://stackoverflow.com/comment/88758266
type: UnansweredQuestion
has title: Django: Loop over list of objects and save in model with ForeignKey
tagged with: django
has comment: http://stackoverflow.com/comment/88757827
has comment: http://stackoverflow.com/comment/88757022
has comment: http://stackoverflow.com/comment/88757623

http://stackoverflow.com/comment/88817106
comment on: http://stackoverflow.com/a/50908449
type: AnswerComment
has text: @Javier Buzzi Haha, fair enough, I hadn't seen the python3-x tag ;) , +1
type: Comment
score: 1

http://stackoverflow.com/q/50953477
tagged with: pyqt
has body: I have this code: self.entriesx = self.generate_stringvars() # Fill in the entry fields if a template is selected. def autofill(self): # Generate a dictionary of all the saved templates. test_dictionary = self.build_test_dictionary() # Retrive the selected qual name from the form. self.coded_entry = self.comboBox.currentText() entries = test_dictionary[self.coded_entry] # Set each entry field in self.entriesx to the corresponding value # from the template. i_count = 0 for i in self.entriesx: i.set(entries[i_count]) i_count += 1 # Reload the entry fields with their new values. self.add_entry_fields() The autofill(self) function automatically fills in the respective entries into entry fields based on a chosen item from a combo box. The autofill function also relies on this function: # Generate a list of string variables to store the entries. def generate_stringvars(self): temp_entriesx = [] count = 0 while count &lt; 21: temp_entriesx.append("") count += 1 return temp_entriesx When I compile my code I get an error AttributeError: 'str' object has no attribute 'set' for i.set(entries[i_count]) in my autofill function. How do I fix it? Edit: This is a follow up question to this post.
answer count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/50953712
accepted answer: http://stackoverflow.com/a/50953712
favorite count: 0
has comment: http://stackoverflow.com/comment/88908645
tagged with: python
duplicate of: http://stackoverflow.com/q/50951872
type: AnsweredQuestion
upvote count: 0
score: -1
type: Question
linked to: http://stackoverflow.com/q/50951872
has title: AttributeError: 'str' object has no attribute 'set' error in python pyQt
has comment: http://stackoverflow.com/comment/88908585

http://stackoverflow.com/comment/88864433
type: AnswerComment
comment on: http://stackoverflow.com/a/50931843
type: Comment
has text: Can you post your PYTHONPATH? It should contain the paths to those libraries only, not the libraries themselves (just wanting to make sure)
score: 0

http://stackoverflow.com/a/59166195
answers question: http://stackoverflow.com/q/50925390
has body: You can calculate area of circle without defining any function. Try this: pi = 3.142 r = float(input("enter your radius of circle: ")) Area = pi * r * r print("Area of the circle is: ", area)
type: Answer
score: 0

http://stackoverflow.com/q/50877370
answer count: 2
has comment: http://stackoverflow.com/comment/88756985
has comment: http://stackoverflow.com/comment/88756712
has answer: http://stackoverflow.com/a/50878118
score: 0
has answer: http://stackoverflow.com/a/50878319
tagged with: python
tagged with: module
tagged with: python-3.x
linked to: http://stackoverflow.com/q/41972261
tagged with: pycharm
type: UnansweredQuestion
has title: PyCharm does not run – Project Interpreter problems
type: Question
has body: First of all, I want to note that I've read a lot of links related to my problem. I have some problems with running the code when I want to import a module. Here is an example of the code: import numpy as np Then PyCharm gives me an exception: Traceback (most recent call last): File "/Users/Alexander 1 2/PycharmProjects/Coursera/Week1/Vectors/Vecors.py", line 1, in import numpy as np ModuleNotFoundError: No module named 'numpy' Process finished with exit code 1 I have read this and did all what was written. However, it hasn't been working. I've reloaded the PyCharm – no result. Help me, please! I'm using MacOS 10.13.5, PyCharm 2018.1.4 CE.
tagged with: numpy

http://stackoverflow.com/a/50937716
type: Answer
has comment: http://stackoverflow.com/comment/88875068
score: 1
upvote count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/88875036
has body: You need to take into account the input layer and the output layer as well. It looks like you are inputting 5-dimensional features and outputting 3-dimensional outputs. Your network has 2 hidden layers of size 2 and 3. So the coefs_ should have shapes (5,2),(2,3),(3,3) so that your inputs are changing from 5-dim to 2-dim, then from 2-dim to 3-dim then from 3-dim to 3-dim for the output. Remember that there is a weight attached to each connection from one layer to the next. So if you have 5 neurons (input layer) connected to 2 neurons (first hidden layer) then you need 5*2=10 weights to describe the 10 connections between these two layers. That is exactly what a shape (5,2) array has.
answers question: http://stackoverflow.com/q/50937628

code-injection
tags question: http://stackoverflow.com/q/50985856
tag name: code-injection
type: Tag

http://stackoverflow.com/a/50901063
answers question: http://stackoverflow.com/q/50901034
score: 1
has comment: http://stackoverflow.com/comment/88816868
upvote count: 1
has comment: http://stackoverflow.com/comment/88836668
downvote count: 0
has comment: http://stackoverflow.com/comment/88836922
has body: It is still a string. Test this by type(linestr). You cannot add an integer to a string. What you need to do is extract each value from liststr. This can be done easily using strip() and running through this list to get each value, next you need to pass it to int() to turn each value into an integer, append it to your list with integers, then you can use it as expected: new_liststr = [] for i in liststr.split(): new_liststr.append(int(i)) print(new_linestr[0]+1) Or as a single liner: new_liststr = [int(i) for i in liststr.split()] print(new_linestr[0]+1)
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/50901034

http://stackoverflow.com/q/50983026
favorite count: 0
has title: How to read messages after the last consumed message in case of consumer shutdown in Kafka?
type: UnansweredQuestion
tagged with: python
score: 2
linked to: http://stackoverflow.com/q/33676266
upvote count: 2
type: Question
tagged with: apache-kafka
has body: I have a way of performing this task in shell: How to make kafka consumer to read from last consumed offset but not from beginning However, I am willing to do this in Python, using kafka-python I could not find any api for this case. http://kafka-python.readthedocs.io/en/latest/apidoc/KafkaConsumer.html
tagged with: kafka-consumer-api
has answer: http://stackoverflow.com/a/50984498
tagged with: kafka-python
downvote count: 0
answer count: 1

http://stackoverflow.com/q/51000457
score: 1
tagged with: django
downvote count: 1
type: Question
linked to: http://stackoverflow.com/q/50999577
tagged with: html-table
tagged with: boolean
has comment: http://stackoverflow.com/comment/89001739
duplicate of: http://stackoverflow.com/q/50999577
tagged with: jquery
has comment: http://stackoverflow.com/comment/88997094
favorite count: 0
has title: Change boolean value with form submit button JQuery + Django
has comment: http://stackoverflow.com/comment/89004836
type: UnansweredQuestion
tagged with: python
has body: So this is my template where I have a table with products. Each product has a default "in_cart" value of False. So each row has a submit button "add to cart". I would like to change on click the boolean value to true so it appears in /cart. this is the table: {% load staticfiles %} List of car parts available: Name Price {% for product in products_list %} {{ product.name }} ${{ product.price }} {% if not product.in_cart %} {% csrf_token %} {% else %} {{ print }} {% endif %} {% endfor %} I created a file in myapp/static/submit.js $('#buttonId').click(function() { $.ajax({ url: 'cart/', method: 'POST', data: { name: product.in_cart, click: true } success: function (data) { } }); }); Don't really know how to go from there.
has comment: http://stackoverflow.com/comment/88996656
answer count: 0
upvote count: 2

http://stackoverflow.com/q/50915424
tagged with: string
tagged with: pandas
has title: String operations on only certain column names in pandas dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/88830975
has answer: http://stackoverflow.com/a/50915606
type: UnansweredQuestion
has body: I have column names in a dataframe ID c1 c2 c3 c4 c5 c6 c7 c8 c9 c10 c11 c12 ... cN but I want it to look like ID c01 c02 c03 c04 c05 c06 c07 c08 c09 c10 c11 c12 ... cN How can I only change select column names without changing any others?
type: Question
tagged with: dataframe
score: 0
answer count: 1

http://stackoverflow.com/a/55063546
score: 0
answers question: http://stackoverflow.com/q/50948180
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/102563678
downvote count: 1
has body: from gremlin_python.process.anonymous_traversal import traversal from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection from gremlin_python.structure.graph import Graph graph = Graph() g = graph.traversal().withRemote(DriverRemoteConnection('ws://localhost:8182/gremlin','g', username = "root",password="root_password")) Works for me

http://stackoverflow.com/comment/88810947
score: 0
comment on: http://stackoverflow.com/a/50905469
type: Comment
has text: Traceback (most recent call last): File "\\oat.int\home$\acs\student\2015\15SrokaTy\Documents\Python Coding\IOT adventure - no one can survive..py", line 232, in <module> backstory() File "\\oat.int\home$\acs\student\2015\15SrokaTy\Documents\Python Coding\IOT adventure - no one can survive..py", line 23, in backstory time.sleep(0) AttributeError: 'builtin_function_or_method' object has no attribute 'sleep'
type: AnswerComment

http://stackoverflow.com/q/50952618
has comment: http://stackoverflow.com/comment/88931860
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88908428
type: Question
tagged with: google-admin-sdk
has title: Creating new User Google admin sdk python
tagged with: google-directory-api
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/50952996
has comment: http://stackoverflow.com/comment/89564577
has answer: http://stackoverflow.com/a/64170449
has body: I'm getting an error that google doesn't recognize the user names in the json. I cannot find a way to include the http header application/json. The return URL gives me another error code but I pass login authentication. My code: from __future__ import print_function from apiclient.discovery import build from httplib2 import Http from oauth2client import file, client, tools import requests import json import pprint # Setup the Admin SDK Directory API SCOPES = 'https://www.googleapis.com/auth/admin.directory.user' #Global scope for access to all user and user alias operations. store = file.Storage('credentials.json') creds = store.get() if not creds or creds.invalid: flow = client.flow_from_clientsecrets('client_secret.json', SCOPES) creds = tools.run_flow(flow, store) service = build('admin', 'directory_v1', http=creds.authorize(Http())) # Call the Admin SDK Directory API userInfo = { "name" : { "givenName" : "Donald", "familyName" : "Dump", }, "kind" : "user", "primaryEmail" : "testUser@test.com", "isAdmin": False, "isDelegatedAdmin": False, "agreedToTerms": True, "password": "testpass1234", "changePasswordAtNextLogin": True } response = service.users().insert(body=json.dumps(userInfo)).execute()

http://stackoverflow.com/q/50864602
answer count: 1
type: UnansweredQuestion
tagged with: django
tagged with: python
linked to: http://stackoverflow.com/q/49709479
tagged with: mysql
has answer: http://stackoverflow.com/a/50865130
type: Question
has body: This is the first time I am using mySQL and django, and I have some problems with getting my content from the server and show it on my webpage. Here is my codes: This is the index.html {% extends 'test/layout.html' %} {% block content %} {{title}} Webpages {% for homes in homes %} {{homes.title}} {% endfor %} {% endblock %} The views.py from django.shortcuts import render from django.http import HttpResponse from .models import Home def index(request): homes = Home.objects.all()[:10] context = { 'title': 'All Home', 'homes': homes } return render(request, 'test/index.html', context) def details(request, id): home = Home.objects.get(id=id) context = { 'Home': home } return render(request, 'test/details.html', context) urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'', views.index, name='index'), url(r'details/(?P<id>\d+)/', views.details, name='details') ] models.py from django.db import models from datetime import datetime class Home(models.Model): title = models.CharField(max_length=100) body = models.TextField() created_at = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.title class Meta: verbose_name_plural = "Home" details.html {% extends 'test/layout.html' %} {% block content %} {{home.title}} {{home.body}} {{created_at}} Go Back {% endblock %} The problem is that when i click on the links on my webpage, the details.html file with the text form the server don't show. instead the homepage shows up(index.html), but now under a different url.(Normal url on homepage: localhost:8000, the new url: localhost:8000/test/details.html) I think the problems is in the urls.py file, but i am not sure. Hopes anyone can help. edit: my file folder testdjango | |--testdjango(all the normal project files are in here) |--test | |--__pycache__ | |--migrations | |--templates | | |--test | | |--detalils.html | | |--index.html | | |--layout.html | | | |--__init__.py | |--admin.py | |--apps.py | |--models.py | |-…
has title: Problems with getting content from mySQL server to webpage via django
score: 0

http://stackoverflow.com/a/50913008
has comment: http://stackoverflow.com/comment/88826367
has body: Let us first implement the median-of-three for three numbers, so an independent function. We can do that by sorting the list of three elements, and then return the second element, like: def median_of_three(a, b, c): return sorted([a, b, c])[1] Now for a range low .. high (with low included, and high excluded), we should determine what the elements are for which we should construct the median of three: the first element: L[low], the last element L[high-1], and the middle element (in case there are two such, take the first) L[(low+high-1)//2]. So now we only need to patch the partitioning function to: def Partition(L, low, high, ascending = True): print('Quicksort, Parameter L:') print(L) result = 0 pivot = median_of_three(L[low], L[(low+high-1)//2], L[high-1]) i = low + 1 for j in range(low + 1, high, 1): result += 1 if (ascending and L[j] &lt; pivot) or (not ascending and L[j] &gt; pivot): L[i], L[j] = L[j], L[i] i += 1 L[low], L[i-1] = L[i-1], L[low] return i - 1, result EDIT: determining the median of three elements. The median of three elements is the element that is in the middle of the two other values. So in case a &lt;= b &lt;= c, then b is the median. So we need to determine in what order the elements are, such that we can determine the element in the middle. Like: def median_of_three(a, b, c): if a &lt;= b and b &lt;= c: return b if c &lt;= b and b &lt;= a: return b if a &lt;= c and c &lt;= b: return c if b &lt;= c and c &lt;= a: return c return a So now we have defined the median of three with four if cases. EDIT2: There is still a problem with this. After you perform a pivot, you swap the element L[i-1] with L[low] in your original code (the location of the pivot). But this of course does not work anymore: since the pivot now can be located at any of the three dimensions. Therfore we need to make the median_of_three(..) smarter: not only should it return the pivot element, but the location of that pivot as well: def median_of_three(L, low, high): mid = (l…
has comment: http://stackoverflow.com/comment/88830734
has comment: http://stackoverflow.com/comment/88828081
has comment: http://stackoverflow.com/comment/88927178
has comment: http://stackoverflow.com/comment/88831239
has comment: http://stackoverflow.com/comment/88831813
has comment: http://stackoverflow.com/comment/88927216
score: 4
accepted answer of: http://stackoverflow.com/q/50912873
has comment: http://stackoverflow.com/comment/88831269
has comment: http://stackoverflow.com/comment/88830600
upvote count: 4
has comment: http://stackoverflow.com/comment/88826404
has comment: http://stackoverflow.com/comment/88925742
answers question: http://stackoverflow.com/q/50912873
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88926622
has comment: http://stackoverflow.com/comment/88827578
has comment: http://stackoverflow.com/comment/88827697
has comment: http://stackoverflow.com/comment/88830980
has comment: http://stackoverflow.com/comment/88828109
has comment: http://stackoverflow.com/comment/88926955
has comment: http://stackoverflow.com/comment/88831139
type: Answer
has comment: http://stackoverflow.com/comment/88926777
has comment: http://stackoverflow.com/comment/88927567
has comment: http://stackoverflow.com/comment/88926602
has comment: http://stackoverflow.com/comment/88828041

http://stackoverflow.com/comment/88828678
score: 2
comment on: http://stackoverflow.com/q/50914204
type: Comment
has text: @RafaelC: I feel like you should write an answer to that effect.
type: QuestionComment

http://stackoverflow.com/q/51001046
upvote count: 1
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51001083
downvote count: 0
favorite count: 0
tagged with: exception
type: UnansweredQuestion
has title: Sleep in case of error, python
tagged with: python
has answer: http://stackoverflow.com/a/51001158
has body: So I have a situation where I am to use internet connection for 12 hours straight and make calls to an api. But Light keeps going off after every 10 minutes. Is is possible to write a try, except function that will cause a delay of 10 minutes in case an error of timed out is generated. It is hopeful that the electricity will come back in 10 minutes.| This is what I am currently using: try: a=translator.translate(str(x1),dest='hi') b=translator.translate(str(x2),dest='hi') except: sleep(60*10)
score: 1
tagged with: error-handling

http://stackoverflow.com/comment/91614429
comment on: http://stackoverflow.com/a/50984159
type: Comment
has text: Isnt it that this line of code is pointless: "c_loss = classifier.train_on_batch(image_batch, label_batch)" I should have there the generated_images instead, no? Or to train initially with the real data and just produce the error from the generated_images.
score: 0
type: AnswerComment

http://stackoverflow.com/a/50926238
answers question: http://stackoverflow.com/q/50926134
downvote count: 0
has body: Use the following:- import re http_user_agent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/603.2.4 (KHTML, like Gecko) Version/10.1.1 Safari/603.2.4" if 'Safari' in http_user_agent and 'Mobile' not in http_user_agent: version = re.compile(r'\b({0}).*?'.format('Version[/\.\d]*\s'), flags=re.IGNORECASE).search(http_user_agent) print(version.group(0)) Here we have changed regex Version to Version[/\.\d]*\s to include number '.' and '/' till the space character.
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/q/50969484
downvote count: 0
has answer: http://stackoverflow.com/a/50969529
favorite count: 0
tagged with: django
tagged with: python
type: AnsweredQuestion
score: 3
upvote count: 3
tagged with: mysql
has body: I'm using Django-models for saving data to database but I have a problem, a new record has an incorrect id (I need to save some records in a for loop) My error: IntegrityError: (1062, u"Duplicate entry '46' for key 'PRIMARY'") The view:
type: Question
tagged with: django-models
accepted answer: http://stackoverflow.com/a/50969529
has title: error saving data to database
answer count: 1

http://stackoverflow.com/comment/88773832
type: Comment
type: QuestionComment
score: 0
has text: neither work...
comment on: http://stackoverflow.com/q/50876440

http://stackoverflow.com/a/50966021
score: 2
answers question: http://stackoverflow.com/q/50965671
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: nltk.word_tokenize takes a string as an input, you have passed it a list. If I understand correctly, I think you want this: ... for doc in book.get_items(): doc_content = str(doc.content) for w in nltk.word_tokenize(doc_content): german_corpus.append(w.lower())
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50965671

http://stackoverflow.com/a/50892937
has body: Create a model in models.py: from __init__.py import db class ContactModel(db.Model): __tablename__ = 'contact' id = db.Column(db.Integer, primary_key = True) name = db.Column(db.String(120)) email = db.Column(db.String(120)) def save_to_db(self): db.session.add(self) db.session.commit() Then in init.py: from flask import Flask from config import Config from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate app = Flask(__name__) app.config.from_object(Config) db = SQLAlchemy(app) migrate = Migrate(app, db) #create all db tables @app.before_first_request def create_tables(): from models import ContactModel db.create_all() from app import routes, models
score: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88787272
type: Answer
answers question: http://stackoverflow.com/q/50892823
upvote count: 3
accepted answer of: http://stackoverflow.com/q/50892823

http://stackoverflow.com/a/64491706
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50878513
upvote count: 2
has body: Terminate your server if it still running . Then navigate to your folder which has catalogs.db and rename it to backups.db or something else ..you can also delete it. Run your server and the create all method will automatically create catalogs.db for you. I think the error occurred because you had made some changes after the creation. I was experiencing the same issue so hopefully, it will help you.
type: Answer

http://stackoverflow.com/comment/88940708
comment on: http://stackoverflow.com/a/50971838
type: Comment
score: 0
has text: Slightly faster than my solution but still slower than that of @taras.
type: AnswerComment

http://stackoverflow.com/a/50929003
has body: @Aaron is already covering well the error regarding the numerical meaning of your loss, and why you should consider native Tensorflow losses such as tf.losses.sparse_softmax_cross_entropy(). I will personally focus on "why the NaNs?". Possible Reason: As your weight and bias variables can take negative values, it is possible that your network output out = tf.matmul(l3, output['weight'])+ output['bias'] becomes negative too. When it happens, tf.log(neural_network_model(x)) will output NaN (as the logarithm is undefined for null and negative values), and so will your cross_entropy loss. Making sure your network output is positive (e.g. adding another relu or softmax + adding a small positive epsilon inside tf.log() e.g. tf.log(out + 1e-8)) may solve your problem. Demonstration: To make my point clear regarding your possibly-negative y and thus tf.log(y) == NaN, find below your slightly edited code. Besides some optimizations and input-mocking, your network architecture is the same. I only edited the initialization of the weights/bias of the last layer (in a dirty way...) to ensure y &gt;= 0: import tensorflow as tf import numpy as np n_node_hl1 = 100 n_node_hl2 = 100 n_node_hl3 = 100 n_classes = 62 hidden_layer_1 = {'weight': tf.Variable(tf.random_normal([4096, n_node_hl1])), 'bias': tf.Variable(tf.random_normal([n_node_hl1]))} hidden_layer_2 = {'weight': tf.Variable(tf.random_normal([n_node_hl1, n_node_hl2])), 'bias': tf.Variable(tf.random_normal([n_node_hl2]))} hidden_layer_3 = {'weight': tf.Variable(tf.random_normal([n_node_hl2, n_node_hl3])), 'bias': tf.Variable(tf.random_normal([n_node_hl3]))} # &gt;&gt;&gt; CHANGE: MAKING SURE THE OUTPUT VARIABLES HAVE POSITIVE VALUES SO LOG(OUTPUT) != NaN # note: you do NOT want to do that! tf.abs() here are just to make my point. output = {'weight': tf.Variable(tf.abs(tf.random_normal([n_node_hl3, n_classes]))), 'bias': tf.Variable(tf.abs(tf.random_normal([n_classes])))} def neural_network_model(data): l1 = tf.add(tf.matmul(da…
has comment: http://stackoverflow.com/comment/88858378
has comment: http://stackoverflow.com/comment/88857247
type: Answer
downvote count: 1
answers question: http://stackoverflow.com/q/50928863
score: -1
upvote count: 0

http://stackoverflow.com/comment/95378750
has text: Note that in recent versions of Telethon, `client.get_messages(chat, limit=400)` should work just fine.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50975793

http://stackoverflow.com/q/50997096
answer count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/96845784
type: UnansweredQuestion
tagged with: selenium
tagged with: google-chrome
score: 2
has comment: http://stackoverflow.com/comment/96846297
has comment: http://stackoverflow.com/comment/88992720
has body: I purchased a VPS &mdash; my first ever &mdash; which is running CentOS 7 64-bit. I had absolutely zero experience with CentOS 7 until I began using this VPS today, so please go easy on me. When trying to scrape some dynamically generated content with Scrapy and Selenium, the script ultimately fails and the log throws an error that reads: DevToolsActivePort file doesn't exist On the very next line in the log, it pulls up info about the Chrome WebDriver: (Driver info: chromedriver=2.40.565383 ... Hence I suspect the issue has nothing to do with locating webdriver. I've included part of the log below. The execution of the script always begins to hang for an extended period of time before ultimately failing when Selenium is first queried, which is why I haven't included the purely Scrapy part of the log. The second-to-top answer with 4 votes on this thread reads, "This error message implies that the ChromeDriver was unable to initiate/spawn a new WebBrowser i.e. Chrome Browser session." I've installed the Chrome Browser according to these instructions from the official repository. Chrome is installed in the /usr/bin/google-chrome directory, whereas chromedriver is located in the /usr/local/bin/ directory. Both directories have been added to PATH. I've tried searching section 7.1 Exceptions in this non-official Selenium documentation for anything having to do with this error, but came up empty handed. When I try to launch Google Chrome on the VPS via SSH, I get an error that reads [83526:83526:0622/212649.156252:ERROR:zygote_host_impl_linux.cc(88)] Running as root without --no-sandbox is not supported. See https://crbug.com/638180. and links to a page that is no longer available... When I try to open Chrome with the --no-sandbox parameter, I then get the error: (google-chrome-stable:85573): Gtk-WARNING **: cannot open display: [0622/221013.556327:ERROR:nacl_helper_linux.cc(310)] NaCl helper process running without a sandbox! Most likely you need to configure your SUID s…
has comment: http://stackoverflow.com/comment/96846067
type: Question
has comment: http://stackoverflow.com/comment/88995380
downvote count: 0
has title: Selenium/Chrome/ChromeDriver Issue Preventing Crawl on VPS (DevToolsActivePort file doesn't exist)
tagged with: linux
tagged with: python
linked to: http://stackoverflow.com/q/50642308
favorite count: 0
tagged with: selenium-chromedriver

http://stackoverflow.com/comment/88863241
has text: @LearningPython The option you mention with setting a flag that is checked each loop, is the recommended way to do this.
comment on: http://stackoverflow.com/q/50911444
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50869991
has title: code showing empty dataframe
has body: I write the below code for my project but dataframe df showing empty records.I want to know where i am lacking in the code: import urllib from urllib2 import * import pandas as pd def urlmake(req): requests = [req] for parms in requests: url = 'http://localhost:8983/solr/data/select?indent=on&amp;' + urllib.urlencode(parms) connection = urlopen(url) response = eval(connection.read()) t = response['response']['numFound'] req2 = req['q'][13:17] print(req2) if(req2 == 'AXIS'): print('true') for i in range(0,t): t1 = float((response['response']['docs'][i]['message']).split(" ")[1]) #print(t1) t2 = response['response']['docs'][i]['customer_id'] #print(t2) df = df.append(pd.DataFrame(t2,t1)) ba_query = [{'q':'sender_name:*AXIS* AND message:*Avbl Lmt*','start':0,'rows':211,'wt':'json'}] for i in range(0,len(ba_query)): urlmake(ba_query[i]) getting errror as: UnboundLocalError: local variable 'df' referenced before assignment
has comment: http://stackoverflow.com/comment/88741594
tagged with: pysolr
has comment: http://stackoverflow.com/comment/88741666
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88741725
accepted answer: http://stackoverflow.com/a/50870037
answer count: 1
has answer: http://stackoverflow.com/a/50870037
score: 0
has comment: http://stackoverflow.com/comment/88741700
tagged with: python
tagged with: python-2.x

http://stackoverflow.com/comment/88963890
comment on: http://stackoverflow.com/a/50978831
has text: The thing is that I'm reading a [http://shop.oreilly.com/product/0636920052289.do](book) and it is talking about the `decision_function`. So I'm trying to get head around it.
type: AnswerComment
type: Comment
score: 1

http://stackoverflow.com/a/54706465
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/50952937
upvote count: 1
answers question: http://stackoverflow.com/q/50952937
has body: After long time trying and reading everywhere I realized the problem was caused by self-signed certificates. I generated new certificates with different Common Names for CA and broker and everything seems to work fine.
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/50993365
favorite count: 0
tagged with: roc
upvote count: 2
tagged with: python
has title: How to put Bokeh legend on the 'bottom_right'
has body: I am trying to produce an ROC curve using Bokeh. I have the following code that used to run before, but now I get an error saying: ValueError: invalid value: 'bottom_right'; allowed values are horizontal or vertical p = figure(title='ROC Curve: Logistic Regression', width=800, height=800) p.line(x=fpr, y=tpr, legend='ROC Curve: Area Under Curve = %0.3f' %roc_auc) p.legend.orientation = 'bottom_right' p.xaxis.axis_label = 'False Positive Rate' p.yaxis.axis_label = 'True Positive Rate' show(p) All I want to do is to put the legend at the bottom of the screen so it won't cover part of the curve. Can anyone advise please? Thanks.
score: 2
type: AnsweredQuestion
tagged with: bokeh
type: Question
has answer: http://stackoverflow.com/a/50994210
accepted answer: http://stackoverflow.com/a/50994210
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/88834033
has text: It would be nice, if you could add a little bit more context (e.g runnable function, import, etc) to your code. It will make your problem reproducable for others, so it will be easier to help you.
comment on: http://stackoverflow.com/q/50916624
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/q/50891877
answer count: 1
accepted answer: http://stackoverflow.com/a/50893252
type: AnsweredQuestion
has title: Multiple buttons in html, same view, different values
has body: I'm trying to have my html display a session.counter on an HTML page. The counter should increment by a random number, with 4 different options for the range at which it increments (based on buttons). So far, I have all their actions routing to the same view, but I'm not sure how to code the values into the view! Can I nest multiple if-checks into the view? If so, do I need to redirect immediately after each check, or can it be after the if-checks? EDIT: I've tried adding hidden inputs to make my view more efficient. I'm still a novice, so if the more descriptive your feedback, the easier it will be for me to implement changes and understand why! Here's the html: Gold Count: {{ session.request.goldCount }} Blood Lotus Master (earns 50 to 200 gold coins) {% csrf_token %} 収める - Reap Shadow Dance Troupe (earns 35 to 50 gold coins) {% csrf_token %} 織る - Weave Necromancy (earns -200 to 200 gold coins) {% csrf_token %} 召喚 - Summon Clan War! (earns -2000 to 2000 gold coins) {% csrf_token %} 影の戦争 - Shadow War and here is the views.py file def index(request): if 'goldCount' not in request.session: request.session['goldCount'] = 0 return render(request, 'index.html') def process_gold(request): reap = random.randint(50,200) weave = random.randint(35,50) summon = random.randint(-200,200) war = random.randint(-2000,2000) print(request.POST) if request.POST['earn'] == 'reap': request.session['goldCount'] += random.randint(50,200) if request.POST['earn'] == 'weave': request.session['goldCount'] += random.randint(35,50) if request.POST['earn'] == 'summon': request.session['goldCount'] += random.randint(-200,200) if request.POST['earn'] == 'war': request.session['goldCount'] += random.randint(-2000,2000) return redirect('/')
has answer: http://stackoverflow.com/a/50893252
type: Question
tagged with: django
has comment: http://stackoverflow.com/comment/88785940
tagged with: python
tagged with: django-views
score: 0
tagged with: django-forms
has comment: http://stackoverflow.com/comment/88786420

http://stackoverflow.com/comment/88954316
type: QuestionComment
comment on: http://stackoverflow.com/q/50920685
score: 0
has text: Share the image
type: Comment

http://stackoverflow.com/comment/88729257
type: QuestionComment
has text: whats the output you are getting now?
comment on: http://stackoverflow.com/q/50863364
score: 0
type: Comment

http://stackoverflow.com/q/50888329
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/50888646
has body: Hi there I'm trying to get a list of autocorrelations for different shifts. My code is the following: thetas = np.array([0.24233997, 0.33467202, 0.35020237, ...]) autocorrelation = [] for shift in range(1,21): correlation = np.corrcoef(thetas[:-shift], thetas[shift:])[0,1] autocorrelation.append(correlation) This gives me this error: C:\Users\PC\Anaconda3\lib\site-packages\numpy\lib\function_base.py:3175: RuntimeWarning: Degrees of freedom &lt;= 0 for slice c = cov(x, y, rowvar) C:\Users\PC\Anaconda3\lib\site-packages\numpy\lib\function_base.py:3109: RuntimeWarning: divide by zero encountered in double_scalars c *= 1. / np.float64(fact) C:\Users\PC\Anaconda3\lib\site-packages\numpy\lib\function_base.py:3109: RuntimeWarning: invalid value encountered in multiply c *= 1. / np.float64(fact) C:\Users\PC\Anaconda3\lib\site-packages\numpy\lib\function_base.py:1128: RuntimeWarning: Mean of empty slice. avg = a.mean(axis) C:\Users\PC\Anaconda3\lib\site-packages\numpy\core\_methods.py:73: RuntimeWarning: invalid value encountered in true_divide ret, rcount, out=ret, casting='unsafe', subok=False) Does anyone know how to fix this code or another way to create a list of autocorrelations for many different shifts?
tagged with: numpy
score: 0
has title: Autocorrelation function for different shifts with Python
answer count: 1
accepted answer: http://stackoverflow.com/a/50888646
tagged with: python-3.x
tagged with: python

http://stackoverflow.com/q/50942847
accepted answer: http://stackoverflow.com/a/50943209
answer count: 2
tagged with: pandas
upvote count: 1
has answer: http://stackoverflow.com/a/50943209
tagged with: unique
favorite count: 0
has body: I want to determine the count of unique values based off two columns in a pandas df. Below is an example: import pandas as pd d = ({ 'B' : ['08:00:00','John','08:10:00','Gary','08:41:42','John','08:50:00','John', '09:00:00', 'Gary','09:15:00','John','09:21:00','Gary','09:30:00','Gary','09:40:00','Gary'], 'C' : ['1','1','1','1','1','1','2','2','2', '2','2','2','3','3','3', '3','3','3'], 'A' : ['Stop','','Res','','Start','','Stop','','Res','','Start','','Stop','','Res','','Start',''] }) df = pd.DataFrame(data=d) Output: A B C 0 Stop 08:00:00 1 1 John 1 2 Res 08:10:00 1 3 Gary 1 4 Start 08:41:42 1 5 John 1 6 Stop 08:50:00 2 7 John 2 8 Res 09:00:00 2 9 Gary 2 10 Start 09:15:00 2 11 John 2 12 Stop 09:21:00 3 13 Gary 3 14 Res 09:30:00 3 15 Gary 3 16 Start 09:40:00 3 17 Gary 3 If I perform the count based of Column A and C I return the following: k = df.groupby('A').C.nunique() Res 3 Start 3 Stop 3 I'm hoping to split those up based on the people in Column B. So the intended output would be: John Stop 2 Res 0 #Nan Start 2 Gary Stop 1 Res 3 Start 1 I have tried k = df.groupby('A').B.C.nunique()
tagged with: python
has answer: http://stackoverflow.com/a/50943270
has title: Count of unique values by groupby in two columns
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question
tagged with: group-by
possible better answer: http://stackoverflow.com/a/50943270

http://stackoverflow.com/q/50925382
has comment: http://stackoverflow.com/comment/88850104
tagged with: python
type: AnsweredQuestion
upvote count: 0
has answer: http://stackoverflow.com/a/50925589
has comment: http://stackoverflow.com/comment/88850233
accepted answer: http://stackoverflow.com/a/50925589
has comment: http://stackoverflow.com/comment/88850246
has body: I have row value of a voltage measurement. -Infinity, 0.00061050, 0.00061050, -Infinity, 0.00061050, -Infinity, -Infinity, 0.00061050, 0.00122100, Infinity, Infinity, Infinity, Infinity, I only need the "Infinity" replaced with 1 actually numpy converts "+/-Infinity" to -inf or inf &gt; import matplotlib.pyplot as plt &gt; import numpy as np &gt; &gt; x, y, z = &gt; np.loadtxt('20180618-0001_innen_aussen_innen_0_25_Sek_Abtast.csv', &gt; delimiter=',', skiprows=10, unpack=True) &gt; &gt; z[z == '-inf'] = 1 &gt; &gt; print(z) plt.plot(x,y,z, label='Loaded from file!') &gt; &gt; plt.xlabel('x') &gt; &gt; plt.ylabel('y') &gt; &gt; plt.title('Interesting Graph\nCheck it out') &gt; &gt; plt.legend() &gt; &gt; plt.show()
type: Question
tagged with: numpy
answer count: 2
has comment: http://stackoverflow.com/comment/88883381
score: -1
possible better answer: http://stackoverflow.com/a/50929747
has answer: http://stackoverflow.com/a/50929747
downvote count: 1
has title: search and replace a string in cell
tagged with: string
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/q/51008838
has comment: http://stackoverflow.com/comment/89012893
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89011874
has comment: http://stackoverflow.com/comment/89010741
has comment: http://stackoverflow.com/comment/89011944
answer count: 0
downvote count: 0
duplicate of: http://stackoverflow.com/q/43322964
score: 1
favorite count: 0
linked to: http://stackoverflow.com/q/31172719
type: Question
has comment: http://stackoverflow.com/comment/89010778
tagged with: upgrade
tagged with: python
has comment: http://stackoverflow.com/comment/89010759
has comment: http://stackoverflow.com/comment/89011907
tagged with: installation
has body: I tried to install new packages, for example by executing : ! pip install ggplot But when I do this, I get an error : PermissionError: [WinError 5] Accès refusé: 'C:\\Program Files\\Anaconda3\\Lib\\site-packages\\brewer2mpl' You are using pip version 8.1.2, however version 10.0.1 is available. You should consider upgrading via the 'python -m pip install --upgrade pip' command. So I tried to execute as they ask : python -m pip install --upgrade pip Then I get this error : SyntaxError: invalid syntax (&lt;ipython-input-8-93493bbcf27f&gt;, line 1) File "&lt;ipython-input-8-93493bbcf27f&gt;", line 1 python -m pip install --upgrade pip ^ SyntaxError: invalid syntax Is there anyone who knows where I did wrong ?
upvote count: 1
has comment: http://stackoverflow.com/comment/89011930
has title: I can't install new packages / Python asks me to upgrade with its new version, but it doesn't work neither
has comment: http://stackoverflow.com/comment/89010748

http://stackoverflow.com/q/50947816
type: UnansweredQuestion
tagged with: python
has body: Im trying to plot a 3D surface of the implied volatility. But i keep getting this error message for the BS function: line 29, in _amin return umr_minimum(a, axis, None, out, keepdims) TypeError: '&lt;=' not supported between instances of 'builtin_function_or_method' and 'builtin_function_or_method' Code I'm running: def CND(X): return float(norm.cdf(X)) def BlackScholes(v=0.8,CallPutFlag = 'c',S = 110.,X = 100.,T = 1.,r = 0.01): try: d1 = (log(S/X)+(r+v*v/2.)*T)/(v*sqrt(T)) d2 = d1-v*sqrt(T) if CallPutFlag=='c': return S*CND(d1)-X*exp(-r*T)*CND(d2) else: return X*exp(-r*T)*CND(-d2)-S*CND(-d1) except: return 0 def calc_impl_vol(price = 5., right = 'c', underlying = 110., strike = 100., time = 1., rf = 0.005, inc = 0.001): f = lambda x: BlackScholes(x,CallPutFlag=right,S=underlying,X=strike,T=time,r=rf)-price return optimize.brentq(f,0.,5.) def mesh_plot2(X,Y,Z): fig = plt.figure() ax = Axes3D(fig, azim = -29, elev = 50) XX,YY,ZZ = make_surf(X,Y,Z) ax.plot_surface(XX,YY,ZZ, color = 'white') ax.contour(XX,YY,ZZ) plt.xlabel("expiry") plt.ylabel("strike") def make_surf(X,Y,Z): XX,YY = np.meshgrid(np.linspace(min(X),max(X),230),np.linspace(min(Y),max(Y),230)) ZZ = griddata(np.array([X,Y]).T,np.array(Z),(XX,YY), method='linear') return XX,YY,ZZ F=pd.read_excel('test_data.xlsx') def get_surf(F): q=F q.reset_index(inplace=True) vals = [] for index, row in q.iterrows(): if row['Type'] == 'c': underlying = float(row['Underlying_Price']) price = (float(row['ask'])+float(row['bid']))/2.0 expd = (row['exp']) exp1 = (expd) / (365) try: impl = calc_impl_vol(price, 'c', underlying, float(row['Strike']), exp1) vals.append([exp,float(row['Strike']),impl]) except: pass vals = np.array(vals).T mesh_plot2(vals[0],vals[1],vals[2]) surf=get_surf(F) I suspect the error is in the vals because it is returned as an "ndarray object of numpy module" I have tried everything my beginner python coding mind can think of. Is there anyone who can see my mistake.
answer count: 0
has comment: http://stackoverflow.com/comment/88896131
type: Question
has comment: http://stackoverflow.com/comment/88895441
has comment: http://stackoverflow.com/comment/88895935
has comment: http://stackoverflow.com/comment/88895117
has comment: http://stackoverflow.com/comment/124402798
tagged with: numpy
score: 0
tagged with: 3d
has title: 3D plot of volatility surface
tagged with: finance
tagged with: python-3.x

http://stackoverflow.com/comment/89002664
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50952453
has text: Check my answer [here](https://stackoverflow.com/questions/50178109/python-modules-installing-properly-but-dont-exist-in-editors/50178345#50178345) I believe it will solve your issue

http://stackoverflow.com/q/50892010
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/88784740
type: Question
has body: I'm new to django, I follow a tutorial from udemy (tweetme) While setting-up rest_framework to load serialized data as json, I get these errors : TypeError: e.indexOf is not a function in : jquery-3.3.1.min.js:2:82466 and : Source map error: request failed with status 404 Resource URL: http://127.0.0.1:8000/static-directory/rest_framework/css/bootstrap.min.css Source Map URL: bootstrap.min.css.map I just used serialized classes and simple view to display my data, (I got the display but still have the error) The output in my console: [17/Jun/2018 08:50:24] "GET / HTTP/1.1" 200 5324 [17/Jun/2018 08:50:24] "GET /static-directory/rest_framework/js/csrf.js HTTP/1.1" 304 0 [17/Jun/2018 08:50:24] "GET /static-directory/rest_framework/js/ajax-form.js HTTP/1.1" 304 0 [17/Jun/2018 08:50:24] "GET /static-directory/rest_framework/js/jquery-3.3.1.min.js HTTP/1.1" 304 0 . //other .css and .js with a success GET (200 and 3xx) . [17/Jun/2018 08:50:24] "GET /static-directory/rest_framework/css/bootstrap.min.css HTTP/1.1" 200 121200 [17/Jun/2018 08:50:24] "GET /static-directory/rest_framework/img/grid.png HTTP/1.1" 200 1458 [17/Jun/2018 08:50:25] "GET /static-directory/rest_framework/css/bootstrap.min.css.map HTTP/1.1" 404 1764 Here is my code: in "/tweets/models.py": from django.conf import settings from django.db import models class Tweet(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default = 1,on_delete=models.CASCADE) content = models.CharField(max_length=150, default="") boolean = models.BooleanField(default=True) timestamp = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) in "/tweets/api/views.py": from rest_framework import generics from .serializers import TweetSerializer from tweets.models import Tweet class TweetListApiView(generics.ListAPIView): serializer_class = TweetSerializer def get_queryset(self): return Tweet.objects.all() in "/tweets/api/serializers.py": from rest_framework import serializers from tweets.mo…
has title: rest_framework TypeError e.indexOf is not a function | bootstrap.min.css 404 not found
has comment: http://stackoverflow.com/comment/88786220
has answer: http://stackoverflow.com/a/50895319
answer count: 1
tagged with: jquery
tagged with: django-rest-framework
favorite count: 0
tagged with: typeerror
upvote count: 2
downvote count: 2
tagged with: django
tagged with: python
accepted answer: http://stackoverflow.com/a/50895319

http://stackoverflow.com/a/50986358
has comment: http://stackoverflow.com/comment/89006951
score: 1
has comment: http://stackoverflow.com/comment/89007880
upvote count: 1
has comment: http://stackoverflow.com/comment/89006946
has comment: http://stackoverflow.com/comment/89012668
has comment: http://stackoverflow.com/comment/89012689
has body: To open sheet sheetname from excel_path use df = pd.read_excel(excel_path, sheetname=sheetname) Consider the dataframe: df = pd.DataFrame({"a": [1,2,3,4,5,6], "b": [7,8,9,0,1,2], "c": [3,4,5,6,7,8], "date": ["2018-01-01", "2018-02-02", "2018-03-03", "2018-04-04", "2018-05-05", "2018-06-06"]}) &gt; a b c date 0 1 7 3 2018-01-01 1 2 8 4 2018-02-02 2 3 9 5 2018-03-03 3 4 0 6 2018-04-04 4 5 1 7 2018-05-05 5 6 2 8 2018-06-06 First, convert date column to datetime dtype with necessary format: df["date"] = pd.to_datetime(df["date"], format="%Y-%m-%d") Get differences between items in df["date"] and today and filter them: days_threshold = 60 filtered_ix = (pd.Timestamp("now") - df["date"]).dt.days &lt; days_threshold Select filtered rows from dataframe using .loc filtered_df = df.loc[filtered_ix] To save filtered rows to Excel on sheet output_sheet with filepath output_path use df.to_excel: filtered_df.to_excel(output_path, sheet_name=output_sheet, index=False)
has comment: http://stackoverflow.com/comment/89013227
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50985537
has comment: http://stackoverflow.com/comment/88975404
answers question: http://stackoverflow.com/q/50985537
type: Answer
has comment: http://stackoverflow.com/comment/88975803

http://stackoverflow.com/q/50966269
tagged with: glob
accepted answer: http://stackoverflow.com/a/50966556
tagged with: python
tagged with: opencv
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88929271
tagged with: image-processing
type: Question
tagged with: numpy
has title: read dynamic number of images of same shape into Python NumPy array
has answer: http://stackoverflow.com/a/50966556
has body: I have this code: image_list = [] for filename in glob.glob('C:\\Users\\Utilizador\\Desktop\\menu\\*.jpg'): im=cv2.imread(filename) image_list.append(im) This creates me a list of images, but I need it to be in an array form with shape (num_of_images, width, height, 3) All images have the same shape Any ideas? Thanks
score: 0
answer count: 1

http://stackoverflow.com/a/50923513
has body: Replacing the hour parameter Since a time object has a range from 00:00 to 23:59. In case you add one hour, it can thus get out of range, and hence it is no longer a time object. We can however implement this with wraparound (this means that for example 23:59 and two minutes is 00:01) ourselves, like: a = start.replace(hour=(start.hour+1) % 24) We here thus replace the hours of the start (we are not replacing it on the start object, but create a copy) with (start.hour + 1) % 24. The modulo 24 is necessary to make perform the wraparound. Storing a timestamp in a DateTimeField The above is however not a nice way to do this: typically time depends on the timezone (location) and the specific date (for example daylight saving time, some countries have changed the timezone, etc.). Therfore I advice you to use a DateTimeField instead of a TimeField. For example in october 28, 2018 some parts of the world enter daylight saving time, and that means that if you add one hour, the clock can in some cases, still display the same numbers. With a TimeField, this context is lost: we will change the numbers of the clock, regardless what the time is, and what the specific laws of the culture of the user are saying.
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50923151
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50923151
type: Answer
score: 3
upvote count: 3

http://stackoverflow.com/q/51006378
type: UnansweredQuestion
tagged with: python
answer count: 0
tagged with: openpyxl
has comment: http://stackoverflow.com/comment/89006748
type: Question
has comment: http://stackoverflow.com/comment/89015388
has body: I have been struggling with this code all day. During each run of the loop, a table is read from a different MS Word file. The table is copied to a dataframe and then it is copied to a row in an Excel file. With each subsequent run of the for-loop, the Excel row is incremented so the new dataframe can be written to a new row, but after the file executes only one row is showing a dataframe. When I print(tfile), I get the following .. ('CIV-ASCS-016_TRS.docx', 'CIV-ASCS-018_TRS .docx', 'CIV-ASCS-020_TRS.docx', 'CIV-ASCS-021_TRS .docx') This proves that loop ran 4 times based on 4 files in the directory. I set the initial row pos to 0 outside of the for-loop. Note: I am not showing any lines of code with regards to importing the necessary libraries. files = glob('*.docx') pos = 1 for i, wfile in enumerate(files[:1]): document = Document(wfile) table = document.tables[0] data = [] keys = {} for j, row in enumerate(table.rows): text = (cell.text for cell in row.cells) if j == 0: keys = tuple(text) continue row_data = dict(zip(keys, text)) data.append(row_data) tfile = tuple(files) df = pd.DataFrame(data) df.loc[-1] = [wfile, 'Test Case ID'] df.index = df.index + 1 # shifting index df = df.sort_index() # sorting by index df1 = df.rename(index=str, columns={"Test Case ID": "TC Attributes"}) df21 = df1.drop(columns = ['TC Attributes']) df3 = df21.T # read the existing sheets so that openpyxl won't create a new one later book = load_workbook('test.xlsx') writer = pd.ExcelWriter('test.xlsx', engine='openpyxl') writer.book = book writer.sheets = dict((ws.title, ws) for ws in book.worksheets) df3.to_excel(writer, 'sheet7', header = False, index = False, \ startrow = pos) pos += 1 writer.save()
has comment: http://stackoverflow.com/comment/89009876
score: 0
tagged with: pandas
has title: For loop with enumerate iterates 4 times, but only 1 dataframe is written to Excel instead of 4 dataframes

http://stackoverflow.com/a/50862811
upvote count: 4
downvote count: 0
score: 4
has body: df2 = df1.sort_values(['Animal', 'Date']) df2['Order']=df1.groupby('Animal').Meal.transform(lambda x : ' '.join(x)) Output: Animal Date Meal Order 2 Cat 01/12/18 Mouse Mouse CatFood 3 Cat 02/23/18 CatFood Mouse CatFood 0 Dog 01/08/18 DogFood DogFood Bone Treat 1 Dog 01/09/18 Bone DogFood Bone Treat 4 Dog 01/15/18 Treat DogFood Bone Treat
answers question: http://stackoverflow.com/q/50862747
has comment: http://stackoverflow.com/comment/88728455
type: Answer

http://stackoverflow.com/comment/88952009
comment on: http://stackoverflow.com/q/50977764
type: Comment
type: QuestionComment
score: 1
has text: @ImportanceOfBeingErnest I edited the photo `plt.yscale('log'), plt.grid() ` But if there are two signal in the graph so it does not easily distinguish between signals. Because the signals are so close to each other.

http://stackoverflow.com/q/50882495
upvote count: 2
type: UnansweredQuestion
has body: Im trying to read in some data from the second sheet of a excel spreadsheet. skipping the first 18 rows and only columns C to F. This is what I have tried import pandas as pd new_file=pd.read_excel("C:\Users\denis\Documents\Dissertation\Raw Data\CO\1213Q1.xls",sheetname=1, skiprows=18, parse_cols=[2,5]) when I run this I get the following error runfile('C:/Users/denis/Documents/Dissertation/Code/test.py', wdir='C:/Users/denis/Documents/Dissertation/Code') File "C:/Users/denis/Documents/Dissertation/Code/test.py", line 9 new_file=pd.read_excel("C:\Users\denis\Documents\Dissertation\Raw Data\CO\1213Q1.xls",sheetname=1, skiprows=18, parse_cols=[2,5]) ^ SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape does anyone know what could be causing this?
has comment: http://stackoverflow.com/comment/88767264
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/88767324
downvote count: 0
has answer: http://stackoverflow.com/a/50882676
favorite count: 0
linked to: http://stackoverflow.com/q/1347791
has title: pandas-read_excel syntax error
tagged with: pandas
linked to: http://stackoverflow.com/q/37400974
tagged with: python
score: 2
has answer: http://stackoverflow.com/a/50882523
duplicate of: http://stackoverflow.com/q/37400974

http://stackoverflow.com/comment/88878554
type: Comment
comment on: http://stackoverflow.com/a/50940225
score: 0
type: AnswerComment
has text: Simply use `mydict` instead of `newdict` (works in Python 2.7 but shows error `RuntimeError: dictionary changed size during iteration` in Python 3.x). I used copy to prevent this, as we would changing dictionary contents while iterating over it.

http://stackoverflow.com/a/50995183
downvote count: 0
score: 4
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88985478
has body: You can accomplish what you want by reindexing your out DataFrame and swapping the levels of the index. Starting from the result of your concatenation: from itertools import product # Swap the index levels out = out.swaplevel(0,1) # Form the product of the two index levels ids = list(product(out.index.get_level_values(0).unique(), out.index.get_level_values(1).unique())) # Reindex out, filling missing with 0 and sorting the index out = out.reindex(ids).fillna(0).sort_index().astype('int') out is now: x1 x2 x4 x5 Name Dean Option1 0 0 0 0 Option2 1 0 1 0 Option3 1 0 1 0 Option4 0 0 0 0 Option5 1 0 1 0 Option6 0 0 0 0 James Option1 1 0 0 2 Option2 0 1 1 1 Option3 1 1 1 3 Option4 0 1 1 1 Option5 1 0 0 2 Option6 1 1 1 3 William Option1 0 1 0 0 Option2 0 0 0 0 Option3 1 1 0 1 Option4 0 1 0 0 Option5 1 0 0 1 Option6 1 0 0 1
type: Answer
accepted answer of: http://stackoverflow.com/q/50994949
upvote count: 4
answers question: http://stackoverflow.com/q/50994949

http://stackoverflow.com/a/69175190
type: Answer
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/136260162
answers question: http://stackoverflow.com/q/50895643
has comment: http://stackoverflow.com/comment/136260180
has body: For anyone using Postgres and django 2 or higher: There is a CIEmailField that stores and retrieves the email address case sensitive but compares it case insensitive. This has the benefit of preserving case in the address (should a user want their address to look like JohnDoe@ImportantCompany.com) without allowing multiple accounts with the same email. Usage is simple: from django.contrib.postgres.fields import CIEmailField # ... class User(AbstractBaseUser, ...): email = CIEmailField(unique=True, ...) # ... Except on migrating I got the error: django.db.utils.ProgrammingError: type "citext" does not exist To solve this, follow this so answer and set up the CITextExtension before the first CreateModel migration operation: from django.contrib.postgres.operations import CITextExtension class Migration(migrations.Migration): ... operations = [ CITextExtension(), ... ] Note: both in the so answer and in the official documentation is stated that you should add it before the first CreateModel migration operation. For me it was sufficient to add it in the first migration that uses the CIEmailField.
upvote count: 2

http://stackoverflow.com/a/54490266
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50883814
has body: I had a same issue, but you need to download it to your site-packpages of where your python is there for python-idle or if ur getting a download error in pycharm , I solved the error by downloading dlib from cmd to the venv of my pycharm.project directory command being install dlib--19.16.0 (current one) or you can download a .whl file which suits your python,processor configuration run dt .whl file and your good to go

http://stackoverflow.com/a/50992500
type: Answer
accepted answer of: http://stackoverflow.com/q/50992407
answers question: http://stackoverflow.com/q/50992407
downvote count: 0
has body: This should do the job... n = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47] n.sort() mylist = [x for x in n if x in range(11, 38)] print(mylist) Want to print that as comma separated string: print(mylist.strip('[]'))
score: 3
type: AcceptedAnswer
upvote count: 3

http://stackoverflow.com/comment/88879264
score: 0
comment on: http://stackoverflow.com/q/50937982
type: Comment
type: QuestionComment
has text: can you share the input path(path), you are passing to your function.

http://stackoverflow.com/a/50890958
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50876440
downvote count: 0
has body: { "format": "time" } uses RFC-3339 section-5.6 "Internet Date/Time Format". http://json-schema.org/latest/json-schema-validation.html#rfc.section.7.3.1 https://www.rfc-editor.org/rfc/rfc3339#section-5.6

http://stackoverflow.com/comment/88905643
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50953681
has text: Which means that all people move out of the Sandbox at the end to use it properly. Is that correct?

http://stackoverflow.com/comment/88780518
comment on: http://stackoverflow.com/a/50889350
score: 0
type: AnswerComment
type: Comment
has text: He doesn't simply want instances with the same args to compare as equal, he wants them to be the same instance. And the only way to do that is to return the original instance.

http://stackoverflow.com/comment/88997114
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51001660
has text: yes U: union and X,Y,A,B etc represent elements of the list

http://stackoverflow.com/comment/88935230
comment on: http://stackoverflow.com/q/50969449
score: 1
has text: Interesting question. Quick and dirty solution is to just use ipython, which already has all that set up.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50912888
type: UnansweredQuestion
downvote count: 2
tagged with: python
score: -2
has answer: http://stackoverflow.com/a/50912954
has comment: http://stackoverflow.com/comment/88829115
type: Question
has title: Range function in prime numbers program
upvote count: 0
answer count: 1
has body: this is a program for printing prime numbers from 2 and 11. for num in range(2,12): prime = True for i in range(2,num): if (num%i==0): prime = False if prime: print num In the second for-loop during the last iteration the value of the num=11 .. so the range should take num as 10 i.e (n-1) but in this program value 11 is still getting printed .. how is that?
tagged with: python-2.7
favorite count: 0
has comment: http://stackoverflow.com/comment/88825929

http://stackoverflow.com/a/65151218
has body: A very simple numpy encoder can achieve similar results more generically. Note this uses the np.generic class (which most np classes inherit from) and uses the a.item() method. If the object to encode is not a numpy instance, then the json serializer will continue as normal. This is ideal for dictionaries with some numpy objects and some other class objects. import json import numpy as np def np_encoder(object): if isinstance(object, np.generic): return object.item() json.dumps(obj, default=np_encoder)
has comment: http://stackoverflow.com/comment/128581741
answers question: http://stackoverflow.com/q/50916422
score: 35
has comment: http://stackoverflow.com/comment/123115384
has comment: http://stackoverflow.com/comment/132290445
has comment: http://stackoverflow.com/comment/118766732
has comment: http://stackoverflow.com/comment/132290568
type: Answer
downvote count: 1
has comment: http://stackoverflow.com/comment/123513126
has comment: http://stackoverflow.com/comment/132302776
has comment: http://stackoverflow.com/comment/132290478
upvote count: 36
has comment: http://stackoverflow.com/comment/119312633
has comment: http://stackoverflow.com/comment/132316356

http://stackoverflow.com/comment/88941706
score: 1
comment on: http://stackoverflow.com/a/50971713
has text: Well, my solution is also O(m*n). How come everybody ignored the first correct answer? Go figure :)
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50991739
type: UnansweredQuestion
has title: Python import error while deploying as package
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/88980418
tagged with: pypi
type: Question
has body: Following is my project structure: root directory | - __init__.py | - notdoneyet.py | - helpers.py | - opencv_generators.py | - seam_carve.py | - imgtovideos.py notdoneyet.py file contains the entry point of project and the remaining scripts are imported as modules and when required. My __init__.py contains following code: from .notdoneyet import user_input from .helpers import createFolder from .helpers import getFileExtension from .helpers import writeImage from .opencv_generators import generateEnergyMap from .opencv_generators import generateColorMap from .imagetovideos import generateVideo from .imagetovideos import getToProcessPaths from .seam_carve import cropByColumn from .seam_carve import cropByRow I have published the package on testPyPI. But when I try to import it after installing on local machine, I get the import error. Initial code for notdoneyet.py: import os, sys, cv2, argparse #Local imports import imgtovideos as itv import helpers as hp #Error on this line import opencv_generators as og import seam_carve as sc def main(argsip): #usr inpt I am getting the error "no module named helpers" Here is screenshot of the error: Please help me. Thank you.
score: 0
tagged with: python-import
has comment: http://stackoverflow.com/comment/88980435
tagged with: packaging
tagged with: importerror

http://stackoverflow.com/comment/88771046
type: Comment
score: 1
has text: Great weapon names `sword_of_eventual_obsolescence`
comment on: http://stackoverflow.com/q/50884518
type: QuestionComment

http://stackoverflow.com/a/56072795
has body: Why don't you just use my_value = os.getenv("SOME_VALUE") It will just return None if it doesn't exist. And if you want, you can throw your own errors.
answers question: http://stackoverflow.com/q/50869968
type: Answer
has comment: http://stackoverflow.com/comment/125107194
upvote count: 4
score: 0
downvote count: 4

http://stackoverflow.com/q/50934908
answer count: 3
possible better answer: http://stackoverflow.com/a/50937853
has title: Get fourth to last line where a string occurs in a file
has answer: http://stackoverflow.com/a/50935261
has answer: http://stackoverflow.com/a/50940500
tagged with: python
has comment: http://stackoverflow.com/comment/88868802
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50937853
has comment: http://stackoverflow.com/comment/88868621
has body: I am currently searching through a log file that contains IP addresses. Log example: 10.1.177.198 Tue Jun 19 09:25:16 CDT 2018 10.1.160.198 Tue Jun 19 09:25:38 CDT 2018 10.1.177.198 Tue Jun 19 09:25:36 CDT 2018 10.1.160.198 Tue Jun 19 09:25:40 CDT 2018 10.1.177.198 Tue Jun 19 09:26:38 CDT 2018 10.1.177.198 Tue Jun 19 09:27:16 CDT 2018 10.1.177.198 Tue Jun 19 09:28:38 CDT 2018 I can currently grab the IP address from the last line of the log. I can also search for all line numbers that have the same IP address. If the last IP address in the log is listed 3 or more times in the log, how can I get the line number for the 3rd to last occurrence of that IP address? For example, I want to get the line number for this line: 10.1.177.198 Tue Jun 19 09:26:38 CDT 2018 Or better yet, just print the entire line. Here is an example of my code: import re def run(): try: logfile = open('read.log', 'r') for line in logfile: x1 = line.split()[0] for num, line in enumerate(logfile, 0): if x1 in line: print("Found " + x1 + " at line:", num) print ('Last Line: ' + x1) logfile.close except OSError as e: print (e) run() I am listing all the line numbers where the specific IP address occurs. print("Found " + x1 + " at line:", num) I am wanting to print the line where "num" is the 3rd to last number in the list of line numbers. My overall goal is to grab the IP address from the last line in the log file. Then check if it has previously been listed more than 3 times. If it has, I want to find the 3rd to last listing of the address and get the line number.(or just print the address and date listed on that line)
has comment: http://stackoverflow.com/comment/88868942
has comment: http://stackoverflow.com/comment/88868713
type: Question
linked to: http://stackoverflow.com/q/2301789
has comment: http://stackoverflow.com/comment/88868652
accepted answer: http://stackoverflow.com/a/50935261
score: 0

event-handling
tag name: event-handling
type: Tag
tags question: http://stackoverflow.com/q/50938297

http://stackoverflow.com/comment/88809739
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50896529
has text: Does it support two columns groupby ?
score: 0

http://stackoverflow.com/a/50986739
downvote count: 1
has body: for i in L: This means while iterating over the list, value of each element in list is stored in i. So if you change the value of i no change will happen in the list Consider this- a=2 b=a b=3 Changing b does not change the value of a.
answers question: http://stackoverflow.com/q/50986441
has comment: http://stackoverflow.com/comment/88968332
type: Answer
upvote count: 0
has comment: http://stackoverflow.com/comment/88968635
has comment: http://stackoverflow.com/comment/88968146
score: -1

http://stackoverflow.com/q/50944405
downvote count: 0
has body: Given the following pandas DataFrame where some indices are NaN, how to drop the third and eight row since their index is NaN? Thanks import pandas as pd import numpy as np data = list('abcdefghil') indices = [0, 1, np.nan, 3, 4, 5, 6, np.nan, 8, 9] df = pd.DataFrame(data, index=indices, columns=['data'])
has answer: http://stackoverflow.com/a/50944440
answer count: 3
tagged with: pandas
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/50944482
accepted answer: http://stackoverflow.com/a/50944440
has answer: http://stackoverflow.com/a/50944468
type: AnsweredQuestion
has title: Pandas: drop rows with nan-valued index
possible better answer: http://stackoverflow.com/a/50944482
upvote count: 5
type: Question
tagged with: numpy
score: 5

http://stackoverflow.com/a/50919068
answers question: http://stackoverflow.com/q/50869939
score: 0
type: AcceptedAnswer
type: Answer
has body: 1 import argparse 2 from argparse import Namespace 3 4 parser = argparse.ArgumentParser() 5 parser.add_argument('--a', default=1) 6 args = parser.parse_args() 7 8 import os 9 if os.path.exists('/tmp/a'): 10 with open('/tmp/a', 'r') as f: 11 ns = f.read() 12 print(ns) 13 args = parser.parse_args(namespace=eval(ns)) 14 else: 15 with open('/tmp/a', 'w') as f: 16 f.write(str(args)) 17 18 print(args.a) since string Namespace(a='2') comes from a Namespace instance, so we can eval it.
accepted answer of: http://stackoverflow.com/q/50869939

http://stackoverflow.com/comment/88768569
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50882841
type: QuestionComment
has text: In foo.py, I've tried editing the import statement to be `import middle.utils as utils` but that gives a `ModuleNotFoundError: no module named 'middle'`. Similarly, if I try something like`from . import utils` that gives a `ImportError: cannot import name 'utils'`.

http://stackoverflow.com/comment/88799593
score: 0
type: Comment
has text: @CoreyGoldberg i'm agree with you, i forgot about `WebDriverWait` that was in @Guy answer
comment on: http://stackoverflow.com/a/50897099
type: AnswerComment

http://stackoverflow.com/comment/88766113
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50881693
has text: Not "interpreter", but rather "compiler".
type: Comment

twilio
tag name: twilio
type: Tag
tags question: http://stackoverflow.com/q/50882497

beautifulsoup
tags question: http://stackoverflow.com/q/50989482
tags question: http://stackoverflow.com/q/50948320
tags question: http://stackoverflow.com/q/50957283
tags question: http://stackoverflow.com/q/50870931
tags question: http://stackoverflow.com/q/50882622
tags question: http://stackoverflow.com/q/50880811
tags question: http://stackoverflow.com/q/50957861
tags question: http://stackoverflow.com/q/50873293
tags question: http://stackoverflow.com/q/51005547
tags question: http://stackoverflow.com/q/50867740
tags question: http://stackoverflow.com/q/50914691
tags question: http://stackoverflow.com/q/50974695
tags question: http://stackoverflow.com/q/50879131
tags question: http://stackoverflow.com/q/50880175
tag name: beautifulsoup
tags question: http://stackoverflow.com/q/50931907
tags question: http://stackoverflow.com/q/50968127
tags question: http://stackoverflow.com/q/50965257
tags question: http://stackoverflow.com/q/50940424
tags question: http://stackoverflow.com/q/50870393
tags question: http://stackoverflow.com/q/50944783
tags question: http://stackoverflow.com/q/51006509
tags question: http://stackoverflow.com/q/51009982
tags question: http://stackoverflow.com/q/50878049
tags question: http://stackoverflow.com/q/50959926
tags question: http://stackoverflow.com/q/50923235
tags question: http://stackoverflow.com/q/50916111
tags question: http://stackoverflow.com/q/50914741
tags question: http://stackoverflow.com/q/50912466
tags question: http://stackoverflow.com/q/51001782
tags question: http://stackoverflow.com/q/50977971
tags question: http://stackoverflow.com/q/50998002
tags question: http://stackoverflow.com/q/50893983
tags question: http://stackoverflow.com/q/50884839
tags question: http://stackoverflow.com/q/50867153
tags question: http://stackoverflow.com/q/50897213
type: Tag
tags question: http://stackoverflow.com/q/50865601
tags question: http://stackoverflow.com/q/50969205
tags question: http://stackoverflow.com/q/50947539
tags question: http://stackoverflow.com/q/51006301
tags question: http://stackoverflow.com/q/50950593
tags question: http://stackoverflow.com/q/50884094
tags question: http://stackoverflow.com/q/50964844
tags question: http://stackoverflow.com/q/50915665
tags question: http://stackoverflow.com/q/50938835
tags question: http://stackoverflow.com/q/50920242
tags question: http://stackoverflow.com/q/50898876
tags question: http://stackoverflow.com/q/50949203
tags question: http://stackoverflow.com/q/50929475
tags question: http://stackoverflow.com/q/50899824
tags question: http://stackoverflow.com/q/50964115
tags question: http://stackoverflow.com/q/50912666
tags question: http://stackoverflow.com/q/50863315
tags question: http://stackoverflow.com/q/50855442
tags question: http://stackoverflow.com/q/50956573
tags question: http://stackoverflow.com/q/50873360
tags question: http://stackoverflow.com/q/50906647
tags question: http://stackoverflow.com/q/50945078
tags question: http://stackoverflow.com/q/50857672
tags question: http://stackoverflow.com/q/50904156
tags question: http://stackoverflow.com/q/50892926
tags question: http://stackoverflow.com/q/50863201
tags question: http://stackoverflow.com/q/50877660
tags question: http://stackoverflow.com/q/50917770

machine-learning
tags question: http://stackoverflow.com/q/50899221
tags question: http://stackoverflow.com/q/50886428
tags question: http://stackoverflow.com/q/50877011
tags question: http://stackoverflow.com/q/50924451
tags question: http://stackoverflow.com/q/50882282
tags question: http://stackoverflow.com/q/50923808
tags question: http://stackoverflow.com/q/50923923
tags question: http://stackoverflow.com/q/50965004
tags question: http://stackoverflow.com/q/51008505
tags question: http://stackoverflow.com/q/50867992
tags question: http://stackoverflow.com/q/50975924
tags question: http://stackoverflow.com/q/50964401
tags question: http://stackoverflow.com/q/50920758
tags question: http://stackoverflow.com/q/50896495
tags question: http://stackoverflow.com/q/50966600
tags question: http://stackoverflow.com/q/50861243
tags question: http://stackoverflow.com/q/50926961
tags question: http://stackoverflow.com/q/50955155
tags question: http://stackoverflow.com/q/50946913
tags question: http://stackoverflow.com/q/50911337
tags question: http://stackoverflow.com/q/50979693
tags question: http://stackoverflow.com/q/50876172
tags question: http://stackoverflow.com/q/51004943
tags question: http://stackoverflow.com/q/50980594
tags question: http://stackoverflow.com/q/50942553
tags question: http://stackoverflow.com/q/50925072
tag name: machine-learning
tags question: http://stackoverflow.com/q/51008555
tags question: http://stackoverflow.com/q/50867573
tags question: http://stackoverflow.com/q/51008162
tags question: http://stackoverflow.com/q/50976429
tags question: http://stackoverflow.com/q/50986948
tags question: http://stackoverflow.com/q/50874279
tags question: http://stackoverflow.com/q/50931180
tags question: http://stackoverflow.com/q/50981478
tags question: http://stackoverflow.com/q/50995005
tags question: http://stackoverflow.com/q/50940827
tags question: http://stackoverflow.com/q/50994116
tags question: http://stackoverflow.com/q/50997028
tags question: http://stackoverflow.com/q/50914245
type: Tag
tags question: http://stackoverflow.com/q/50965217
tags question: http://stackoverflow.com/q/50877791
tags question: http://stackoverflow.com/q/50999596
tags question: http://stackoverflow.com/q/50897444
tags question: http://stackoverflow.com/q/50921502
tags question: http://stackoverflow.com/q/50986575
tags question: http://stackoverflow.com/q/50863494
tags question: http://stackoverflow.com/q/50869405
tags question: http://stackoverflow.com/q/50996623
tags question: http://stackoverflow.com/q/50975447
tags question: http://stackoverflow.com/q/50897244
tags question: http://stackoverflow.com/q/50961658
tags question: http://stackoverflow.com/q/50963187
tags question: http://stackoverflow.com/q/50991972
tags question: http://stackoverflow.com/q/50914860
tags question: http://stackoverflow.com/q/50912994
tags question: http://stackoverflow.com/q/50880224
tags question: http://stackoverflow.com/q/50975701
tags question: http://stackoverflow.com/q/50972234
tags question: http://stackoverflow.com/q/50897557
tags question: http://stackoverflow.com/q/50932433
tags question: http://stackoverflow.com/q/51000841
tags question: http://stackoverflow.com/q/51007631
tags question: http://stackoverflow.com/q/50884043
tags question: http://stackoverflow.com/q/51008752
tags question: http://stackoverflow.com/q/50883917
tags question: http://stackoverflow.com/q/50957340
tags question: http://stackoverflow.com/q/50931168
tags question: http://stackoverflow.com/q/50913468
tags question: http://stackoverflow.com/q/50932489
tags question: http://stackoverflow.com/q/50928392
tags question: http://stackoverflow.com/q/50999504
tags question: http://stackoverflow.com/q/50939526
tags question: http://stackoverflow.com/q/50961057
tags question: http://stackoverflow.com/q/51007989
tags question: http://stackoverflow.com/q/50993978
tags question: http://stackoverflow.com/q/50904858
tags question: http://stackoverflow.com/q/50934706
tags question: http://stackoverflow.com/q/50890791

http://stackoverflow.com/a/50958316
downvote count: 0
has comment: http://stackoverflow.com/comment/88913947
has body: __setattr__ is a special method: For custom classes, implicit invocations of special methods are only guaranteed to work correctly if defined on an object’s type, not in the object’s instance dictionary. Python doesn't document anywhere exactly which special methods skip the instance dictionary, and when they do so—in fact, it's really up to each implementation—but (at least in CPython and PyPy), __setattr__ always goes straight to the type. Note that PEP 562 adds a special case for __getattr__ and __dir__ on ModuleType to Python 3.7, but does not include __setattr__. So, assigning sys.__setattr__ has no effect. This is also why '__setattr__' in dir(sys) is False—just as it is for anything that isn't a type. The dir function doesn't return attributes found on the class (or inherited from a base class). If you want to check for an attribute, you normally use hasattr(sys, '__setattr__')—or, better, just try to access the attribute (because that works even with, e.g., dynamic attributes created by custom __getattribute__). Also, this means that the place to set your breakpoint would be types.ModuleType.__setattr__ (or type(sys).__setattr__, which is the same place). But that isn't going to work in CPython, because that's a C function slot on a builtin type (actually just inherited from object.__setattr__), not a Python method. There are two traditional ways around this. Neither of them is guaranteed to work with builtin modules; from a quick test, with CPython 3.7, the first one works but the second doesn't. But try them both on your own Python implementation/version. First, you can just create a subclass: class HookedModuleType(types.ModuleType): def __setattr__(self, name, value): print(f'{self.__name__}.__setattr__({name}, {value})') return super().__setattr__(name, value) … and then re-type the module: mymodule.__class__ = HookedModuleType Alternatively, since ModuleType doesn't override the default behavior of __setattr__, it just inherits it from object, which me…
has comment: http://stackoverflow.com/comment/88914092
accepted answer of: http://stackoverflow.com/q/50958222
has comment: http://stackoverflow.com/comment/88913969
has comment: http://stackoverflow.com/comment/88913921
has comment: http://stackoverflow.com/comment/88914042
type: Answer
answers question: http://stackoverflow.com/q/50958222
has comment: http://stackoverflow.com/comment/88943778
upvote count: 2
has comment: http://stackoverflow.com/comment/88914015
has comment: http://stackoverflow.com/comment/88914024
has comment: http://stackoverflow.com/comment/88914100
score: 2
has comment: http://stackoverflow.com/comment/88913912
has comment: http://stackoverflow.com/comment/88914050
type: AcceptedAnswer

http://stackoverflow.com/comment/88940071
type: QuestionComment
comment on: http://stackoverflow.com/q/50971064
has text: Have you seen this? https://docs.scipy.org/doc/numpy/user/numpy-for-matlab-users.html
score: 0
type: Comment

http://stackoverflow.com/comment/88939672
score: 0
has text: @Cameron, like what ?! .. if it solve my problem why not
comment on: http://stackoverflow.com/q/50971337
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88776175
type: Comment
has text: Use np.where. I am in a mobile, as soon I get to my laptop I can post a solution.
score: 0
comment on: http://stackoverflow.com/q/50885585
type: QuestionComment

http://stackoverflow.com/q/50913499
answer count: 1
duplicate of: http://stackoverflow.com/q/24380791
linked to: http://stackoverflow.com/q/14162026
favorite count: 0
tagged with: python-3.x
tagged with: python
has answer: http://stackoverflow.com/a/50913604
accepted answer: http://stackoverflow.com/a/50913604
score: 2
type: AnsweredQuestion
downvote count: 0
linked to: http://stackoverflow.com/q/24380791
type: Question
tagged with: numpy
tagged with: vector
has title: vector substitution in numpy/python
tagged with: arrays
upvote count: 2
has body: Given two vectors v=['a','b','c'] and i=np.random.randint(len(v),size=10), I can get the "substitution" vector vi = [v[i[x]] for x in range(len(i))] E.g., vi is ['a', 'a', 'c', 'c', 'b', 'a', 'c', 'a', 'c', 'a'] if i = array([0, 0, 2, 2, 1, 0, 2, 0, 2, 0]) Is there a vectorized operation for this?

http://stackoverflow.com/comment/88941363
type: QuestionComment
type: Comment
score: 1
has text: @ᴡʜᴀᴄᴋᴀᴍᴀᴅᴏᴏᴅʟᴇ3000 "convert my excel data in to .txt format by pipe (|) delimited." They want `to_csv`.
comment on: http://stackoverflow.com/q/50972328

http://stackoverflow.com/comment/88875268
score: 0
has text: try `if_exists='append'`
comment on: http://stackoverflow.com/q/50938216
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50922533
score: 1
upvote count: 1
type: Question
downvote count: 0
accepted answer: http://stackoverflow.com/a/50922584
tagged with: dataframe
tagged with: pandas
answer count: 1
favorite count: 0
has body: I have a DataFrame df with 2000 rows. The first few rows look like the following: +--------------+----------+--+ | Timestamp | Duration | | +--------------+----------+--+ | 1/5/18 0:23 | 22 | | | 1/5/18 3:34 | 32 | | | 1/5/18 23:48 | 24 | | | 1/6/18 2:26 | 15 | | | 1/6/18 14:13 | 23 | | +--------------+----------+--+ I would like to create a new column C based on the following criteria: if Duration >= 20: then add 20 mins to the timestamp. if Duration &lt; 20: then null. So, given the above information and data, the new table should look like: +--------------+----------+--------------+--+--+ | Timestamp | Duration | C | | | +--------------+----------+--------------+--+--+ | 1/5/18 0:23 | 22 | 1/5/18 0:43 | | | | 1/5/18 3:34 | 32 | 1/5/18 3:54 | | | | 1/5/18 23:48 | 24 | 1/6/18 0:08 | | | | 1/6/18 2:26 | 15 | Null | | | | 1/6/18 14:13 | 23 | 1/6/18 14:33 | | | +--------------+----------+--------------+--+--+ Any ideas on how to do that?
has title: Adding minutes to timestamp in python
has comment: http://stackoverflow.com/comment/88844365
tagged with: datetime
tagged with: python
has answer: http://stackoverflow.com/a/50922584
type: AnsweredQuestion

spyder
tags question: http://stackoverflow.com/q/50864404
tag name: spyder
tags question: http://stackoverflow.com/q/50869441
tags question: http://stackoverflow.com/q/50967990
tags question: http://stackoverflow.com/q/50879241
tags question: http://stackoverflow.com/q/50936819
type: Tag
tags question: http://stackoverflow.com/q/50946003
tags question: http://stackoverflow.com/q/50943962
tags question: http://stackoverflow.com/q/50874157
tags question: http://stackoverflow.com/q/50963625
tags question: http://stackoverflow.com/q/50962531
tags question: http://stackoverflow.com/q/50861659
tags question: http://stackoverflow.com/q/51006038
tags question: http://stackoverflow.com/q/50945363
tags question: http://stackoverflow.com/q/50914978
tags question: http://stackoverflow.com/q/50931076
tags question: http://stackoverflow.com/q/51006884
tags question: http://stackoverflow.com/q/51005141

http://stackoverflow.com/comment/88910570
comment on: http://stackoverflow.com/q/50953465
type: Comment
type: QuestionComment
has text: no because I am not trying to prove sth; I am countering the argument that the issue is due to a wrong python executable or a misalignment between the python executables used by pip and ansible (as you hinted); to put it simply the task fails __no matter the python executable used__
score: 0

http://stackoverflow.com/a/51004649
answers question: http://stackoverflow.com/q/51003884
has body: You can use a list comprehension or generator expression, as described by @PM2Ring. However, if you're going to check for the existence of a language often, it's a good idea to create a set first and use O(1) lookup available to set. Here's an example: from operator import itemgetter tmdbMovie = {'spoken_languages': [{'iso_639_1': 'pt', 'name': 'Português'}, {'iso_639_2': 'pt', 'name': 'Français'}]} language_names = set(map(itemgetter('name'), tmdbMovie['spoken_languages'])) if 'Português' in language_names: # do something
score: 0
type: Answer

http://stackoverflow.com/q/50914204
has answer: http://stackoverflow.com/a/50914304
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/50915062
has comment: http://stackoverflow.com/comment/88828541
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/88828510
favorite count: 0
tagged with: python-3.x
has body: I am learning 'Exceptions' in Python. Consider the following code : def fancy_divide(): try: print(5/0) except Exception: print(Exception) If I run the above code, ie fancy_divide() it prints out &lt;class 'Exception'&gt;. But if I modify the code : def fancy_divide(): try: print(5/0) except Exception as ex: print(ex) It prints out 'division by zero' on calling the function fancy_divide(). Why this difference? I thought that the 'as' keyword is just to rename objects.
has title: What is 'as' keyword doing in the following code?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88828482
tagged with: python
has comment: http://stackoverflow.com/comment/88828678
score: 4

http://stackoverflow.com/q/50981884
has body: These are my models where Apps have menu_items: class App(models.Model): name = models.CharField(max_length=50) class Menu(models.Model): name = models.CharField(max_length=120) app = models.ForeignKey(App, on_delete=models.PROTECT) url = models.CharField(max_length=120, null=True) class Meta: ordering = ['name', 'app'] This is my View, is there any way this can be optimized? class AboutView(TemplateView): template_name = 'about.html' def get_context_data(self, *args, **kwargs): context = super(AboutView, self).get_context_data(*args, **kwargs) menu_items = Access.objects.filter(user__id=self.request.user.id) applist = [] for m in menu_items: applist.append(m.menu.app.name) apps = App.objects.filter(name__in=applist) context = { "menu_items": menu_items, "apps": apps } return context This is my template, I rearrange the menu_items under each app. {% for app in apps %} {{ app.name }} {% for item in menu_items %} {% if item.menu.app.name == app.name %} {{ item.menu.name }} {# href="{{ item.menu.url }} #} {% endif %} {% endfor %} {% endfor %} I was hoping there was a better way in doing this. Thank you in advance. As requested, here is the Access Model class Access(models.Model): menu = models.ForeignKey(Menu, on_delete=models.PROTECT) user = models.ForeignKey(User, on_delete=models.PROTECT)
downvote count: 0
has comment: http://stackoverflow.com/comment/88959561
possible better answer: http://stackoverflow.com/a/50994396
has comment: http://stackoverflow.com/comment/88963314
has comment: http://stackoverflow.com/comment/88960189
type: Question
has answer: http://stackoverflow.com/a/50994396
has comment: http://stackoverflow.com/comment/88960773
has answer: http://stackoverflow.com/a/50990106
accepted answer: http://stackoverflow.com/a/50990106
upvote count: 2
answer count: 2
tagged with: filter
tagged with: django-queryset
has comment: http://stackoverflow.com/comment/88959335
has comment: http://stackoverflow.com/comment/88973791
favorite count: 0
tagged with: model
has title: Django: How to get a distinct Parent List from a Child Queryset related to the User?
tagged with: django
tagged with: python
score: 2
type: AnsweredQuestion

http://stackoverflow.com/comment/88803927
comment on: http://stackoverflow.com/a/50895073
has text: was just confused why you implied OP uses flask
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/50916692
upvote count: 1
score: 1
has body: My first association with this question was to use plt.barh - but I have to admit I struggled a while with the datetime / time topics until the result was as I intended... However, this is what came out of the idea: Assumed, the following dataframe would be the start: df Out: timestamp name 0 21:51:38.622 test 1 21:51:38.991 cha.LoginTest4 2 21:51:39.054 cha.LoginTest2 3 21:51:40.068 cha.LoginTest4 4 21:51:40.101 cha.LoginTest2 5 21:51:40.366 cha.LoginTest1 6 21:51:40.413 cha.LoginTest3 7 21:51:50.435 cha.LoginTest1 8 21:51:50.463 cha.LoginTest3 9 21:51:50.484 test At first I'd group by name and create a new dataframe, which contains start and duration data in matplotlib.dates datatype: grpd = df.groupby('name') plot_data = pd.DataFrame({'start': dt.date2num(pd.to_datetime(grpd.min().timestamp)), 'stop': dt.date2num(pd.to_datetime(grpd.max().timestamp))}, grpd.min().index) Subtract the first start time to go from zero (still adding 1 because this is how matplotlib.dates starts) plot_data -= plot_data.start.min() - 1 plot_data['duration'] = plot_data.stop - plot_data.start Based on this dataframe, plotting a horizontal barchart over time is easy: fig, ax = plt.subplots(figsize=(8,4)) ax.xaxis_date() ax.barh(plot_data.index, plot_data.duration, left=plot_data.start, height=.4) plt.tight_layout()
downvote count: 0
has comment: http://stackoverflow.com/comment/88838079
answers question: http://stackoverflow.com/q/50889901
type: Answer

http://stackoverflow.com/a/50952534
type: Answer
score: 7
has comment: http://stackoverflow.com/comment/88907407
has comment: http://stackoverflow.com/comment/88907897
has comment: http://stackoverflow.com/comment/88907779
downvote count: 1
answers question: http://stackoverflow.com/q/50951403
has comment: http://stackoverflow.com/comment/88910337
accepted answer of: http://stackoverflow.com/q/50951403
type: AcceptedAnswer
has body: button.on_click must be given a callback function. You pass the result of on_button_clicked evaluated with parameter 2 (so, literally the square root of 2) instead of passing in a function. You can use partial function evaluation to do what you want, by replacing your last line of code with: import functools button.on_click(functools.partial(on_button_clicked, 2))
upvote count: 8

http://stackoverflow.com/q/50992136
has title: How to plot a shapefile centered in the Pacific with Basemap?
has body: When plotting with Basemap's readshapefile, if the defined map is centered anywhere else than the longitudinal center of the shapefile, only a portion of it it's plotted. Here's an example using Natural Earth's coastlines: import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap shpf = './NaturalEarth/ne_50m_land/ne_50m_land' fig, ax = plt.subplots(nrows=1, ncols=1, dpi=100) m = Basemap( ax = ax, projection = 'cyl', llcrnrlon = 0, llcrnrlat = -90, urcrnrlon = 360, urcrnrlat = 90 ) m.readshapefile(shpf,'ne_50m_land') m.drawmeridians(np.arange(0,360,45),labels=[True,False,False,True]) Which produces: Is there a workaround for this with Basemap or Python? I know some people re-center the shapefile in QGIS or similar, but it seems unpractical to do so every time you create a new map, and my QGIS skills are extremely basic.
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51021870
tagged with: matplotlib-basemap
tagged with: shapefile
tagged with: python-3.x
type: Question
tagged with: python
answer count: 1
score: 0
has answer: http://stackoverflow.com/a/51021870

http://stackoverflow.com/a/51012318
upvote count: 4
type: Answer
score: 3
downvote count: 1
answers question: http://stackoverflow.com/q/51010315
has body: Your problem is, you want PIL to read a PageObject defined by pypdf, which is a wrong way. You should convert pdf to image format, then use PIL to read it. In that case, wand is probably what you need. See its home page. Here is a sample to save all pages in a pdf with jpg format: from wand.image import Image as WImage with WImage(filename=your_pdf_path, resolution=(300,300)) as imgs: imgs.format = 'jpg' page_idx = 0 for img in imgs.sequence: WImage(image=img).save(str(page_idx)+'.jpg') Now, you might want to check out the api mentioned above, and solve your problem.

http://stackoverflow.com/comment/95300481
comment on: http://stackoverflow.com/a/50959070
has text: Hi @SrihariRaghu . I really appreciate your work regarding this answer. I would like to ask one thing. I am facing similar kind of issue for univariate time series prediction. My problem is like this I have value till Dec-2018(monthly basis) Now I am trying to predict for next one year (2019) but not getting any luck. I also tried many methods but nothing is working out for me. Any suggestion or help from your side will be highly appreciated.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/88992471
comment on: http://stackoverflow.com/q/50997477
score: 0
type: Comment
type: QuestionComment
has text: But that is only because the model is empty, there is nothing to save. You directly ask if saving Model is possible.

http://stackoverflow.com/q/50873017
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/88747701
has body: I have downloaded a package with the following general structure: - pkg - runs - __init__.py - script.py - data - subdata - __init__.py - datascript.py When I try to run script.py from the Anaconda prompt using C:\pkg&gt;python runs/script.py I get the error Traceback (most recent call last): File "runs/script.py", line 4, in &lt;module&gt; from data.subdata import * ModuleNotFoundError: No module named 'data.subdata' so apparently, python is interpreting data.subdata as a module instead of a path. How can I fix that?
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/50873156
accepted answer: http://stackoverflow.com/a/50873156
type: AnsweredQuestion
tagged with: anaconda
has title: Module not found error because path is interpreted as module
score: 1
upvote count: 1
type: Question

http://stackoverflow.com/q/50888068
answer count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/30083872
has comment: http://stackoverflow.com/comment/88777936
has body: I am trying to plot S on a fine meshgrid. S is a 2D array with the values at points of SR and Temp. I want to make a fine meshgrid of SR and Temp and plot a contour map of S. I am trying to use RectBivariateSpline, but getting an error while finding Z2. The error I am getting is: in line Z2 = zspline(TT,SR) raise ValueError("Error code returned by bispev: %s" % ier) ValueError: Error code returned by bispev: 10 My code: import numpy as np import matplotlib.pyplot as plt from scipy.interpolate import RectBivariateSpline T = np.array([850,800,750]) strain_rate = np.array([0.0003,0.001,0.01,0.1]) flow_stress1 = np.array([[28.16, 49.46, 95.96], [46.45, 80.51, 126.62], [151.46, 107.94, 235.14], [165.63, 228.77, 319.15]]) Temp = 1000/(273+T) TT = np. linspace(max(Temp), min(Temp),50) S = np.log10(flow_stress1) SR= np.log10(strain_rate) srate= np.linspace(min(SR), max(SR),100) zspline = RectBivariateSpline(SR,Temp,S , kx=2, ky=2) Z2 = zspline(TT,SR) fig = plt.figure() ax = fig.add_subplot(111) x,y = np.meshgrid(Temp,SR) ax.contourf(x,y,Z2) plt.show() I have tried looking but have not found a satisfactory method of solving this problem.
tagged with: python-3.x
type: Question
has comment: http://stackoverflow.com/comment/88779796
tagged with: python
has title: Unable to interpolate on a 2D array on a meshgrid using Rectbivariatespline
score: 0
tagged with: matplotlib
tagged with: scipy

http://stackoverflow.com/comment/97790469
comment on: http://stackoverflow.com/q/50905636
type: Comment
type: QuestionComment
has text: Did you ever solve this?
score: 0

http://stackoverflow.com/comment/88735986
score: 0
has text: @BryanOakley Also Bryan did you have any suggestions on what the issue could be? I know you are quite well versed in tkinter
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50856226

crop
tags question: http://stackoverflow.com/q/50967071
tag name: crop
type: Tag

http://stackoverflow.com/comment/88905240
has text: @johnsharpe Alright, so when we are talking about super, super isnt concerned with the subclasses super class, its concerned with the next class in the MRO? This is my first time trying to implement multiple inheritance vs multi-level inheritance.
comment on: http://stackoverflow.com/q/50953637
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/88804809
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50902504
has text: You didn't ask a question. What kind of help do you need? Stackoverflow isn't a free code-writing service, but we can help if there is some specific part of the problem that you need help with.
type: Comment

http://stackoverflow.com/a/50971704
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50971332
answers question: http://stackoverflow.com/q/50971332
has comment: http://stackoverflow.com/comment/88944879
type: Answer
score: 3
has comment: http://stackoverflow.com/comment/88945955
upvote count: 3
has body: Here's one way using pd.concat with NumPy arrays: res = pd.concat([pd.Series(df[col].values.flatten(), name=col) \ for col in df.columns.unique()], axis=1) print(res) peter brian mike 0 2 3 5.0 1 4 6 7.0 2 4 6 NaN 3 1 5 NaN Note mike is forced to float since it contains NaN values. Explanation df.columns.unique extracts unique column names. df[col].values.flatten extracts the values from all series for a particular name as a NumPy array, and then flattens them into a 1-dimensional array. pd.Series converts the array into a series object. We iterate over all such unique column names via a list comprehension. pd.concat concatenates a list of series into a dataframe.
type: AcceptedAnswer

http://stackoverflow.com/a/50992391
has body: for building in buildings: data1[building].update({ switch_ip: { 'max': MAX, 'total': total }} This would result in a data structure something like: {'Azalea': { '10.16.62.10': { 'max': '10', 'total': '40' }}, { '10.16.62.12': { 'max': '12', 'total': '32' }}}
answers question: http://stackoverflow.com/q/50992241
score: 0
type: Answer

http://stackoverflow.com/q/50916903
tagged with: h.264
accepted answer: http://stackoverflow.com/a/50917584
has comment: http://stackoverflow.com/comment/88834132
tagged with: udp
tagged with: python
has comment: http://stackoverflow.com/comment/88835008
has body: I was able to receive/view UDP h264 packets through VLC command line (i.e. VLC --network-caching 0 --demux h264 udp://...) I am planning on processing those frames through OpenCV algorithms. However, I can't seem to find a way to send the VLC frames over to my Python OpenCV script. Is it possible to pipe VLC stream output to be processed through Numpy in a separate script? I have previously tried directly streaming to OpenCV by using its VideoCapture function, but for some reason, the video stalls and stops at a distorted black image. For now, it seems like incorporating VLC is the only solution (even though I am not totally sure why VLC works over other methods). Thank you. EDIT: The following is a snippet of the error message on the terminal. It seems like there are problems with the first few frames, but I don't know why the stream works on VLC. From the client, I first sent a default key frame data, and then sent video feed h264 data. [h264 @ 0x7f9c50020200] top block unavailable for requested intra mode -1 [h264 @ 0x7f9c50020200] error while decoding MB 7 0, bytestream 7208 [h264 @ 0x7f9c50020200] top block unavailable for requested intra mode -1 [h264 @ 0x7f9c50020200] error while decoding MB 8 9, bytestream 7381
score: 0
has comment: http://stackoverflow.com/comment/88859475
has comment: http://stackoverflow.com/comment/88833930
has answer: http://stackoverflow.com/a/50917584
tagged with: vlc
tagged with: opencv
type: AnsweredQuestion
has title: How to process VLC UDP stream over OpenCV
linked to: http://stackoverflow.com/q/47112642
has comment: http://stackoverflow.com/comment/88836947
type: Question
has comment: http://stackoverflow.com/comment/88836192
answer count: 1

http://stackoverflow.com/q/50913694
tagged with: pandas
tagged with: python
has title: Column name not found, probably because 'Latin-1' character recognized as utf-8
tagged with: iso-8859-1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50913779
type: Question
has body: I am using Python 2.7 on Jupyter Notebook using Pandas library, and I am facing the following issue: I have a dataset which contains characters with accents, to extract the data from the .csv I have written the following code: datafile = pd.read_csv("exportacionEmitidas.csv", delimiter=";", encoding='latin-1', low_memory=False) These are the columns that I get, which look fine to me: Nº Serie + Nº Factura Ejercicio Periodo Fecha Expedición Fecha Operacion NIF Destinatario Nombre o Razón Social Destinatario However, when I try to make a new dataframe with only some of the columns I get the following annoying message: datafile"Nº Serie + Nº Factura","Fecha Expedición" KeyError: "['N\\xc2\\xba Serie + N\\xc2\\xba Factura' 'Fecha Expedici\\xc3\\xb3n'] not in index" I wouldn't like to select the columns by its column index because I would like to avoid to make any mistake in the event that the order of the columns changes.
answer count: 1
accepted answer: http://stackoverflow.com/a/50913779
tagged with: python-2.7
score: 0

http://stackoverflow.com/a/50916495
has comment: http://stackoverflow.com/comment/88834504
score: 0
type: Answer
has body: I'd replace the zeros with np.NaN to remove things you don't care about and stack. Then form the strings you want and groupby.apply(list) import numpy as np df = df.set_index('index') # if 'index' is not your index. stacked = df.replace(0, np.NaN).stack().reset_index() stacked['Positives'] = stacked['level_1'] + '-' + stacked[0].astype(int).astype('str') stacked = stacked.groupby('index').Positives.apply(list).reset_index() stacked is now: index Positives 0 1 [B-1, C-2] 1 2 [C-3] 2 4 [A-1] Or if you just want one string and not a list, change the last line: stacked.groupby('index').Positives.apply(lambda x: ', '.join(list(x))).reset_index() # index Positives #0 1 B-1, C-2 #1 2 C-3 #2 4 A-1
answers question: http://stackoverflow.com/q/50915875
has comment: http://stackoverflow.com/comment/88834670

http://stackoverflow.com/a/50996805
type: Answer
has body: I found a way. First of all, slicing isn't the way. By testing the following: %%timeit -n 2 ws = sparse.csr_matrix((nm, nm), dtype=np.float) for i in xrange(5925,6000): # 75 iterations ws[i,i-l:i], ws[i-l:i, i] = win_largo(i,l) I got 2 loops, best of 3: 2.02 s per loop Whereas, win_largo takes a couple of mili seconds to compute. Since slicing isn't the best way to assign the computed objects, I decided to take an advantage of the elements of the sparse slices returned by win_largo. Therefore, I modified the function so that it returns the set of indices in which it is non zero and its corresponding data set: %%timeit -n 5 row_ind, col_ind, datos = [], [], [] for i in xrange(5500,6000): # 500 iterations indx_w, datos_w = win_largo(i,l) row_ind.extend( np.repeat(i, len(indx_w)).tolist() ) col_ind.extend( np.add(i-l, indx_w).tolist() ) datos.extend( datos_w.tolist() ) What I got, left me speechless: 5 loops, best of 3: 2.02 s per loop Therefore, the whole loop took 3 min and 32 s to complete. WAY less than 6 hours… approximately 0.92% of the original time. That's way a lot. After this, I was able to add some extra data to each list, so that the resulting sparse object would be: ws = sparse.csr_matrix((datos, (row_ind, col_ind)), [nm, nm]) This just took a couple seconds. In total, I was able to get this matrix in 4 minutes :D
answers question: http://stackoverflow.com/q/50993356
accepted answer of: http://stackoverflow.com/q/50993356
type: AcceptedAnswer
score: 0

http://stackoverflow.com/q/50916124
type: AnsweredQuestion
upvote count: 9
tagged with: command-line-arguments
has answer: http://stackoverflow.com/a/50916304
type: Question
accepted answer: http://stackoverflow.com/a/50916304
score: 9
has body: I have a program using argparse. It takes 1 required positional argument, 1 optional positional argument, and 1 flag argument. Something like: usage: test.py [-h] [-a A] b [c] So, I tried using this: parser = argparse.ArgumentParser() parser.add_argument('-a') parser.add_argument('b') parser.add_argument('c', nargs='?', default=None) print(parser.parse_args()) Which works fine for test.py B C -a A and test.py -a A B C. But when I do test.py B -a A C, it throws an error: $ python3 test.py B -a A C usage: test.py [-h] [-a A] b [c] test.py: error: unrecognized arguments: C So, how can I get it to accept the optional positional argument to be accepted even if there is a flag in between? Note that this works if I remove the nargs='?', default=None, but then it's not optional. The problem also happens with nargs='*', but this doesn't happen for nargs=N (e.g. nargs=1, nargs=2) and doesn't happen for nargs='+'. nargs=argparse.REMAINDER makes it parse the flags as part of c (c = ['-a', 'A', 'C'], a = None)
answer count: 1
downvote count: 0
favorite count: 0
tagged with: argparse
tagged with: python
has title: Allow positional command-line arguments with nargs to be seperated by a flag

http://stackoverflow.com/q/50980113
tagged with: sliding-window
possible better answer: http://stackoverflow.com/a/51012919
score: 16
has comment: http://stackoverflow.com/comment/89019458
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/51015756
has comment: http://stackoverflow.com/comment/89018056
has comment: http://stackoverflow.com/comment/89017404
has comment: http://stackoverflow.com/comment/89020796
linked to: http://stackoverflow.com/q/15722324
has title: Evaluate a function in a sliding window with Keras
answer count: 2
has comment: http://stackoverflow.com/comment/89019800
downvote count: 0
tagged with: keras
accepted answer: http://stackoverflow.com/a/51015756
favorite count: 0
has body: I'm trying to extend a matching matching algorithm across a sequence. My matches are 20 units long and have 4 channels at each timepoint. I have built a model that encapsulates the matching, I just can't figure out how to use that in a sliding window to apply it across a longer sequence to find the matches within the sequence. I have 2 (20, 4) input tensors (query and target) that I concatenate, add, flatten, and then apply a simple dense layer. I have data at this stage to train with 100K query, target pairs. def sum_seqs(seqs): return K.sum(seqs, axis=3) def pad_dims(seq): return K.expand_dims(seq, axis=3) def pad_outshape(in_shape): return (in_shape[0], in_shape[1], in_shape[2], 1) query = Input((20, 4)) query_pad = Lambda(pad_dims, output_shape=pad_outshape, name='gpad')(query) target = Input((20,4)) target_pad = Lambda(pad_dims, output_shape=pad_outshape)(target) matching = Concatenate(axis = 3)([query_pad, target_pad]) matching = Lambda(sum_seqs)(matching) matching = Flatten()(matching) matching = Dropout(0.1)(matching) matching = Dense(1, activation = 'sigmoid')(matching) match_model = Model([query, target], matching) This works perfectly. Now I want to use this pre-trained model to search a longer target sequence with varying query sequences. It seems it should be something like: long_target = Input((100, 4)) short_target = Input((20, 4)) choose_query = Input((20, 4)) spec_match = match_model([choose_query, short_target]) mdl = TimeDistributed(spec_match)(long_target) But TimeDistributed takes a Layer not a Tensor. Is there a wrapper I'm missing? Am I going about this the wrong way? Do I need to reformulate this as a convolution problem somehow? Continued experimentation: After a day of beating my head against the keyboard it is clear that both TimeDistributed and backend.rnn only allow you to apply a model/layer to a single time-slice of the data. It doesn't seem like there is a way to do this. It looks like the only thing that can "walk" across multiple sl…
has comment: http://stackoverflow.com/comment/89017311
has comment: http://stackoverflow.com/comment/89016739
tagged with: python
has answer: http://stackoverflow.com/a/51012919
upvote count: 16
has comment: http://stackoverflow.com/comment/89022250
type: AnsweredQuestion
tagged with: conv-neural-network
has comment: http://stackoverflow.com/comment/89018118
linked to: http://stackoverflow.com/q/40731433

http://stackoverflow.com/a/50867192
type: Answer
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/88765105
answers question: http://stackoverflow.com/q/50866804
accepted answer of: http://stackoverflow.com/q/50866804
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88739749
has body: You're only setting up your request context. You need to actually have your app dispatch the request to have anything happen-- similar to your c.get() in your full Client. Give the following a try and I think you'll have better luck: def test_index(): with app.test_request_context('/'): app.dispatch_request() print('&gt;&gt;&gt;&gt;test session:', session) assert_equal(session.get('key'), 'value')

http://stackoverflow.com/q/50895717
has body: Okay so i'm trying to add an indian/nepali font for a gesture recognition system and i'm struggling a bit with the Pillow library. I followed the documentation for pillow and i'm getting an AttributeError. My Code: def put_splitted_text_in_blackboard(blackboard, splitted_text): draw = ImageDraw.Draw(blackboard) for text in splitted_text: fonts = ImageFont.truetype("preeti.TTF", 50) draw.text((10, 25), text, font=fonts) It's giving me this error: Traceback (most recent call last): File "C:\Program Files\Python36\lib\site-packages\PIL\ImageDraw.py", line 289, in Draw return im.getdraw(mode) AttributeError: 'numpy.ndarray' object has no attribute 'getdraw' The blackboard has been defined here: def recognize() blackboard = np.zeros((480, 640, 3), dtype=np.uint8) splitted_text = split_sentence(text, 2) put_splitted_text_in_blackboard(blackboard, splitted_text) cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2) res = np.hstack((img, blackboard)) cv2.imshow("Recognizing gesture", res) cv2.imshow("thresh", thresh) if cv2.waitKey(1) == ord('q'): break Anyone know where it went wrong?
has comment: http://stackoverflow.com/comment/88791843
has comment: http://stackoverflow.com/comment/88791873
tagged with: opencv
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50896089
type: Question
upvote count: 4
has title: AttributeError: 'numpy.ndarray' object has no attribute 'getdraw'
accepted answer: http://stackoverflow.com/a/50896089
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/88791778
score: 4
has comment: http://stackoverflow.com/comment/88791905
has comment: http://stackoverflow.com/comment/88791703
tagged with: python
favorite count: 0

http://stackoverflow.com/comment/88859150
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50929964
has text: It's a syntax error, you're just missing a comma after `'Value'`
type: Comment

http://stackoverflow.com/q/50965020
accepted answer: http://stackoverflow.com/a/51167942
tagged with: file-not-found
tagged with: setuptools
has title: FileNotFoundError after python setup.py install (not after develop!)
linked to: http://stackoverflow.com/q/7522250
has answer: http://stackoverflow.com/a/51167942
answer count: 1
has comment: http://stackoverflow.com/comment/88939276
score: 0
has body: I have a python project with the following structure: src/ main.py example.txt setup.py After installation, I should be able to call myprogramm -name bla and it should create a new folder bla and copy example.txt inside. When installing the program with python setup.py develop (inside a virtualenv) everything works fine and as expected. However, when using python setup.py install, I get a FileNotFoundError when executing the command as Python cannot find example.txt. Why doesn't it copy example.txt to the correct location when installing with python setup.py install? How can I fix the problem? Do I need to include example.txt explicitly in my setup.py somehow?
tagged with: python
tagged with: installation
has comment: http://stackoverflow.com/comment/88926375
type: Question
type: AnsweredQuestion

http://stackoverflow.com/a/50996102
score: 19
has body: From docs: Avoid catching exceptions inside atomic! Since the function had multiple nested try and excepts, I inserted another transaction.atomic() within a the try and except closest to where the error is occurring. Per docs, have nested try and excepts could complicate the initial atomic. I found that placing the atomic (for a second time) helps. Hope this helps others facing a similar situation. try: item_to_group_keys = [] promo_key = 'promo:' + str(request.user.id) with connection.cursor() as cursor: with transaction.atomic(): // more code here... try: with transaction.atomic(): // **added second atomic** //more code except: pass except IntegrityError:
type: AcceptedAnswer
upvote count: 19
accepted answer of: http://stackoverflow.com/q/50866370
type: Answer
answers question: http://stackoverflow.com/q/50866370
downvote count: 0

http://stackoverflow.com/comment/88778061
type: QuestionComment
has text: after reviewing replies below it seems (1) is the most pandiac and (3) is the most performant
score: 0
comment on: http://stackoverflow.com/q/50883050
type: Comment

http://stackoverflow.com/q/50975669
has body: I am trying to clean a very large data frame in Pandas. I have columns labeled currentAge, currentAge2, sex, sex2, height, height2, weight, weight2. For some rows there is a value for currentAge and for other rows there is NaN for currentAge2. It can also go the other way where for some rows there is a value for currentAge2 and NaN for currentAge. This is true for the other metrics sex, weight, and height. I want to merge the common metrics together like currentAge and currentAge2 so that there is one column currentAge with no NaNs. How would I go about doing this?
has title: Merge columns with NaN
type: AnsweredQuestion
type: Question
score: 0
tagged with: pandas
answer count: 1
has answer: http://stackoverflow.com/a/50975952
accepted answer: http://stackoverflow.com/a/50975952
tagged with: python

sql-server
tags question: http://stackoverflow.com/q/50895398
tags question: http://stackoverflow.com/q/50882613
tags question: http://stackoverflow.com/q/50972596
type: Tag
tags question: http://stackoverflow.com/q/50940145
tags question: http://stackoverflow.com/q/50998868
tag name: sql-server
tags question: http://stackoverflow.com/q/50862705

http://stackoverflow.com/comment/88824723
has text: The .csv could solve all my problems, because I could read it in a text editor and update what I need from different scripts. Does it support dictionary, or should I use another way to store info? I have yet to work with .csv
type: QuestionComment
comment on: http://stackoverflow.com/q/50911961
score: 0
type: Comment

http://stackoverflow.com/comment/88831267
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50915609
score: 0
has text: Could you include the full traceback in the question?

http://stackoverflow.com/comment/88993417
has text: `[] == list()` might give you the impression that `list()` is like e.g. `array()` in PHP – just an alternate syntax – but that’s not the case. It’s a type that gives an empty list when called with no arguments, converts an iterable to a list when called with one argument, and can’t be called with more than one argument. `[x]` is not equivalent to `list(x)`, and `list(x, y, …)` makes no sense.
type: Comment
comment on: http://stackoverflow.com/q/50999726
type: QuestionComment
score: 3

http://stackoverflow.com/comment/135333780
score: 1
comment on: http://stackoverflow.com/a/54549488
type: AnswerComment
type: Comment
has text: python3-yaml is a deep dependency on a number of platforms - do this with caution.

http://stackoverflow.com/q/50978134
downvote count: 0
type: UnansweredQuestion
has body: I want to implement Q-learning in the Bipedal Walker v2 of OpenAI but after looking for tutorials, they seem to always be finite environment which make the Q matrix and reward matrix simple to initialize. e.g: http://mnemstudio.org/path-finding-q-learning-tutorial.htm my only question is, what should be the dimensions of those matrix in a more open-like environment such as the one I want to use? Environment in question: https://gym.openai.com/envs/BipedalWalker-v2/ Observation you get (note that there is some value which can be infinite): https://github.com/openai/gym/wiki/BipedalWalker-v2
tagged with: reinforcement-learning
tagged with: deep-learning
has title: what should the Q matrix dimensions be in an open-like environment for Q-learning
favorite count: 0
has answer: http://stackoverflow.com/a/50984201
type: Question
upvote count: 2
answer count: 2
tagged with: python
has answer: http://stackoverflow.com/a/50993029
tagged with: openai-gym
tagged with: q-learning
score: 2

http://stackoverflow.com/q/50991629
has body: I need to configure several pieces of software to access various executables that might change with conda environments. I know that this is broad so lets stick to jupyter lab, I want to add an item to Windows' context menu. I have all of keys in my registy setup except for Default of command and this entry needs to path to jupyter lab. As I understand all anaconda's executables will be found in Users\my.name\AppData\Local\Continuum\anaconda3 This is the part where I'm lost directory above contains "Scripts" and "env" after examining each it looks to me like "Scripts" contains executables for base(root) environment and env contains files specific to each environment. Is there another directory that I missed, that contains files/links to currently activated environment? Maybe my approach is to0 direct so is there a programmatic way to figure out where is the executable I'm looking for? I should point out that I'm working on Win 10 machine.
favorite count: 0
upvote count: 1
tagged with: windows
answer count: 0
has title: How to setup path to jupyter lab of activated environment
type: UnansweredQuestion
tagged with: python
tagged with: anaconda
downvote count: 0
score: 1
type: Question

http://stackoverflow.com/comment/88788050
type: Comment
has text: as long as they are independent, you no need locks. synchronization(locks) only comes into picture, when two threads access to a shared variable.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50893889

http://stackoverflow.com/comment/88814302
has text: Yes, use a gif and make it the first (and only) parameter.
comment on: http://stackoverflow.com/q/50907095
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88926845
comment on: http://stackoverflow.com/q/50962903
has text: Thanks, `{% autoescape off %}{% quote %}{% endautoescape %}` solved my problem!
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/88980232
has text: It looks like you want us to write some code for you. While many users are willing to produce code for a coder in distress, they usually only help when the poster has already tried to solve the problem on his own. A good way to show this effort is to include a [Minimal, complete, verifiable example](http://stackoverflow.com/help/mcve). Check the [intro tour](https://stackoverflow.com/tour) you were *supposed* to finish before posting, especially [How to Ask](http://stackoverflow.com/help/how-to-ask).
comment on: http://stackoverflow.com/q/50992584
score: 1
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/88862965
type: QuestionComment
has text: @NilsWerner I have updated, why I need it.
comment on: http://stackoverflow.com/q/50930770
score: 0
type: Comment

http://stackoverflow.com/a/50878681
has body: As you didn't specify which part of the matched string you want to check, so I included some more groups. import re s = 'hello there estabilidade this is just some text (yes it is)' r = re.search(r"(estabilidade([.\S]+))\(", s) print(r.group(1)) # "estabilidade this is just some text" print(r.group(2)) # " this is just some text"
score: 0
answers question: http://stackoverflow.com/q/50878549
type: Answer
has comment: http://stackoverflow.com/comment/88759674

http://stackoverflow.com/q/50920241
has comment: http://stackoverflow.com/comment/91432481
type: UnansweredQuestion
has body: A simple Python 3.6 script using aiohttp and python-socketio and running on Windows 10 outputs the following when started: ======== Running on http://0.0.0.0:8080 ======== (Press CTRL+C to quit) However, pressing CTRL+C does not terminate the script! I had to open Task Manager and kill each of the Python processes until killing one of them releases the aiohttp script back to the command prompt. Any one experienced the same problem? from aiohttp import web import socketio sio = socketio.AsyncServer() app = web.Application() sio.attach(app) @sio.on('connect') def connect(sid, environ): print(sid) if __name__ == '__main__': web.run_app(app)
tagged with: socket.io
has title: CTRL+C does not terminate aiohttp app in Python 3.6 script on Windows
linked to: http://stackoverflow.com/q/24774980
score: 4
type: Question
downvote count: 0
favorite count: 0
tagged with: python-3.x
tagged with: python-asyncio
tagged with: python
upvote count: 4
tagged with: aiohttp
answer count: 0

http://stackoverflow.com/a/50946216
score: 0
has comment: http://stackoverflow.com/comment/88890031
type: Answer
answers question: http://stackoverflow.com/q/50946084
has comment: http://stackoverflow.com/comment/88890164
has body: To make sure whether the element is being located try this: new_button_list = driver.find_elements_by_xpath('//a[@id="button-new"]') this will return a list because of using 'elements': then check the length of the list, one good thing is it wont through an exception and also let you know whether the element is located.
has comment: http://stackoverflow.com/comment/88889887

http://stackoverflow.com/q/50892218
has body: This is where I am at, but I'm not sure where to go from here: import imaplib import email conn = imaplib.IMAP4() conn.login("username", "password") status, messages = conn.select('INBOX') if status != "OK": print ("Incorrect mail box") exit() print (messages)
score: 0
tagged with: email
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: imaplib
upvote count: 1
downvote count: 1
has title: I want to grab all emails from an inbox using the Python IMAPLIB module... how can I do this?
type: Question
has answer: http://stackoverflow.com/a/50892520
has comment: http://stackoverflow.com/comment/88785610

http://stackoverflow.com/comment/88964468
comment on: http://stackoverflow.com/q/50982008
score: 0
type: Comment
type: QuestionComment
has text: @irene It was the spaces in front of the text

http://stackoverflow.com/q/50909935
has body: I'm having the DataFrame that looks like this: enter image description here I need to convert it to the structure that looks like this: {1234: [[(1504010302, 45678), (1504016546, 78908)], [(1506691286,23208)]], 4576: [[(1529577322, 789323)], [(1532173522, 1094738), (1532190922, 565980)]]} So basically, I need to use the first-level index ('userID') as the key of the list of all sessions of a particular user and form distinct lists of particular sessions with page views as tuples based on the second-level index ('session_index'). I was trying to implement this solution: Convert dataframe to dictionary of list of tuples. But I couldn't figure out how to modify it to get the structure I need. from datetime import datetime # I'm creating the sample of different sessions iterator = iter([{'user': 1234, 'timestamp': 1504010302, 'pageid': 45678}, {'user': 1234, 'timestamp': 1504016546, 'pageid':78908}, {'user': 1234, 'timestamp': 1506691286, 'pageid':23208} , {'user': 4567, 'timestamp': 1529577322, 'pageid': 789323}, {'user': 4567, 'timestamp': 1532173522, 'pageid': 1094738}, {'user': 4567, 'timestamp': 1532190922, 'pageid': 565980}]) # Then I'm creating an empty DataFrame df = pd.DataFrame(columns=['userID', 'session_index', 'timestamp', 'pageid']) # Then I'm filling the empty DataFrame based on the logic that I need to get in the final structure for entry in iterator: if not (df.userID == entry['user']).any(): df = df.append([{'userID': entry['user'], 'session_index': 1, 'timestamp': entry['timestamp'], 'pageid': entry['pageid']}], ignore_index=True) else: session_numbers = df[(df.userID == entry['user']) &amp; (df.timestamp.apply(lambda x: abs(datetime.fromtimestamp(x) - datetime.fromtimestamp(entry['timestamp'])).days*24 + abs(datetime.fromtimestamp(x) - datetime.fromtimestamp(entry['timestamp'])).seconds // 3600 ) &lt;= 24)] if len(session_numbers.session_index.values) == 0: df = df.append([{'userID': entry['user'], 'session_index': df.session_index[df.userID == entry…
tagged with: pandas
upvote count: 1
downvote count: 0
answer count: 1
linked to: http://stackoverflow.com/q/45882917
favorite count: 0
has comment: http://stackoverflow.com/comment/88822140
type: UnansweredQuestion
tagged with: python
score: 1
has title: How to convert multi indexed dataframe into a complex structure?
type: Question
has answer: http://stackoverflow.com/a/50911382
has comment: http://stackoverflow.com/comment/88821917

http://stackoverflow.com/comment/88892194
score: 0
type: AnswerComment
has text: Thank for your comment !
comment on: http://stackoverflow.com/a/50945721
type: Comment

http://stackoverflow.com/comment/88762695
type: QuestionComment
has text: that other check win shouldnt be capitalized but it still doesnt work
comment on: http://stackoverflow.com/q/50880120
score: 0
type: Comment

scipy
tags question: http://stackoverflow.com/q/50932067
tags question: http://stackoverflow.com/q/50898924
tags question: http://stackoverflow.com/q/51003769
tags question: http://stackoverflow.com/q/50994300
tags question: http://stackoverflow.com/q/50934578
tags question: http://stackoverflow.com/q/50964427
tags question: http://stackoverflow.com/q/50913856
tags question: http://stackoverflow.com/q/50879749
tags question: http://stackoverflow.com/q/50945375
tags question: http://stackoverflow.com/q/50881318
type: Tag
tags question: http://stackoverflow.com/q/50857909
tags question: http://stackoverflow.com/q/50974693
tags question: http://stackoverflow.com/q/50855794
tags question: http://stackoverflow.com/q/50954503
tag name: scipy
tags question: http://stackoverflow.com/q/50860512
tags question: http://stackoverflow.com/q/50866114
tags question: http://stackoverflow.com/q/50930049
tags question: http://stackoverflow.com/q/50859654
tags question: http://stackoverflow.com/q/51002508
tags question: http://stackoverflow.com/q/50928802
tags question: http://stackoverflow.com/q/50907049
tags question: http://stackoverflow.com/q/50975349
tags question: http://stackoverflow.com/q/50890596
tags question: http://stackoverflow.com/q/50975621
tags question: http://stackoverflow.com/q/50864884
tags question: http://stackoverflow.com/q/50932433
tags question: http://stackoverflow.com/q/50877762
tags question: http://stackoverflow.com/q/50975833
tags question: http://stackoverflow.com/q/50974217
tags question: http://stackoverflow.com/q/50929729
tags question: http://stackoverflow.com/q/50941165
tags question: http://stackoverflow.com/q/50888068
tags question: http://stackoverflow.com/q/50884533
tags question: http://stackoverflow.com/q/51002825
tags question: http://stackoverflow.com/q/50978828
tags question: http://stackoverflow.com/q/50892250
tags question: http://stackoverflow.com/q/50930468
tags question: http://stackoverflow.com/q/50889231
tags question: http://stackoverflow.com/q/50861243

http://stackoverflow.com/q/50906210
answer count: 1
downvote count: 0
tagged with: scikit-learn
favorite count: 0
score: 13
tagged with: tfidfvectorizer
has body: I wanted to learn more about NLP. I came across this piece of code. But I was confused about the outcome of TfidfVectorizer.fit_transform when the result is printed. I am familiar with what tfidf is but I could not understand what the numbers mean. import tensorflow as tf import numpy as np from sklearn.feature_extraction.text import TfidfVectorizer import os import io import string import requests import csv import nltk from zipfile import ZipFile sess = tf.Session() batch_size = 100 max_features = 1000 save_file_name = os.path.join('smsspamcollection', 'SMSSpamCollection.csv') if os.path.isfile(save_file_name): text_data = [] with open(save_file_name, 'r') as temp_output_file: reader = csv.reader(temp_output_file) for row in reader: text_data.append(row) else: zip_url = 'http://archive.ics.uci.edu/ml/machine-learning-databases/00228/smsspamcollection.zip' r = requests.get(zip_url) z = ZipFile(io.BytesIO(r.content)) file = z.read('SMSSpamCollection') # Format data text_data = file.decode() text_data = text_data.encode('ascii', errors='ignore') text_data = text_data.decode().split('\n') text_data = [x.split('\t') for x in text_data if len(x) &gt;= 1] # And write to csv with open(save_file_name, 'w') as temp_output_file: writer = csv.writer(temp_output_file) writer.writerows(text_data) texts = [x[1] for x in text_data] target = [x[0] for x in text_data] target = [1 if x == 'spam' else 0 for x in target] # Normalize the text texts = [x.lower() for x in texts] # lower texts = [''.join(c for c in x if c not in string.punctuation) for x in texts] # remove punctuation texts = [''.join(c for c in x if c not in '0123456789') for x in texts] # remove numbers texts = [' '.join(x.split()) for x in texts] # trim extra whitespace def tokenizer(text): words = nltk.word_tokenize(text) return words tfidf = TfidfVectorizer(tokenizer=tokenizer, stop_words='english', max_features=max_features) sparse_tfidf_texts = tfidf.fit_transform(texts) print(sparse_tfidf_texts) And the output is:…
tagged with: python
tagged with: nlp
upvote count: 13
tagged with: tf-idf
has answer: http://stackoverflow.com/a/50906599
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50906599
type: Question
has title: Confused with the return result of TfidfVectorizer.fit_transform

http://stackoverflow.com/comment/88870772
comment on: http://stackoverflow.com/a/50935699
has text: Yes, my fault for not making that more clear. Still a noob on stack! :)
score: 0
type: AnswerComment
type: Comment

ironpython
tags question: http://stackoverflow.com/q/50981983
tags question: http://stackoverflow.com/q/51008695
tag name: ironpython
type: Tag
tags question: http://stackoverflow.com/q/50919908
tags question: http://stackoverflow.com/q/51006818

http://stackoverflow.com/comment/88729671
type: AnswerComment
comment on: http://stackoverflow.com/a/50863467
score: 0
type: Comment
has text: I do not think using a loop here would be a bad idea as you have to sort your dataframe accordingly. @SrinidhiPatil

http://stackoverflow.com/a/50877889
has comment: http://stackoverflow.com/comment/88758007
upvote count: 1
has comment: http://stackoverflow.com/comment/88758318
has comment: http://stackoverflow.com/comment/88758119
score: 1
has comment: http://stackoverflow.com/comment/88758336
type: AcceptedAnswer
downvote count: 0
has body: To use globals, you need to declare them within the function. For example: variable = 0 def function(): global variable variable += 1 function() This code increments the global variable. However, this function does not: variable = 0 def function(input): global variable input += 1 function(variable) The local variable is a copy of the global
has comment: http://stackoverflow.com/comment/88758166
type: Answer
accepted answer of: http://stackoverflow.com/q/50877762
answers question: http://stackoverflow.com/q/50877762

http://stackoverflow.com/comment/88989102
has text: What exactly you're asking in #4? Single number repetition? This would be at best something like 2^32 - 2^25 for floats, or 2^64-2^52 for doubles. Sequence repetition? Something like 2^19337-1
score: 0
comment on: http://stackoverflow.com/q/50983331
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50925513
tagged with: django-related-manager
type: Question
has body: Having these kind of model definitions and a relationship between the two: class Car(models.Model): description = models.CharField(max_length=35) def save(self, **kwargs): invalidate_cache() super().save(**kwargs) def delete(self, **kwargs): invalidate_cache() return super().delete(**kwargs) class Passenger(models.Model): car = models.ForeignKey(Car, related_name='passengers') I have defined custom save and delete on the Car model because when a car instance is modified I have to perform some extra operations, in particular I need to invalidate a cache. My doubt is: creating/updating/deleting a related model would call these custom methods? I'll try to be more clear: c1 = Car(description='super fast car') p = Passenger(car=c1) Clearly the creation of the c1 calls the Car.save but would the creation of the instance p of Passenger call the Car.save or not? From my tests it seems so but I want to be more sure it wasn't just a specific case and this happens all the time in the Django model handling cycle (I could not find a specific documentation on this).
has comment: http://stackoverflow.com/comment/88850486
has title: Model Creation calls its related model save method?
score: 0
has comment: http://stackoverflow.com/comment/88850217
has comment: http://stackoverflow.com/comment/88850461
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/88850199
answer count: 0
tagged with: django-models

http://stackoverflow.com/comment/88776476
type: Comment
comment on: http://stackoverflow.com/q/50886095
type: QuestionComment
has text: This is a bad question because you're not asking a specific question. That said, the above comments are bad comments because rather than point this out, they say rtfm. Which there isn't really one because python mechanize is a terrible abandoned project. I guess what I'm trying to say is: Use requests or find another language to do this in.
score: 0

http://stackoverflow.com/a/50918809
downvote count: 0
answers question: http://stackoverflow.com/q/50918660
type: Answer
has body: First, you are not using Python 3.x; you are using 2.7 - your results can be reproduced only in 2.7, but not in 3.x. Second, you have integer division in the line weighted_score = int((score_earned / 100) * weight_1) In Python 2.7, if you divide a smaller int number by a larger int number, you always get a 0. Your line must be: weighted_score = int((score_earned / 100.0) * weight_1) # Mind the .0
score: 1
upvote count: 1

http://stackoverflow.com/q/50959785
tagged with: scikit-learn
tagged with: decision-tree
score: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/50961693
linked to: http://stackoverflow.com/q/20224526
has title: Get split points from DecisionTreeClassifier for single numeric variable
type: Question
type: AnsweredQuestion
has body: I am trying to get splits from decision tree created based on a single variable. Is the following the correct and safe way how to get the splits? from sklearn.tree import DecisionTreeClassifier import numpy as np x = np.array([1,2,3,4,5,6,7]) y = np.array([1,0,0,1,1,0,1]) x = x.reshape(7, -1) clf = DecisionTreeClassifier() clf.fit(x, y) # My splits np.sort(clf.tree_.threshold[clf.tree_.feature == 0]) I see only 0 and -2 in clf.tree_.fature and my understanding is that -2 represents TREE_UNDEFINED (see here) while the other points will be leafs with some defined threshold.
has answer: http://stackoverflow.com/a/50961693
answer count: 1

http://stackoverflow.com/comment/88950392
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50977130
has text: Try yielding `dict.copy()` and you'll see the difference
score: 0

http://stackoverflow.com/comment/90001136
has text: thanks for you time.Processor Intel(R) Core(TM) i5-8250U CPU @ 1.60GHz, 1800 Mhz, 4 Core(s), 8 Logical Processor(s)/4gDDR4 memory/i run the main above question and your solution for every 50 chunks without any pain!i try to do what you whant now for 1:1400000 i will report as soon as possible
comment on: http://stackoverflow.com/a/51000045
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50867343
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50867576
tagged with: pip
accepted answer: http://stackoverflow.com/a/50867576
type: Question
has body: So I recently downloaded python3 and django-2 but I realised my computer has already python 2 and django 1.11, so I managed to create project with django 3 using python3 django -m startproject or something like this, even I managed to create a django 2 project, this time at the urls.py, it says "No name 'path' in module 'django.urls'. Can you help me with how to create a project using django2 and python3 in lubuntu and this error.
score: 0
has title: No name 'path' issue, unable to start project in django, lubuntu
answer count: 1
tagged with: path
tagged with: django

http://stackoverflow.com/a/50892134
has comment: http://stackoverflow.com/comment/88784880
type: Answer
score: 1
upvote count: 1
has body: If you extend your model with a method to find the correct sub-object: class MenuItem(models.Model): def custom_url(self): return self.menuitemcustomurl_set.first() # assume the first one is correct ... then you can use this method in you template directly {{ menu_item.custom_url }}
answers question: http://stackoverflow.com/q/50891833
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50891833
downvote count: 0

http://stackoverflow.com/q/50902490
answer count: 0
upvote count: 3
type: UnansweredQuestion
has body: I'm looking to connect my DSLR (Canon T3i) - and generally any DSLR - for use with opencv-python. I'd ideally like to be able to do it via Windows or Linux. I've seen libgphoto2 mentioned (on the linux side) but have not found a general enough post on and forums to explain how to get opencv to recognize a connected DSLR via the "cv2.VideoCapture(camera_id)" Does anyone know how this is accomplished?
downvote count: 1
type: Question
tagged with: opencv
has title: How to set up DSLR (Canon T3i) to work with opencv-python
tagged with: camera
favorite count: 0
tagged with: python
score: 2

http://stackoverflow.com/comment/128870392
type: Comment
score: 0
type: AnswerComment
has text: Hi @Chris The other answer is missing some information that I consider is important. The GDAL installation is not included and it does not say which version you should include to install, that´s why I decided to join all.
comment on: http://stackoverflow.com/a/72936761

http://stackoverflow.com/q/50879774
has comment: http://stackoverflow.com/comment/88761919
downvote count: 0
answer count: 1
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88761802
has answer: http://stackoverflow.com/a/50879891
tagged with: python
has title: Best Way to Design this Locus Class
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88761915
has comment: http://stackoverflow.com/comment/88761648
has comment: http://stackoverflow.com/comment/88761959
upvote count: 1
has body: Context: Hello to anyone who looks at this question. I am a beginning python coder (2 weeks going strong!) and I believe I initially designed my classes poorly and am asking for help on a good way to re-design the fundamental one (in Locus.py). Background: The project has 4 classes so far which can be found here (https://github.com/asriley/HalfSiblings). The very base class Locus has a tuple to represent an allele of genetic data (a,b). The next class, Individual has a list of alleles: [(a,b),(c,d),(a,e),(f,d)]. In general though, we have n individuals and l loci for each individual. Sample Data: 7 individuals(rows) with 3 loci (cols) 1,1 5,3 4,3 1,2 4,7 3,7 2,3 3,6 5,4 2,4 7,4 4,9 3,6 8,9 3,0 6,5 4,8 0,0 7,7 7,7 7,9 I am trying to figure out how to design this class to incorporate it in other classes (Especially Individual) because eventually I have to use networkx to build graphs on the data. A full snippet of the Locus class and the current error is given: class Locus: # constructor def __init__(self): self.alleles = () def get_alleles(self): return self._alleles def set_alleles (self,x, y): if x and y: self._alleles = (x,y) alleles = property (get_alleles, set_alleles) l1 = Locus() l1.set_alleles(1,2) l1.set_alleles(2,3) print (l1.get_alleles()) Traceback (most recent call last): File "Locus.py", line 13, in &lt;module&gt; l1 = Locus() File "Locus.py", line 4, in __init__ self.alleles = () TypeError: set_alleles() missing 1 required positional argument: 'y' Can anyone assist with how I should properly handle this class? File parsing is done in one of the other classes from the github link. So thats not an issue here. Eventually, I want to send a 2D list of Individuals (containing the genetic Locus info) to the other classes.
type: Question
tagged with: oop
has comment: http://stackoverflow.com/comment/88761938
accepted answer: http://stackoverflow.com/a/50879891
has comment: http://stackoverflow.com/comment/88761845

http://stackoverflow.com/comment/89015316
type: AnswerComment
has text: @j.stalin - DO you think `mask = df.a.str.contains("AAA|DDD|KKK")` ?
comment on: http://stackoverflow.com/a/51011202
type: Comment
score: 0

http://stackoverflow.com/comment/88863472
comment on: http://stackoverflow.com/a/50931771
score: 0
type: AnswerComment
has text: Just did. I think yes, when merging the order, the NaN should be dropped.
type: Comment

http://stackoverflow.com/q/50992976
tagged with: python
upvote count: 1
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52907189
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/88981998
favorite count: 0
has title: Trying to use setProperty to an Entry in python with appJar module
has body: I'm using appJar to create a gui to my py bot. I'm trying to create readonly Entrys so... i've tried this: app.addEntry("ANI") app.setProperty("ANI",prop=readonly ,value=True) but it's not working... I need some help with this. Thank you all.
type: UnansweredQuestion

http://stackoverflow.com/a/50859696
accepted answer of: http://stackoverflow.com/q/50859683
answers question: http://stackoverflow.com/q/50859683
score: 3
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: IIUC, Using mask df_result.mask(df_criteria==1,0) Out[55]: x y A 0 20 B 30 0 C 10 10
upvote count: 3
has comment: http://stackoverflow.com/comment/88722922
has comment: http://stackoverflow.com/comment/88722583

http://stackoverflow.com/q/50973384
score: 0
tagged with: django-admin
has body: I added a field to my database model that was completely unrelated, when I started getting this issue Environment: Request Method: GET Request URL: http://127.0.0.1:8000/admin/backend/network/add/ Django Version: 2.0.6 Python Version: 3.6.5 Installed Applications: ['backend.apps.BackendConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template C:\Users\woode\Documents\RIoT Suite\riot-portal\env\lib\site-packages\django\contrib\admin\templates\admin\includes\fieldset.html, error at line 19 'str' object has no attribute 'utcoffset' 9 : {% for field in line %} 10 : &lt;div{% if not line.fields|length_is:'1' %} class="field-box{% if field.field.name %} field-{{ field.field.name }}{% endif %}{% if not field.is_readonly and field.errors %} errors{% endif %}{% if field.field.is_hidden %} hidden{% endif %}"{% elif field.is_checkbox %} class="checkbox-row"{% endif %}&gt; 11 : {% if not line.fields|length_is:'1' and not field.is_readonly %}{{ field.errors }}{% endif %} 12 : {% if field.is_checkbox %} 13 : {{ field.field }}{{ field.label_tag }} 14 : {% else %} 15 : {{ field.label_tag }} 16 : {% if field.is_readonly %} 17 : &lt;div class="readonly"&gt;{{ field.contents }}&lt;/div&gt; 18 : {% else %} 19 : {{ field.field }} 20 : {% endif %} 21 : {% endif %} 22 : {% if field.field.help_text %} 23 : &lt;div class="help"&gt;&lt;/div&gt; 24 : {% endif %} 25 : &lt;/div&gt; 26 : {% endfor %} 27 : &lt;/div&gt; 28 : {% endfor %} 29 : &…
answer count: 1
has comment: http://stackoverflow.com/comment/88944455
tagged with: python
has answer: http://stackoverflow.com/a/50975380
has comment: http://stackoverflow.com/comment/88945537
has comment: http://stackoverflow.com/comment/88945469
has title: Unable to view the add screen in Django's Admin panel
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88945234
tagged with: django
has comment: http://stackoverflow.com/comment/88945542
has comment: http://stackoverflow.com/comment/88945901
type: Question

http://stackoverflow.com/comment/88759346
type: QuestionComment
type: Comment
score: 1
has text: @MOROZILnic I think you've misinterpreted what OP wants: they're looking for something like (in C): `void increase(int* a) { (*a)++; } increase(&i);`
comment on: http://stackoverflow.com/q/50878530

http://stackoverflow.com/a/50942504
type: Answer
score: 1
upvote count: 1
has body: You could try this: import re def my_input(): my_string = input("Important ions are: ").split() # storing the input as elements of a list w = " ".join(my_string) # joining all the elements in the list print("Important ions are: ", re.sub(" ",", ",w[0:-2]) +'and '+ my_string[-1]) # appending the last element after inserting ', ' and 'and' my_input() This should give you the output exactly the way you wanted. The reason why your code prints the input repeatedly is because of this line: print(my_string, sep=",") It just prints the whole input as many times as there elements in the input. Also, sep= "," won't work in loops.
downvote count: 0
answers question: http://stackoverflow.com/q/50940985

http://stackoverflow.com/a/50863000
answers question: http://stackoverflow.com/q/50862660
accepted answer of: http://stackoverflow.com/q/50862660
has body: Your problem is the use of the index() method. When you write row.index(column), it returns you the index for the first column it finds that is equal to the one you gave it. So the problem arises by the fact that you have rows that are equivalent (first and seconds rows for examples, [0, 0, 1] and [0, 0, 1]. I suggest you use the enumerate() built-in function to retrieve the indices. for row_index, row in enumerate(board): for column_index, column in enumerate(row): if column != 0: if column not in ships: ships[column] = column_index, row_index, 0 else: ships[column].append([column_index, row_index, 0]) Output for board = [ [0, 0, 1], [0, 0, 1], [0, 2, 0], [0, 2, 0], ] {1: [[2, 0, 0], [2, 1, 0]], 2: [[1, 2, 0], [1, 3, 0]]}. Just a reminder that the indices start from 0.
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/88731885

http://stackoverflow.com/q/50911726
type: Question
has answer: http://stackoverflow.com/a/50993760
has comment: http://stackoverflow.com/comment/88950240
has comment: http://stackoverflow.com/comment/88830026
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/88846471
favorite count: 0
type: UnansweredQuestion
has body: I am using snakemake in a machine-learning context. I have two rules (process_x_only, and process_x_and_y) that have processed_x.txt as target output, and are thus ambiguous. See following code: rule process_x_only: input: 'x.txt', output: 'processed_x.txt' rule process_x_and_y: input: 'x.txt', 'y.txt' output: 'processed_x.txt', 'processed_y.txt' ruleorder: process_x_only &gt; process_x_and_y rule refit_model: input: 'processed_x.txt', 'processed_y.txt' output: 'predictions_refit.txt' rule predict_model: input: 'processed_x.txt' output: 'predictions.txt' Following snakemake's documentation, I use a ruleorder statement to specify that preferably only x should be processed ( I.e. only when y needs to be processed process_x_and_y should be run, otherwise it is sufficient to just process x and process_x_only can be run.). This resolves the ambiguity problem, but introduces another problem. When I execute: snakemake predictions_refit.txt snakemake will first execute process_x_only, and then process_x_and_y, whereas in this case I only want process_x_and_y to be executed. How do I make snakemake build a DAG where only process_x_and_y is executed? To clarify: This is a big simplification of my actual problem. I am aware that changing the restrictions of my problem statement will solve the problem, but I am interested in how to solve that snakemake is executing both rules in the ruleorder. To add: While executing rule refit model the following warning is displayed: Warning: the following output files of rule process_x_only were not present when the DAG was created: {'processed_x.txt'}
tagged with: python
has comment: http://stackoverflow.com/comment/88968743
score: 1
has title: Snakemake: How to prevent ambiguous rules from being executed both?
tagged with: snakemake
upvote count: 1

http://stackoverflow.com/comment/88894692
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50948490
has text: Are you allowing *any* character position to be a mis-match? Your examples all have the mis-matches at the ends of the strings.
type: Comment

http://stackoverflow.com/q/50988340
has comment: http://stackoverflow.com/comment/88974452
tagged with: python-3.x
tagged with: tkinter
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88977672
tagged with: openpyxl
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88977223
has comment: http://stackoverflow.com/comment/88975229
tagged with: optimization
has comment: http://stackoverflow.com/comment/88976692
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/88976372
score: 1
favorite count: 0
has title: Optimal way to use tkinter and openpyxl to iterate through a spreadsheet?
has body: I'm a complete Python beginner, trying to make a GUI which allows the user to select an Excel file, from which some data will be extracted and analyzed. For the GUI I am using tkinter, and for the Excel operations I am using openpyxl. The code that I currently have works, but when the Excel file selected is large, the runtime is stupidly long (a 10,000 row x 20 column spreadsheet took about an hour to iterate through, and just got slower as time went by). Also, the GUI stops responding for the duration of the iteration. I had previously made the program practically identically using MATLAB, and it worked beautifully, with the whole iteration process taking only one or two seconds, so something is definitely funky here. Now I know this is a problem with me and not Python, so I was hoping you guys could help point me in the right direction of how to fix it. Here are some simplified examples of what I'm working with to help illustrate my situation. I need to go through each row of the spreadsheet, check a certain value in that row to see if it matches what I want, and if it does, I store some data from that row. wb = openpyxl.load_workbook(filename = 'some_garbage.xlsx', read_only=True).worksheets[0] all_data = wb.cell desiredColor = 'Purple' foodStorage = [] for row in range(2, wb.max_row + 1): print(row) if(all_data(row, 1).value == desiredColor): foodStorage.append(all_data(row,2)) print('I found purple! Yee') Should I be using a module other than openpyxl for this task, or am I just making some mistake that keeps openpyxl from performing at its full potential? Should I be using threading, either to speed up the iteration process, or to ensure that my GUI window doesn't go all "Not Responding" on me while the iteration is doing its thing? I tried to search for questions regarding similar issues, but I wasn't really able to find quite what I was looking for, most likely due to my lack of ability to put my problem into the proper words. So, I apologize profusely in ad…
tagged with: python
has comment: http://stackoverflow.com/comment/88975702
has answer: http://stackoverflow.com/a/50992977

http://stackoverflow.com/q/50934155
type: Question
downvote count: 0
answer count: 1
has body: The python package lifetimes is using BG/NBD method which is the same as the R package BTYD. In the R paper, we could estimate the customer lifetime (CLV) package on any newly acquired customer given a specified time range. However, I am not able to find the equivalent function in python. It seems all the information which I could find is to estimate the CLV given a past frequency and recency as a conditional probability. Has anyone had any experience on this ?
favorite count: 0
tagged with: lifetime
type: UnansweredQuestion
tagged with: lifetimes-python
upvote count: 1
tagged with: python
has title: How to get the expected value of customer lifetime using lifetimes package in Python
score: 1
has answer: http://stackoverflow.com/a/53938718

http://stackoverflow.com/comment/88931148
score: 0
type: Comment
has text: Aah!! You mean the lists? I need to store lists, I do not have any other option
comment on: http://stackoverflow.com/a/50966490
type: AnswerComment

http://stackoverflow.com/a/65618207
has body: Try by installing directly within Jupyter using the following command in a Jupyter cell: import sys !{sys.executable} -m pip install your_package_name
score: 10
upvote count: 10
type: Answer
answers question: http://stackoverflow.com/q/50939461
downvote count: 0

http://stackoverflow.com/a/50890306
score: 0
answers question: http://stackoverflow.com/q/50890242
type: Answer
has body: here : folnum= file[i].split(" ",-1) when you make a for loop statment i is of type str not int for i in file: # i is of type string not integer # in this case you has something like this file['a'].split(' ', -1) # ['a'] is for example, in this case when we call lst['string'] we get TypeError: list indices must be integers or slices, not str you need to check first of all what you have in i variable, also as mentioned @MartijnPieters you can use i.split() lines = open("demo.txt").read().splitlines() ... for line in lines: ... line.split(' ', -1) ...

http://stackoverflow.com/q/50930393
has title: How to automatically group conditions together in python?
type: AnsweredQuestion
downvote count: 0
accepted answer: http://stackoverflow.com/a/50930479
has body: I'm trying to automatically group conditions together in python. The difficulty lies in that if there are several conditions, like 100 conditions, it would be tedious to "AND" all of these by hand. How can I use a loop to achieve this? import pandas as pd s1 = pd.Series([1,2,3,4,5,6]) s2 = pd.Series([5,6,7,8,9,10]) s3 = pd.Series([11,12,5,7,8,2]) df = pd.DataFrame({'A': s1,'B': s2,'C': s3}) condition1 = df['A'] &gt; 3 condition2 = df['B'] &gt; 6 condition3 = df['C'] &gt; 5 # AND Operation -&gt;&gt;&gt; Can be achieved with a loop? select = condition1 &amp; condition2 &amp; condition3
favorite count: 0
type: Question
tagged with: python
score: 4
possible better answer: http://stackoverflow.com/a/50930428
has answer: http://stackoverflow.com/a/50930428
answer count: 2
has answer: http://stackoverflow.com/a/50930479
upvote count: 4
tagged with: numpy
tagged with: logical-operators
tagged with: pandas

http://stackoverflow.com/q/50907013
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/88816471
has title: python3 manage.py dbshell not working
has body: I am getting the following error while executing python3 manage.py dbshell on my mac. Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 15, in &lt;module&gt; import MySQLdb as Database File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/MySQLdb/__init__.py", line 19, in &lt;module&gt; import _mysql ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/_mysql.cpython-36m-darwin.so, 2): Library not loaded: libssl.1.0.0.dylib Referenced from: /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/_mysql.cpython-36m-darwin.so Reason: image not found The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in &lt;module&gt; execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/__init__.py", line 347, in execute django.setup() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/Library/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._…
has comment: http://stackoverflow.com/comment/88824281
score: 0
has answer: http://stackoverflow.com/a/50917790
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50908769
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/88816897
tagged with: django-mysql
tagged with: mysql

http://stackoverflow.com/comment/88762486
score: 0
type: Comment
type: AnswerComment
has text: Is there a library in sklearn which splits data into Train and Test based on time and not randomly or is there any other method?
comment on: http://stackoverflow.com/a/50880096

http://stackoverflow.com/comment/88940540
type: Comment
comment on: http://stackoverflow.com/q/50969167
score: 0
type: QuestionComment
has text: It wasn't clear to me what do you try to achieve. only from the name `dopp` I finally realized that you want a transformation for a tone. The transformation should mimic Doppler's effect. Is it right?

http://stackoverflow.com/q/50916517
type: UnansweredQuestion
has body: I'm trying to "SELECT" a value from Db and add this value to another variable, but when I execute this I get this error "TypeError: unsupported operand type(s) for +: 'NoneType' and 'int' " id = input("Digite o id do cartão: ") cash = int(input("Digite o o valor a ser creditado: ")) dia = 3 sql = 'SELECT saldo FROM carteira where idcartao = ?' def selectbanco(): c.execute("SELECT saldo FROM carteira WHERE idcartao=?", (id,)) row = c.fetchone() print(row) row = c.fetchone() soma = (row) + (cash) c.execute("UPDATE carteira SET saldo=? WHERE idcartao=?", (soma, id)) connection.commit() selectbanco() THIS IS MY COMPLETE CODE import sqlite3 connection = sqlite3.connect('clientes.db') c = connection.cursor() #criação de tabela def create_table(): c.execute('CREATE TABLE IF NOT EXISTS carteira (idcartao REAL, saldo REAL, data text)') create_table() #variaveis id = input("Digite o id do cartão: ") cash = int(input("Digite o o valor a ser creditado: ")) dia = 3 sql = 'SELECT saldo FROM carteira where idcartao = ?' #SELECT E RETORNAR VALOR def selectbanco(): c.execute("SELECT saldo FROM carteira WHERE idcartao=?", (id,)) row = c.fetchone() print(row) row = c.fetchone() ##soma = (row + cash) ##print(soma) c.execute("UPDATE carteira SET saldo=? WHERE idcartao=?", (cash, id)) connection.commit() selectbanco() #leitura do banco def read_data(wordUsed): for row in c.execute(sql, (wordUsed,)): print (row) read_data(id) connection.close()
tagged with: python
has answer: http://stackoverflow.com/a/50916854
downvote count: 2
has answer: http://stackoverflow.com/a/50916569
type: Question
has title: Convert SQLITE 'NoneType in a int python
has comment: http://stackoverflow.com/comment/88833034
score: -2
answer count: 2
has comment: http://stackoverflow.com/comment/88833115
upvote count: 0
tagged with: sqlite
has comment: http://stackoverflow.com/comment/88833154
favorite count: 0

http://stackoverflow.com/comment/88729570
type: QuestionComment
comment on: http://stackoverflow.com/q/50863484
type: Comment
score: 1
has text: You should look into Popen (the underlying functionality of subprocess) and the `communicate()` method that will allow you to issue commands to your subprocess.

http://stackoverflow.com/q/50932977
has answer: http://stackoverflow.com/a/50935316
upvote count: 1
type: Question
tagged with: split
accepted answer: http://stackoverflow.com/a/50935316
has body: I like to create a sequence database, based on different activities (ACT) on same or different dates. As you can see, some rows may contain NaN values. I need the final data to train a machine learning model on sequences of activities. ID ACT1 ACT2 ACT3 ACT4 ACT5 0 2015-08-11 2015-08-16 2015-08-16 2015-09-22 2015-08-19 1 2014-07-16 2014-07-16 2014-09-16 NaT 2014-09-12 2 2016-07-16 NaT 2017-09-16 2017-09-16 2017-12-16 The expected output, which will split or merge based on the date values, would look like following table: ID Sequence1 Sequence2 Sequence3 Sequence4 0 ACT1 ACT2,ACT3 ACT5 ACT4 1 ACT1,ACT2 ACT5 ACT3 2 ACT1 ACT3,ACT4 ACT5 Following script will output a string with the whole sequence only: df['Sequence'] = df.loc[:, cols].apply(lambda dr: ','.join(df.loc[:, cols].columns[dr.dropna().argsort()]), axis=1) Sequence ACT1,ACT2,ACT3,ACT5,ACT4 ACT1,ACT2,ACT5,ACT3 ACT1,ACT3,ACT4,ACT5
answer count: 1
downvote count: 0
tagged with: sequence
favorite count: 0
tagged with: python
tagged with: merge
has comment: http://stackoverflow.com/comment/88865328
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88866136
has title: Split or merge actions by date
score: 1

http://stackoverflow.com/q/50951790
has body: I wrote this about a year ago in python 2.x. I have since switched over to 3.x, and I am not getting any errors, but as mentioned above, only one plot is being outputted, the first stdev one. If I use #%% in Spyder to make the code under ...##mean plot##... into its own cell and run the cell, it will make that plot. If I switch the order of the mean and stdev code, then it will just make the one that comes first. I have many similar scripts and they all are having the same issue. Is it the indentation? I've played around with it to no avail. # -*- coding: utf-8 -*- """ Created on Wed Jun 28 09:16:29 2017 @author: kmiranda """ import numpy as np import matplotlib.pyplot as plt import mpl_toolkits.basemap as bm ##from ens_function import ens_data, grd_data from scipy.io import netcdf for date in np.arange(3,16): mem=0o01 DTG = '201501%2.2d00' % (date) nfdir='/u/prob/coupled/rowley/pertobs/kmiranda/scratch/gom/ensemble/post' ncfn=nfdir + '/ncom_relo_gom_' + DTG + '.%3.3d'%mem + '.nc' nc1 = netcdf.netcdf_file(ncfn, 'r') lat = nc1.variables['lat'][:] lon = nc1.variables['lon'][:] dep = nc1.variables['depth'][:] tau = nc1.variables['tau'][:] ## added this. it's probably not right water_temp = nc1.variables['water_temp'] t0 = np.squeeze(water_temp[1,:,:,:])*1. ##I changed the 0 to 1 here t0[np.where(t0 == -30000)]=np.nan bbox=[262.,281.,18.,31.] ma = bm.Basemap(projection='merc',llcrnrlat=bbox[2],urcrnrlat=bbox[3], \ llcrnrlon=bbox[0],urcrnrlon=bbox[1],lat_ts=0,resolution='i') s1 = np.zeros(t0.shape) s2 = np.zeros(t0.shape) #del lat, lon, dep, water_temp, t0 #nc1.close() for i in np.arange(1,33): DTG = '201501%2.2d00' % (date) nfdir='/u/prob/coupled/rowley/pertobs/kmiranda/scratch/gom/ensemble/post' ncfn=nfdir + '/ncom_relo_gom_' + DTG + '.%3.3d' %i + '.nc' nc1 = netcdf.netcdf_file(ncfn, 'r') water_temp = nc1.variables['water_temp'] t0 = np.squeeze(water_temp[1,:,:,:])*1. ##I changed the 0 to 1 here t0[np.where(t0 == -30000)]=np.nan temp = np.ma.masked_invalid(np.squeeze(t…
answer count: 0
type: UnansweredQuestion
tagged with: matplotlib-basemap
tagged with: python-3.x
type: Question
tagged with: python
tagged with: plot
has comment: http://stackoverflow.com/comment/88901742
score: 0
tagged with: matplotlib
has title: This script in python 2.x worked and made multiple plots in one run. Now, in python 3.x, it only makes one plot
has comment: http://stackoverflow.com/comment/88901277

http://stackoverflow.com/q/50964193
type: Question
has title: Need to convert valid date values and error out invalid values in Python
answer count: 1
tagged with: strptime
upvote count: 1
has body: I am using Python3.6 datetime.datetime.strptime to parse different input date values based on provided format. Below is the code I am using. def date_convert(dt, fmt): outdict = {'result': '', 'error': ''} try: outdict['result'] = datetime.strptime(dt, fmt) except Exception: outdict['error'] = 'Invalid input date value, expected format is ' + fmt I am facing two issues with above code Can not recognize invalid date values for %Y%m%d, %y%m%d, %Y%m%d %H:%M and few more formats. In Java we have setLenient option which will help us to match to exact and convert Ex: date_convert('181223', '%Y%m%d') For above input I am getting output as 1812-02-03 00:00:00 but I need to get output as invalid format. How to achieve this Few times I will be getting two or three date formats with in a specific column for few data files. For this I want to pass list of formats so that which ever format matches that should be used and converted. Ex:Below is are values of a single field coming in file. I want to pass somthing like ['%Y%m%d','%m-%d-%y','%d-%b-%Y'] and convert all input values Date_Field 2018-23-04 2018-14-04 03-17-18 12-29-17 25-Mar-2018 29-Jan-2018 Thanks, Raghunath.
favorite count: 0
downvote count: 0
type: UnansweredQuestion
tagged with: python
score: 1
has answer: http://stackoverflow.com/a/50964803

http://stackoverflow.com/a/50944849
upvote count: 3
type: Answer
has body: The answer by @ReblochonMasque is correct in saying that you need to actually show the figure, using plt.show(). You do however not need to return anything from the animating function (unless you want to use blitting, in which case you would need to return an iterable of Artists to blit). And also, if you make your FuncAnimation a class variable (self.ani) it ensures to be able to call show() at any point, not just within the `animate function. import matplotlib.animation as animation import matplotlib.pyplot as plt class Example: def __init__(self): self.fig, self.ax = plt.subplots() def update(self, i): print("This is getting called {}".format(i)) self.ax.plot([i,i+1],[i,i+2]) def animate(self): self.ani = animation.FuncAnimation(self.fig, self.update, interval=100) def main(): obj = Example() obj.animate() plt.show() if __name__ == "__main__": main()
accepted answer of: http://stackoverflow.com/q/50939773
score: 3
downvote count: 0
answers question: http://stackoverflow.com/q/50939773
type: AcceptedAnswer

mask
tags question: http://stackoverflow.com/q/51002815
tags question: http://stackoverflow.com/q/50959570
type: Tag
tag name: mask
tags question: http://stackoverflow.com/q/50888612

http://stackoverflow.com/q/50933025
downvote count: 0
type: Question
score: 1
tagged with: python-2.7
upvote count: 1
answer count: 1
has body: We currently have a Compute Engine server with a MSSQL database. We want to use App Engine and connect to our database within our compute engine. I understand we can not do this using the Standard Environment, yet I am unclear if this can be accomplished using the Flexible environment. We use pyodbc to connect to our database when using Python. I have read in a few places pyodbc does not work with App Engine but I have not found any clear answers. Is it possible to connect to my database in Compute Engine using Google App Engine? Have any of you succeeded in doing this? When using python what library did you use to connect to the database?
favorite count: 0
has answer: http://stackoverflow.com/a/50933354
has title: Does Google App Engine Flexible Environment support pyodbc?
type: UnansweredQuestion
tagged with: google-app-engine
tagged with: google-compute-engine
tagged with: python

http://stackoverflow.com/q/50876655
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/50877106
score: -1
has title: Insert datetime to database using json_populate_record
answer count: 1
downvote count: 1
favorite count: 0
tagged with: postgresql
has body: How can I insert python's datetime to timestamp column using using json_populate_record? I tried an [advice][1]. But it doesn't work for me, when I'm using json_populate_record: def add_trade(self, order_sell_id: UUID, execution_time: datetime): trade = { "order_sell_id": order_sell_id, "execution_time": "TIMESTAMP " + str(execution_time) } try: order_sql = ( f"INSERT INTO \"trade\"(order_sell_id, execution_time) " f" SELECT order_sell_id, execution_time" f" FROM " f"json_populate_record(NULL::\"trade\", '{json.dumps(trade)}');") result = self.database.query(order_sql) except pg.IntegrityError as e: pass For the code above I have an exception: pg.DataError: ERROR: invalid input syntax for type timestamp: "TIMESTAMP 2018-06-15 16:14:36" I tried insert datetime by just adding to dict: "execution_time": execution_time And got: pg.DataError: ERROR: date/time field value out of range: "1529069127000"
type: UnansweredQuestion
tagged with: python
upvote count: 0
type: Question

http://stackoverflow.com/comment/89037915
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51004714
has text: Can you type the entire command? I am not able to get the same.
score: 0

http://stackoverflow.com/q/50910357
tagged with: arrays
downvote count: 0
accepted answer: http://stackoverflow.com/a/50910650
favorite count: 0
tagged with: python
upvote count: 6
has comment: http://stackoverflow.com/comment/88821167
has title: Check equality of two axes in multidiimensional numpy array
type: AnsweredQuestion
score: 6
has answer: http://stackoverflow.com/a/50910650
type: Question
tagged with: numpy
has body: I am given a 3-dimensional shape(n,m,k) numpy array. I'd like to view this as a 2-dimensional matrix containing vectors, i.e. a nxm matrix with a vector of size k. I'd now like to check for two such arrays of shape (n,m,k) wheter entry (x,y,:) in the first array is equal to (x,y,:) in the second array. Is there a method to do this in numpy without using loops? I'd thought about something like A == B conditioned on the first and second axis.
answer count: 1

http://stackoverflow.com/comment/88937299
type: AnswerComment
has text: Hi Thomas., how to go about retaining independent axis (y and x) for each subplot? I used for i,el in enumerate(list(df.columns.values)): df.boxplot(el, by=metacategory,ax=axes.flatten()[i]) but wasn't able to apply independent colors to each box in that case...
type: Comment
comment on: http://stackoverflow.com/a/50967405
score: 0

http://stackoverflow.com/comment/88927120
type: QuestionComment
has text: Im python, is there a way to iterate through each line in the df, change format and append?
score: 0
comment on: http://stackoverflow.com/q/50963793
type: Comment

http://stackoverflow.com/a/50871424
downvote count: 0
upvote count: 2
answers question: http://stackoverflow.com/q/50871370
has comment: http://stackoverflow.com/comment/88744624
has comment: http://stackoverflow.com/comment/88744504
has body: Per https://www.programiz.com/python-programming/methods/set/symmetric_difference: The symmetric difference of two sets A and B is the set of elements which are in either of the sets A or B but not in both. However the difference of course, is self explanatory.
type: Answer
score: 2

http://stackoverflow.com/q/50907268
type: Question
tagged with: lda
has title: Assign categories to words based on similarities
has body: I have corpus of about 1 million documents of sentences. Let's say:- sentence 1: "Thrilling contest between manchester city and manchester united ends in draw" I want to assign sentences based on categories like above message belongs to category of "sports" and again assigned it to further categories like "football" categories in sports. I want to categorize texts into four categories "entertainment","sports","politics","technology". I have used an approach of Word2vec but it can only tells the relationship between two sentences. How exactly I can do this? I don't have any predefined labelled data just only million of records. what I really want to do something like this
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: nlp
answer count: 0
has comment: http://stackoverflow.com/comment/97309319
score: 1
upvote count: 1
tagged with: text-classification

http://stackoverflow.com/q/50932960
answer count: 0
tagged with: linear-regression
score: 0
has title: Get the Beta from a regression model
type: Question
has comment: http://stackoverflow.com/comment/88865209
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88865163
tagged with: python
has body: I am using python to calculate a linear regression from a dataframe. I would like to know how get just the beta of the equation, in order to return to the inial dataframe ? Using this function, I can get the beta: lm = smf.ols("np.log(Volume) ~ np.log(PrecoVenda)", data=df2).fit() print(lm.params) Intercept 5.435106 np.log(PrecoVenda) 0.819627 dtype: float64 How to select just the beta from the equation ?

http://stackoverflow.com/comment/88789346
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50894497
has text: @Chris Definitely try Platypus (https://sveinbjorn.org/platypus) it requires literally nothing just the script itself and it is a .app program so you don't have to `pip install` anything.

http://stackoverflow.com/a/50963422
has body: You can do it without using regular expression. Like: for i in range(len(test)): if 'XXX' in test[i]: test[i] = test[i].replace("XXX","").strip()+" XXX" #if XXX present in the list then remote it and then remove white space of both side using strip function and then append XXX at the end of the string. Output: ['ABC 1', 'ABC 2', 'ABC 1 XXX', 'ABC 2 XXX', 'ABCD 1']
downvote count: 0
answers question: http://stackoverflow.com/q/50963346
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/q/50892989
tagged with: python
has answer: http://stackoverflow.com/a/51079764
score: 1
upvote count: 1
tagged with: networkx
type: Question
has title: Correlation between level and overlapping in community
downvote count: 0
answer count: 1
favorite count: 0
has body: dendo = community.generate_dendrogram(G_fb) for level in range(len(dendo) - 1) : print("partition at level", level, "is", partition_at_level(dendo, level)) So I run the code above on my own data and found that the level of my data is only 1. It seems that the level is the size of the community where in my case, they are small. But what should I do next to find out overlapping communities, which means a node can be included within more than one communities in the output of the detection algorithm, for instance best_partition which is what I used for community detection. In other words, is there any correlation between the level and overlapping? You can find the community graph below.
linked to: http://stackoverflow.com/q/20063927
type: UnansweredQuestion

http://stackoverflow.com/comment/88866232
comment on: http://stackoverflow.com/a/50933653
type: AnswerComment
has text: Hmm, I am not that familiar with python, but the code you've shown here looks like Column1 will get `5` and Column2 will get `'2'` _with the single-quotes included._
score: 0
type: Comment

http://stackoverflow.com/q/50860328
type: Question
has body: My dataframe looks like this: +-----+-------+----------+-------+ | No | Group | refGroup | Value | +-----+-------+----------+-------+ | 123 | A1 | A1 | 5.0 | | 123 | B1 | A1 | 7.3 | | 123 | B2 | A1 | 8.9 | | 123 | B3 | B1 | 7.9 | | 465 | A1 | A1 | 1.4 | | 465 | B1 | A1 | 4.5 | | 465 | B2 | B1 | 7.3 | +-----+-------+----------+-------+ Now I need to add another column which conatains the difference between the value of column Value from the current row and the value of column Value from the row with the same number (No) and the group (Group) that is written in refGroup. Exeption: If refGroup equals Group, Value and refValue are the same. So the result should be: +-----+-------+----------+-------+----------+ | No | Group | refGroup | Value | refValue | +-----+-------+----------+-------+----------+ | 123 | A1 | A1 | 5.0 | 5.0 | | 123 | B1 | A1 | 7.3 | 2.3 | | 123 | B2 | A1 | 8.9 | 3.9 | | 123 | B3 | B1 | 7.9 | 0.6 | | 465 | A1 | A1 | 1.4 | 1.4 | | 465 | B1 | A1 | 4.5 | 3.1 | | 465 | B2 | B1 | 7.3 | 2.8 | +-----+-------+----------+-------+----------+ Explanation for the first two rows: First row: refGroup equals Group -> refValue = Value Second row: search for the row with the same No (123) and refGroup as Group (A1) and calculate Value of the current row minus Value of the referenced row (7.3 - 5.0 = 2.3). I thought I might need to use groupby() and apply(), but how? Hope my example is detailed enough, if you need any further information, please ask :)
has answer: http://stackoverflow.com/a/50861880
answer count: 2
accepted answer: http://stackoverflow.com/a/50861880
has comment: http://stackoverflow.com/comment/88724224
score: 0
tagged with: pandas
has title: Python - Add a column to a dataframe containing a value from another row based on condition
possible better answer: http://stackoverflow.com/a/50862026
has comment: http://stackoverflow.com/comment/88724314
tagged with: python
type: AnsweredQuestion
tagged with: dataframe
has answer: http://stackoverflow.com/a/50862026

http://stackoverflow.com/a/50900549
type: Answer
has body: This code: message = 'First part' + ';' + 'Second part' Is exactly equivalent to: message = 'First part; Second part' The + is just combining the strings together into one. It is not going to make Python remember each part separately so that message[0] is 'First part'. message[0] is just the first character of the string, so it's 'F'. The best you can do is: message = 'First part; Second part' m='101.0.0.1' message = message.replace('First part', m) print(message) The import string is not needed at all and calling the method directly on str is not something you want to do.
accepted answer of: http://stackoverflow.com/q/50900491
has comment: http://stackoverflow.com/comment/88810453
type: AcceptedAnswer
score: 0
has comment: http://stackoverflow.com/comment/88803012
answers question: http://stackoverflow.com/q/50900491

http://stackoverflow.com/q/50869968
has answer: http://stackoverflow.com/a/69037482
tagged with: error-handling
type: Question
has comment: http://stackoverflow.com/comment/88745850
score: 20
answer count: 2
upvote count: 21
tagged with: environment-variables
has title: Is it appropriate to raise an EnvironmentError for os.environ?
downvote count: 1
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has body: When os.environ is given the name of an environment variable that is not set, it throws a KeyError: In [1]: my_value = os.environ['SOME_VALUE'] --------------------------------------------------------------------------- KeyError Traceback (most recent call last) &lt;ipython-input-6-0573debe183e&gt; in &lt;module&gt;() ----&gt; 1 my_value = os.environ['SOME_VALUE'] ~/blah/ve/lib/python3.6/os.py in __getitem__(self, key) 667 except KeyError: 668 # raise KeyError with the original key value --&gt; 669 raise KeyError(key) from None 670 return self.decodevalue(value) 671 KeyError: 'SOME_VALUE' I get that a KeyError is raised because os.environ is like a dict, but in an application that needs SOME_VALUE to be set, I want to raise a more informative error when the user has neglected to set it. One option is to raise an EnvironmentError with a more informative message: try: my_value = os.environ['SOME_VALUE'] except KeyError: raise EnvironmentError('SOME_VALUE environment variable needs to be set to import this module') from KeyError --------------------------------------------------------------------------- KeyError Traceback (most recent call last) KeyError: The above exception was the direct cause of the following exception: OSError Traceback (most recent call last) &lt;ipython-input-10-406772b14ea9&gt; in &lt;module&gt;() 2 my_value = os.environ['SOME_VALUE'] 3 except KeyError: ----&gt; 4 raise EnvironmentError('SOME_VALUE environment variable not set') from KeyError OSError: SOME_VALUE environment variable not set It is curious to me that this raises an OSError. The Python 2.7 documentation says EnvironmentError is the base class for OSError, and that base exceptions "...are only used as base classes for other exceptions." In Python 3.6 documentation, EnvironmentError is listed among concrete exceptions, but without any documentation for the error class itself. Questions: Is it even appropriate to use EnvironmentError in this case? Should I be using some other built-in…
tagged with: python
has answer: http://stackoverflow.com/a/56072795

http://stackoverflow.com/q/50883008
downvote count: 1
has comment: http://stackoverflow.com/comment/88768228
type: Question
has comment: http://stackoverflow.com/comment/88768224
score: -1
has title: Convert a text file into a nested json in python
upvote count: 0
accepted answer: http://stackoverflow.com/a/50883196
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50883196
tagged with: python
type: AnsweredQuestion
has body: My data looks like below. This is the input file: storeId,id,itemId,description 123,1,101,item_1 123,1,102,item_2 123,1,103,item_3 123,2,201,item_4 123,2,202,item_5 I want to parse it using Python and write the JSON equivalent so that the information is re-written to a file in the following format: [{ "storeId": 123, "itemType": [{ "id": 1, "items": [{ "itemId": 101, "description": "item_1" }, { "itemId": 102, "description": "item_2" }, { "itemId": 103, "description": "item_3" }] }, { "id": 2, "images": [{ "itemId": 201, "description": "item_4" }, { "itemId": 202, "description": "item_5" }] }] }] enter code here I am confused how I can achieve this. Can anyone help me, please? I am very new to python.
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/comment/88791383
has text: No that solution is not helping me out @OferSadan . I have tried that still getting the same error.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50895571

http://stackoverflow.com/comment/88829571
score: 0
has text: Unrelated to answering the question: it's customary to `import matplotlib.pyplot as plt`.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50914364

http://stackoverflow.com/comment/88979277
score: 0
type: Comment
type: QuestionComment
has text: You code works as expected on my end. I added a print statement to the loop to check the value of `value.get()` and the ones I have selected were changed to `1`.
comment on: http://stackoverflow.com/q/50991338

http://stackoverflow.com/a/74622637
answers question: http://stackoverflow.com/q/50971279
type: Answer
has body: n = int (input ('')) print(n*(n+1)//2)
score: 0

http://stackoverflow.com/comment/88959549
has text: Thank Wiktor, But that is not the major issue, I am more concerned about the data inside brackets, with your (?:is|not) output changed to ["orderType not in ('connect', 'Modify'"] but there are two more terms missing after modify
comment on: http://stackoverflow.com/q/50982111
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88849442
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50924843
has text: Yes, the experiments are performed using psycopg2. The tables are the same. So, in order to understand, you also expect that the response time would be slower in case of pgpool ?

http://stackoverflow.com/comment/124128867
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50933001
type: Comment
has text: I see your point but I am using Ubuntu 18.04 and python 3.6.9. I wouldn't expect any problem in such a famous distro. But this is the case. I am now using notification with large timeout :(

http://stackoverflow.com/comment/88905271
comment on: http://stackoverflow.com/a/50944356
has text: ok I found you! just remove or hide your id for the security
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/50991698
score: 4
has comment: http://stackoverflow.com/comment/89013595
has comment: http://stackoverflow.com/comment/88986396
has comment: http://stackoverflow.com/comment/88987657
has comment: http://stackoverflow.com/comment/88986521
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/50991371
downvote count: 0
has comment: http://stackoverflow.com/comment/89011336
has comment: http://stackoverflow.com/comment/88986871
has body: Problem &amp; Explanation Your app encountered problem because self is referring to Screen2 and ids.screen1 does not exist in self.ids. If you add a print(self.ids) before the code, it will display all the ids defined in kv file under Screen2. Snippets self.screen2_textinput.text = self.ids.screen1_textinput.text Soltuion Please refer to the example for details. kv file Add a new class ScreenManagement Add screens 1 and 2 under ScreenManagement Add ids for screens 1 and 2 Remove on_text event for screen1_textinput Python file Replace passvariables(self) with on_enter(self, *args) Replace self.ids.screen1_textinput.text with self.manager.ids.screen1.ids.screen1_textinput.text Add class ScreenManagement Replace return sm with return ScreenManagement() Remove all references to sm Example main.py ## IMPORT THE DIFFERENT PACKAGES AND PROGRAMS NEEDED FOR THE APP TO WORK from kivy.app import App from kivy.lang import Builder from kivy.uix.screenmanager import ScreenManager, Screen, NoTransition, SwapTransition, FadeTransition, WipeTransition, FallOutTransition, RiseInTransition from kivy.uix.relativelayout import RelativeLayout from kivy.uix.label import Label from kivy.uix.button import Button ## THE BUILDER HAS THE CODE THAT DEFINES THE APPEARANCE OF THE APP. IT IS THE KIVY CODE Builder.load_string(&quot;&quot;&quot; #:import FallOutTransition kivy.uix.screenmanager.FallOutTransition &lt;ScreenManagement&gt;: transition: FallOutTransition() Screen1: id: screen1 name: 'screen1' Screen2: id: screen2 name: 'screen2' ############################################################SCREEN 1######################################## &lt;Screen1&gt;: RelativeLayout: # RelativeLayout allows the elements of a screen to be positioned relatively to the position of the screen Label: # Label is just text id: screen1_label # Identifier text: 'This screen just shows a TextInput and a slider' # Text that appears in the label pos_hint: {'x': 0.5, 'y': 0.9} # Position of the Label in relation to…

http://stackoverflow.com/q/50982064
possible better answer: http://stackoverflow.com/a/71509091
has answer: http://stackoverflow.com/a/51118519
accepted answer: http://stackoverflow.com/a/51118519
score: 36
downvote count: 1
has comment: http://stackoverflow.com/comment/88986566
tagged with: python-docx
has comment: http://stackoverflow.com/comment/89449737
favorite count: 0
upvote count: 37
answer count: 5
tagged with: http://stackoverflow.com/tag/pdf
tagged with: python
tagged with: pythonanywhere
linked to: http://stackoverflow.com/q/66719566
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/docx
has comment: http://stackoverflow.com/comment/88973141
has body: I'm dealing with a problem trying to develop a web-app, part of which converts uploaded docx files to pdf files (after some processing). With python-docx and other methods, I do not require a windows machine with word installed, or even libreoffice on linux, for most of the processing (my web server is pythonanywhere - linux but without libreoffice and without sudo or apt install permissions). But converting to pdf seems to require one of those. From exploring questions here and elsewhere, this is what I have so far: import subprocess try: from comtypes import client except ImportError: client = None def doc2pdf(doc): """ convert a doc/docx document to pdf format :param doc: path to document """ doc = os.path.abspath(doc) # bugfix - searching files in windows/system32 if client is None: return doc2pdf_linux(doc) name, ext = os.path.splitext(doc) try: word = client.CreateObject('Word.Application') worddoc = word.Documents.Open(doc) worddoc.SaveAs(name + '.pdf', FileFormat=17) except Exception: raise finally: worddoc.Close() word.Quit() def doc2pdf_linux(doc): """ convert a doc/docx document to pdf format (linux only, requires libreoffice) :param doc: path to document """ cmd = 'libreoffice --convert-to pdf'.split() + [doc] p = subprocess.Popen(cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE) p.wait(timeout=10) stdout, stderr = p.communicate() if stderr: raise subprocess.SubprocessError(stderr) As you can see, one method requires comtypes, another requires libreoffice as a subprocess. Other than switching to a more sophisticated hosting server, is there any solution?
has answer: http://stackoverflow.com/a/56067358
has comment: http://stackoverflow.com/comment/88986677
has comment: http://stackoverflow.com/comment/89194139
has answer: http://stackoverflow.com/a/71509091
type: Question
has answer: http://stackoverflow.com/a/71404643
has title: Converting docx to pdf with pure python (on linux, without libreoffice)
has answer: http://stackoverflow.com/a/76250978

http://stackoverflow.com/q/50878530
has comment: http://stackoverflow.com/comment/88759209
score: 1
has comment: http://stackoverflow.com/comment/88759329
has comment: http://stackoverflow.com/comment/88759369
has comment: http://stackoverflow.com/comment/88759132
linked to: http://stackoverflow.com/q/575196
upvote count: 1
linked to: http://stackoverflow.com/q/3238350
linked to: http://stackoverflow.com/q/986006
type: Question
has title: Changing variable in function with argument
accepted answer: http://stackoverflow.com/a/50878793
has comment: http://stackoverflow.com/comment/88759230
has comment: http://stackoverflow.com/comment/88759109
possible better answer: http://stackoverflow.com/a/50878705
has comment: http://stackoverflow.com/comment/88759346
has answer: http://stackoverflow.com/a/50878705
answer count: 2
has comment: http://stackoverflow.com/comment/88759362
has comment: http://stackoverflow.com/comment/88760660
downvote count: 0
has body: I really don't have a clue how to increase variables by using function with an argument. Code down below prints 0 and 1 and i understand why but i don't know how to fix it. It's just a general 'shape' of a code, so there can be any number of variables. Will appreciate if you take a look! i=0 b=0 def increase(a): print(a) a+=1 print(a) for e in range (3): increase(i) increase(b)
favorite count: 0
has comment: http://stackoverflow.com/comment/88759166
has comment: http://stackoverflow.com/comment/88759897
has answer: http://stackoverflow.com/a/50878793
tagged with: python
has comment: http://stackoverflow.com/comment/88759330
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88759151

http://stackoverflow.com/q/51007672
has comment: http://stackoverflow.com/comment/89008549
tagged with: navigation
type: Question
has comment: http://stackoverflow.com/comment/89009066
has body: I'm using Selenium with Python to log onto a page, and then immediately jump to another page in the same tab. I need the credentials of the page to be saved, but what happens is they are lost when I move to the new page. I have tried 2 things - one is to save the cookies after the input.send_keys(keys.ENTER) command in the code below using pickle.dump, and then loading the same cookies after the new page loads. The other is to just load a Firefox profile I made after saving the cookies. Here is my code: from selenium import webdriver from selenium.webdriver.common.keys import Keys import pickle from selenium.webdriver.firefox.webdriver import FirefoxProfile profile = FirefoxProfile("C:\\Users\\ace\\AppData\\Local\\Mozilla\\Firefox\\Profiles\\l4piuit9.ace") driver = webdriver.Firefox(profile) driver.get("https://forums.the-elite.net/index.php?action=login") # #handle the form data and log in by forcing an enter inputElement1 = driver.find_element_by_name("cookieneverexp").click() inputElement2 = driver.find_element_by_name("user") inputElement2.send_keys('REMOVED') inputElement3 = driver.find_element_by_name("passwrd") inputElement3.send_keys('REMOVED') inputElement3.send_keys(Keys.ENTER) #save the cookies, they don't transfer over when navigating to a new page #pickle.dump(driver.get_cookies(), open("elite.pkl", "wb")) #new page / poll driver.get("https://forums.the-elite.net/index.php?action=votelog;topic=22504") #get the cookies #cookies = pickle.load(open("elite.pkl", "rb")) #for cookie in cookies: # driver.add_cookie(cookie) None of these seem to do anything. I thought maybe a delay would be required so I included an implicit_wait of 10s but that did not seem to make a difference. What is the cause of this and how can I resolve it?
tagged with: firefox
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/89009104
has comment: http://stackoverflow.com/comment/89009128
has comment: http://stackoverflow.com/comment/89008861
favorite count: 0
has comment: http://stackoverflow.com/comment/89009792
has comment: http://stackoverflow.com/comment/92268255
tagged with: python
has title: losing cookies when navigating to a new page with selenium
score: 2
upvote count: 2
tagged with: cookies
type: UnansweredQuestion
tagged with: selenium
has comment: http://stackoverflow.com/comment/89008930
has answer: http://stackoverflow.com/a/51008229

selenium
tags question: http://stackoverflow.com/q/50892525
tags question: http://stackoverflow.com/q/50894723
tags question: http://stackoverflow.com/q/51006315
tags question: http://stackoverflow.com/q/50992042
tags question: http://stackoverflow.com/q/50977867
tags question: http://stackoverflow.com/q/50899282
tags question: http://stackoverflow.com/q/50894170
tags question: http://stackoverflow.com/q/50909553
tags question: http://stackoverflow.com/q/50971533
tags question: http://stackoverflow.com/q/50991180
tags question: http://stackoverflow.com/q/50900061
tags question: http://stackoverflow.com/q/50890519
tags question: http://stackoverflow.com/q/50954795
tags question: http://stackoverflow.com/q/50914072
tags question: http://stackoverflow.com/q/50890887
tags question: http://stackoverflow.com/q/50911887
tags question: http://stackoverflow.com/q/50946760
tags question: http://stackoverflow.com/q/51005742
tags question: http://stackoverflow.com/q/50911868
tags question: http://stackoverflow.com/q/50911961
tags question: http://stackoverflow.com/q/50895680
tags question: http://stackoverflow.com/q/50899707
tags question: http://stackoverflow.com/q/50962531
tags question: http://stackoverflow.com/q/50938216
tags question: http://stackoverflow.com/q/50864509
tags question: http://stackoverflow.com/q/50982097
tags question: http://stackoverflow.com/q/50908744
tags question: http://stackoverflow.com/q/50953377
tags question: http://stackoverflow.com/q/50894672
tags question: http://stackoverflow.com/q/50997096
tag name: selenium
tags question: http://stackoverflow.com/q/50886002
tags question: http://stackoverflow.com/q/50929829
tags question: http://stackoverflow.com/q/50970923
tags question: http://stackoverflow.com/q/50990178
tags question: http://stackoverflow.com/q/50946084
tags question: http://stackoverflow.com/q/50882896
tags question: http://stackoverflow.com/q/50971175
tags question: http://stackoverflow.com/q/50997189
tags question: http://stackoverflow.com/q/50905121
tags question: http://stackoverflow.com/q/51001909
tags question: http://stackoverflow.com/q/50918071
tags question: http://stackoverflow.com/q/50893341
tags question: http://stackoverflow.com/q/50937112
tags question: http://stackoverflow.com/q/50994565
tags question: http://stackoverflow.com/q/50887466
tags question: http://stackoverflow.com/q/51007672
tags question: http://stackoverflow.com/q/50947583
tags question: http://stackoverflow.com/q/50991432
tags question: http://stackoverflow.com/q/50937824
tags question: http://stackoverflow.com/q/50977255
tags question: http://stackoverflow.com/q/50885849
tags question: http://stackoverflow.com/q/50863551
tags question: http://stackoverflow.com/q/50918093
tags question: http://stackoverflow.com/q/50939736
tags question: http://stackoverflow.com/q/50867356
tags question: http://stackoverflow.com/q/50903226
tags question: http://stackoverflow.com/q/50939694
tags question: http://stackoverflow.com/q/50958923
tags question: http://stackoverflow.com/q/50898890
tags question: http://stackoverflow.com/q/50872382
tags question: http://stackoverflow.com/q/50949358
tags question: http://stackoverflow.com/q/50936242
tags question: http://stackoverflow.com/q/50908599
tags question: http://stackoverflow.com/q/50971700
type: Tag
tags question: http://stackoverflow.com/q/50915051
tags question: http://stackoverflow.com/q/51009982
tags question: http://stackoverflow.com/q/50939687
tags question: http://stackoverflow.com/q/50950973
tags question: http://stackoverflow.com/q/50877160
tags question: http://stackoverflow.com/q/50864700
tags question: http://stackoverflow.com/q/50960539
tags question: http://stackoverflow.com/q/50897022
tags question: http://stackoverflow.com/q/50974639
tags question: http://stackoverflow.com/q/50890364
tags question: http://stackoverflow.com/q/50999177
tags question: http://stackoverflow.com/q/50915207
tags question: http://stackoverflow.com/q/50996452
tags question: http://stackoverflow.com/q/50983673

http://stackoverflow.com/a/67197452
has body: I am kinda late to this, but if you wanted to do the check on your html, you could try creating a custom flask filter. In your app.py file type this, after you have defined your app variable def check_type(stuff, types): if type(stuff) == type(types): return True return False app.jinja_env.filters['check_type'] = check_type Then in your html file you could do Your Results {% for result in results %} {% for entry in result %} {% if entry | check_type(1) or entry | check_type(1.1) %} {{ entry }} {% else %} WAS NOT AN NUMBER! {% endfor %} {% endfor %} This should work it worked for me; I am using python 3.8 by the way
type: Answer
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50883289

http://stackoverflow.com/a/50997776
has comment: http://stackoverflow.com/comment/88991571
type: Answer
accepted answer of: http://stackoverflow.com/q/50997764
answers question: http://stackoverflow.com/q/50997764
score: 0
type: AcceptedAnswer
has body: You can cast the integer to a string, this will allow to process its characters one by one. You can then use a set to keep track of seen digits. For very big numbers, this will be more efficient than counting digits as you are assured it will always return before the eleventh digit. def has_duplicate_digit(x): digits = set() for d in str(x): if d in digits: return True digits.add(d) return False Examples print(has_duplicate_digit(123)) # False print(has_duplicate_digit(11)) # True

http://stackoverflow.com/a/50982646
type: Answer
has comment: http://stackoverflow.com/comment/88962373
downvote count: 0
has comment: http://stackoverflow.com/comment/88961909
has comment: http://stackoverflow.com/comment/88961635
has body: In urls.py you are using the url() function but path syntax. Change it to path: path('', index, name='polls_list'), path('&lt;int:id&gt;/details/', details, name='polls_details') Edit If you're using pre-2.0, path syntax is not supported, so you need to use regexes: url('^$', index, name='polls_list'), url('^(?P&lt;id&gt;\d+)/details/$', details, name='polls_details')
has comment: http://stackoverflow.com/comment/88960355
score: 1
has comment: http://stackoverflow.com/comment/88961473
has comment: http://stackoverflow.com/comment/88962109
accepted answer of: http://stackoverflow.com/q/50982334
upvote count: 1
answers question: http://stackoverflow.com/q/50982334
type: AcceptedAnswer

http://stackoverflow.com/a/50860567
has comment: http://stackoverflow.com/comment/88723916
has body: It's because few of the items are generated dynamically. There might be any better solution other than using selenium. However, as a workaround you can try the below way instead. from selenium import webdriver from bs4 import BeautifulSoup def fetch_item(driver,keyword): driver.get(url.format(keyword.replace(" ", "+"))) soup = BeautifulSoup(driver.page_source, 'html.parser') for items in soup.select("[id^='result_']"): try: name = items.select_one("h2").text except AttributeError: name = "" print(name) if __name__ == '__main__': url = "https://www.amazon.com/s/field-keywords={}" driver = webdriver.Chrome() try: fetch_item(driver,"men jeans") finally: driver.quit() Upon running the above script you should get 56 names or something as result.
has comment: http://stackoverflow.com/comment/88725040
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50857672
answers question: http://stackoverflow.com/q/50857672
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88725169
upvote count: 2
type: Answer

http://stackoverflow.com/comment/88822951
comment on: http://stackoverflow.com/a/50911002
type: AnswerComment
score: 0
has text: But how to implement this in my code, I understand the concept of recursion. However I don't know how to use it in my case, it seem it is written for max 3 iterations. Here theoretically can be infinite numbers of operations because it depends on user input.
type: Comment

http://stackoverflow.com/q/50864103
possible better answer: http://stackoverflow.com/a/50864302
tagged with: pandas
has answer: http://stackoverflow.com/a/50864302
has answer: http://stackoverflow.com/a/50864161
tagged with: python-3.x
tagged with: python
tagged with: lambda
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88731270
accepted answer: http://stackoverflow.com/a/50864161
type: Question
answer count: 2
has title: From dataFrame to list with TypeError: string indices must be integers
has body: I would like to create a list that looks like this at the end: [ {'name': 'Chrome', 'y': 550}, {'name': 'IE', 'y': 203}, ] my data frame is: df = pd.DataFrame({"CATEGORY":["Chrome","IE","FireFox","Safari","Opera","QQ"],"Users":[550,203,25,305,15,132]}) and in order to acheive this I'm trying something like this: list(map(lambda row: {'name': df[row['CATEGORY']], 'y': row['Users']}, df)) but the result I get is: TypeError: string indices must be integers Can anyone point out (1) what am I doing wrong and (2) how to fix it?
score: 0

http://stackoverflow.com/comment/88860073
type: QuestionComment
has text: Priority is only relevant as a way to choose between different possible parse trees (aka derivations). It seems like your input can only be parsed in one way, or ambiguity='explicit' would return all the different derivations. So priority won't affect the result.
score: 0
comment on: http://stackoverflow.com/q/50928531
type: Comment

http://stackoverflow.com/q/50915949
type: UnansweredQuestion
tagged with: pyqt
score: 3
answer count: 0
downvote count: 0
has body: I have defined 2 classes, one a cython class defined as AndorCameraSDK and a python class AndorCameraGUI. AndorCameraGUI consists of a GUI created using PyQt and AndorCameraSDK consists of camera functionalities. In class AndorCameraSDK, there exist a function LiveAcquisition which consists of acquiring images and displaying them after acquisition.I need to make acquiring and displaying on 2 seperate threads. When I looked up at QThreads examples, it's clearly mentioned to define the threading function within run() inside a Threading class. class YourThreadName(QThread): def __init__(self): QThread.__init__(self) def __del__(self): self.wait() def run(self): #your logic here LiveAcquisition code : @cython.boundscheck(False) @cython.wraparound(False) def LiveAquisition(self,nframes): cdef: int available AT_64 sizeInBytes AT_64 aoiStride AT_WC string[20] AT_WC string1[20] AT_WC string2[20] AT_WC string3[20] unsigned int timeOut unsigned char * pBuf unsigned char * _puc_image int BufSize unsigned int i np.npy_intp dims[2] np.npy_intp strides[2] np.dtype dtype = np.dtype('&lt;H') copy2WCStr("Acquisition Start",string) response_code = AT_Command(&lt;AT_H&gt;self.cameraHandle, string) copy2WCStr("ImageSizeBytes",string1) AT_GetInt(&lt;AT_H&gt; self.cameraHandle, string1, &amp;sizeInBytes) copy2WCStr("AOIStride",string1) AT_GetInt(&lt;AT_H&gt; self.cameraHandle, string1, &amp;aoiStride) dims[0] = self.aoiWidth/self.hbin dims[1] = self.aoiHeight/self.vbin strides[0] = 2 strides[1] = aoiStride image = np.zeros(((self.aoiWidth-self.AOILeft)/self.hbin, (self.aoiHeight-self.AOITop)/self.vbin), dtype=np.uint16) image = np.zeros(((self.aoiWidth)/self.hbin, (self.aoiHeight)/self.vbin), dtype=np.uint16) self.i = 0 self.nframes = nframes start = time.time() def update(): pBuf = &lt;unsigned char *&gt;calloc(sizeInBytes, sizeof(unsigned char)) AT_QueueBuffer(&lt;AT_H&gt;self.cameraHandle, pBuf, sizeInBytes) print "Frame number is :", print self.i timeOut = &lt;unsigned int&gt;(3 * se…
favorite count: 0
type: Question
tagged with: python
tagged with: qthread
upvote count: 3
tagged with: cython
has title: How to implement QThread in Cython, PyQT GUI ?

http://stackoverflow.com/q/50936281
has comment: http://stackoverflow.com/comment/88871896
has comment: http://stackoverflow.com/comment/88871281
has comment: http://stackoverflow.com/comment/88903208
has comment: http://stackoverflow.com/comment/88871895
has comment: http://stackoverflow.com/comment/88902058
has comment: http://stackoverflow.com/comment/88872875
has body: As a data scientist / machine learning developer, I have most of the time (always?) a load_data function. Executing this function often takes more than 5 minutes, because the executed operations are expensive. When I store the end result of load_data in a pickle file and read that file again, then the time often goes down to a few seconds. So a solution I use quite often is: def load_data(serialize_pickle_path, original_filepath): invalid_hash = True if os.path.exists(serialize_pickle_path): content = mpu.io.read(serialize_pickle_path) data = content['data'] invalid_hash = mpu.io.hash(original_filepath) != content['hash'] if invalid_hash: data = load_data_initial() filehash = mpu.io.hash(original_filepath) mpu.io.write(serialize_pickle_path, {'data': data, 'hash': filehash}) return data This solution has a major drawback: If the load_data_initial changed, the file will not be reloaded. Is there a way to check for changes in Python functions?
has comment: http://stackoverflow.com/comment/88871761
has comment: http://stackoverflow.com/comment/88871837
score: 2
has comment: http://stackoverflow.com/comment/88871921
answer count: 1
accepted answer: http://stackoverflow.com/a/50936484
favorite count: 0
has comment: http://stackoverflow.com/comment/88872008
tagged with: python
has comment: http://stackoverflow.com/comment/88878666
type: AnsweredQuestion
upvote count: 3
has answer: http://stackoverflow.com/a/50936484
downvote count: 1
type: Question
has title: How can I check if a loaded Python function changed?

http://stackoverflow.com/comment/88729837
comment on: http://stackoverflow.com/q/50863413
has text: @rd_nielsen I am trying to only pull the result of ID_2 from VW_TABLE which is not in the list of ID from TABLE. Does that make sense?
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51009126
accepted answer: http://stackoverflow.com/a/51043935
type: Question
upvote count: 6
has answer: http://stackoverflow.com/a/51043935
has title: OpenCV: How to correctly apply morphologyEx operation?
has comment: http://stackoverflow.com/comment/89011094
linked to: http://stackoverflow.com/q/10196198
has comment: http://stackoverflow.com/comment/89011081
answer count: 1
favorite count: 0
has body: I am having a problem regarding the kernel size for morphologyEx. I have some captcha images and I want to do the same operation on them and get the same final result. code : image = cv2.imread("Image.jpg") gray = cv2.cvtColor(image , cv2.COLOR_BGR2GRAY) ret, thresh1 = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU) k1 = np.ones((3,3)) k2 = np.ones((5,5)) bottom_image = cv2.morphologyEx(thresh1, cv2.MORPH_CLOSE, k1) bottom_image = 255-bottom_image bottom_image = remove_boxes(bottom_image , True) ret,thresh2 = cv2.threshold(bottom_image,127,255,cv2.THRESH_BINARY_INV) opening = cv2.morphologyEx(thresh2, cv2.MORPH_OPEN, k1) #closing = cv2.morphologyEx(opening, cv2.MORPH_CLOSE, k) # cv2.imshow('opening', opening) dilate = cv2.morphologyEx(opening, cv2.MORPH_DILATE, k2) dilate = cv2.bitwise_not(dilate) # cv2.imshow('dilation', dilate) bottom_image = cv2.morphologyEx(bottom_image, cv2.MORPH_CLOSE, k1) The perfect result would be Input: Output: But the problem appears when I apply it to other images with the same structure output is distorted. Example 1 : Input: Output: Example 2 : Input: Output: Example 3: Input: Output:
score: 6
tagged with: python
tagged with: opencv
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/q/50896287
type: Question
accepted answer: http://stackoverflow.com/a/53902939
tagged with: django
tagged with: python
answer count: 1
upvote count: 1
has title: Django custom login form show extra field
has body: I've created Django custom login form, but it shows email field for 2 times and it fails to auth. here are my files : urls.py path('login/', views.login, name='login'), models.py where is the modeluser table is created : class UserModelManager(BaseUserManager): def create_user(self, email, password, pseudo): user = self.model() user.name = name user.email = self.normalize_email(email=email) user.set_password(password) user.save() return user def create_superuser(self, email, password): ''' Used for: python manage.py createsuperuser ''' user = self.model() user.name = 'admin-yeah' user.email = self.normalize_email(email=email) user.set_password(password) user.is_staff = True user.is_superuser = True user.save() return user class UserModel(AbstractBaseUser, PermissionsMixin): ## Personnal fields. email = models.EmailField(max_length=254, unique=True) name = models.CharField(max_length=16) ## [...] ## Django manage fields. date_joined = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELD = ['email', 'name'] objects = UserModelManager() def __str__(self): return self.email def get_short_name(self): return self.name[:2].upper() def get_full_name(self): return self.name forms.py class SignUpForm(UserCreationForm): email = forms.EmailField(required=True, help_text='البريد الإلكترونى الخاص بك - يجب ان يكون حقيقى (يستخدم لتسجيل الدخول) ') name = forms.CharField(required=True, help_text='إسمك الحقيقى - سيظهر كأسم البائع') password1 = forms.CharField(widget=forms.PasswordInput, help_text='كلمة المرور - حاول ان تكون سهلة التذكر بالنسبة لك') password2 = forms.CharField(widget=forms.PasswordInput, help_text='تأكيد كلمة المرور - إكتب نفس كلمة المرور السابقة مرة أخرى') class Meta: model = UserModel fields = ('email','name', 'password1', 'password2', ) labels = { 'name': 'إسمك الحقيقى - سيظهر كأسم البائع', 'email': 'البربد الإلكترونى Email', 'password1': 'كلمة المر…
has answer: http://stackoverflow.com/a/53902939
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0

http://stackoverflow.com/comment/88951978
type: QuestionComment
comment on: http://stackoverflow.com/q/50977948
has text: Did you use the same language/stopwords/stemming? did you filter emoticons, images, http[s]-links? BTW: What's the corpus?
score: 0
type: Comment

http://stackoverflow.com/q/50897987
has comment: http://stackoverflow.com/comment/88795744
linked to: http://stackoverflow.com/q/6947413
has comment: http://stackoverflow.com/comment/88795750
has comment: http://stackoverflow.com/comment/88796140
favorite count: 0
has body: I'm been struggling with this problem pretty long. I have to communicate with an Arduino and C++ program. I know it is easy in Python, but it has to be in C++ for school project. So I'm reading a lot of things, but no one help me further. So I have a short Python script that communicate with the arduino very well and fast written in Python. communication.py: import serial ser = serial.Serial('/dev/ttyACM0', 9600) def communicate(number): ser.write(number) return ser.readline() The Arduino gets the number and returns values of light sensors in a string. Now I want this to communicate with C++ program. My C++ code (this is only a small part of the full program) mainwindow.cpp: void MainWindow::run(){ while (ui-&gt;startstop-&gt;value() == 1){// as long that the program must run blockchange = 0; // get data from arduino Py_Initialize(); const char* modulename = "communication"; PyObject *pName = PyUnicode_FromString(modulename); PyObject *pModule = PyImport_Import(pName); if (pModule != NULL){ PyObject *pDict = PyModule_GetDict(pModule); PyObject *pFunc = PyDict_GetItem(pDict, PyUnicode_FromString("communicate")); if (pFunc != NULL){ PyObject_CallObject(pFunc, PyLong_FromLong(blockchange)); }else{ std::cout &lt;&lt; "couldn't find func\n"; } }else{ std::cout &lt;&lt; "pyhton module not found\n"; } } It only gives "python module not found". Which means that PyImport_Import(pName) returns NULL. What is wrong? I use Ubuntu 18.04 and my standard version of Python is 3.5 and the program is written in Qt Creator. I tried a lot of things, also without Python, but I haven't found anything that works. I only want that my Arduino reads one int from 0 to 6, and that the C++ program reads a string of 6 numbers separated with a ",".
upvote count: 2
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/18108932
has title: Communicate C++ program with Arduino through Python
tagged with: c++
has comment: http://stackoverflow.com/comment/88795716
answer count: 0
score: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88795941
has comment: http://stackoverflow.com/comment/88795703
has comment: http://stackoverflow.com/comment/88795778

http://stackoverflow.com/comment/88985542
has text: Couldn't you put that method in a loop to write over each cell in your desired range?
comment on: http://stackoverflow.com/q/50995127
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/50991261
type: UnansweredQuestion
tagged with: bcrypt
tagged with: python
has body: While trying to write a login functionality in flask, I wanted to try 'bcrypt' flask extensio. When I use_bcrypt.check_password_hash()_ method to compare user form input password against that users saved password in the db, it always returns false. Here is the code I use to generate passwords: hashPwd = bcrypt.generate_password_hash('form.password.data') Here is the code I use to check the candidate password against the saved one: if form.validate_on_submit(): user = User.query.filter_by(username=form.username.data).first() if user and bcrypt.check_password_hash(user.password, form.password.data): login_user(user, remember=form.rememberMe.data) If I do User.query.get(1).password in python shell, the password is in format: u'$2b$12$JOXUftWBbn/egABOkAYNwezGKfh6GzIHOofUnvx73AiSOfoNWEGFC' When I run the same query in code, the password is: $2b$12$JOXUftWBbn/egABOkAYNwezGKfh6GzIHOofUnvx73AiSOfoNWEGFC The u' in the first pw is the only difference and that might be the issue cause, but I dont know what it is. Any ideas?
score: 3
has comment: http://stackoverflow.com/comment/88977257
downvote count: 0
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/50991421
tagged with: flask
upvote count: 3
has comment: http://stackoverflow.com/comment/137064328
favorite count: 0
has answer: http://stackoverflow.com/a/76589228
has title: Flask bcrypt.check_password_hash() always returns False, can't narrow in on my mistake

http://stackoverflow.com/comment/88866657
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50933839
has text: Yeah it's still running when it fails to continue updating. When it's reopened it shows the correct delay instantly too so even if it lost connection at some point it's must only be briefly. From what I can tell it should resume updating when it regains network connection.
score: 0

http://stackoverflow.com/comment/88736315
type: Comment
type: QuestionComment
has text: Does it need to be random? How "random"?
score: 1
comment on: http://stackoverflow.com/q/50867030

http://stackoverflow.com/comment/88742085
score: 0
type: Comment
type: QuestionComment
has text: Did you try deleting the string in your code and typing it from the scratch? Just in case it really contains the "backspace" character and your code editor is not showing it.
comment on: http://stackoverflow.com/q/50861080

http://stackoverflow.com/comment/88904803
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50941424
score: 0
has text: @ekhumoro so i dont need to decode ?

http://stackoverflow.com/q/50917211
has answer: http://stackoverflow.com/a/50917368
tagged with: python
tagged with: merge
type: AnsweredQuestion
has title: Pandas Merge and Sum Data Frames
score: 1
upvote count: 1
has body: I have the following data frames: Data Frame 1: ID1,ID2,VAL1,VAL2 CAR,RED,5,5 TRUCK,RED,6,6 CAR,BLUE,1,1 Data Frame 2: ID1,ID2,VAL1,VAL2 BIKE,RED,5,5 TRUCK,BLACK,6,6 CAR,RED,1,1 I want to left join these two data frames on the key = {ID1, ID2}. But I also want to sum the values {VAL1, VAL2}. So for instance, the output would be: ID1,ID2,VAL1,VAL2 CAR,RED,6,6 TRUCK,RED,6,6 CAR,BLUE,1,1 I've tried all sorts of combinations of pandas.merge and have had no luck. Can someone help me out?
type: Question
accepted answer: http://stackoverflow.com/a/50917368
tagged with: join
answer count: 1
downvote count: 0
favorite count: 0
tagged with: pandas

http://stackoverflow.com/comment/89000217
comment on: http://stackoverflow.com/q/51003119
score: 0
type: Comment
type: QuestionComment
has text: @martineau i liked this solution very much

http://stackoverflow.com/a/50971437
downvote count: 0
type: Answer
has body: This should work (if i've understood correctly) def f(column): ... # function you want to apply to each column data = [f(column) for matrix in x for column in matrix.T] It's a double for loop, equivalent to (but faster than) data = [] for matrix in x: # iterate through every matrix in the list for column in matrix.transpose(): # iterate through every column in the matrix data.append(f(column))
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50971064
has comment: http://stackoverflow.com/comment/88939849

http://stackoverflow.com/q/50900055
upvote count: 1
downvote count: 1
answer count: 7
has title: Printing a multiplication table with nested loops?
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50900079
has answer: http://stackoverflow.com/a/50900244
has comment: http://stackoverflow.com/comment/88800092
possible better answer: http://stackoverflow.com/a/50900103
accepted answer: http://stackoverflow.com/a/50900244
tagged with: python
has body: I'm having a really hard time trying to figure out this exercise. Print the 2-dimensional list mult_table by row and column. Hint: Use nested loops. Sample output for the given program: 1 | 2 | 3 2 | 4 | 6 3 | 6 | 9 This is the code that I have so far mult_table = [ [1, 2, 3], [2, 4, 6], [3, 6, 9] ] for row in mult_table: for num in row: print(num,' | ',end='|') print() What I get is this 1 ||2 ||3 || 2 ||4 ||6 || 3 ||6 ||9 || I have no idea what I'm doing wrong! I have also tried to do end=' ' but that still leaves a space and | at the end of each row. Please help. I am using Python 3 btw.
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/63872736
has answer: http://stackoverflow.com/a/70516759
type: Question
has answer: http://stackoverflow.com/a/66924999
has answer: http://stackoverflow.com/a/62564537
has answer: http://stackoverflow.com/a/50900103
score: 0

http://stackoverflow.com/q/50861567
tagged with: python-requests
has title: Download CSV from API Call in Python 3 with Requests
type: Question
tagged with: decode
accepted answer: http://stackoverflow.com/a/50861782
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
has body: Im connecting to a third party site to try and download data that is specific to my company. I am posting the required fields and the file is genereated, however, the URL to where the csv is located doesnt have .csv in the link. When I try to get the contents of the site, its only 'b'\xef\xbb\xbf'' download = r.get('http://XXXXXapi-b.XXXstage.com/reporting/Reports?id='+str(requestID), auth=('XXXXX','XXXXX')) print(download) print(download.headers) print(download.content) content = download.content print(content.decode('UTF-8')) the request Id was defined earlier when the request was submitted. The repsonses I get: Response [200] {'Cache-Control': 'no-cache', 'Pragma': 'no-cache', 'Content- Length': '3', 'Content-Type': 'text/csv', 'Expires': '-1', 'Content-Disposition': 'attachment; filename=Report.csv', 'Access-Control-Allow-Origin': '*', 'Date': 'Thu, 14 Jun 2018 14:17:46 GMT'} b'\xef\xbb\xbf' - Am I looking at this incorrectly? Does that content need to be decoded,is there even content? Is the content length mean that there are really only 3 results. Finally, is there a way to download the csv from this get or should the csv data be in the contents?
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/50861782
tagged with: python
type: AnsweredQuestion
score: 1
upvote count: 1

http://stackoverflow.com/a/50925411
has body: You are attempting to print a generator expression. This is not possible. The parentheses, or lack thereof, indicate a generator expression in Python. Instead, you can use a list, indicated by square brackets: n = 10 print([i for i in range(1, n+1)]) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] If you wish to print the contents of a generator expression, you can iterate explicitly: n = 10 for i in (i for i in range(1, n+1)): print(i) Or via unpacking the expression and using the sep argument: n = 10 print(*(i for i in range(1, n+1)), sep='') 12345678910 In this specific example, since you are exhausting the iterator, you can pass a range object directly: n = 10 print(*range(1, n+1), sep='') 12345678910 The * operator is used for sequence unpacking. It can take any iterable and pass unpacked components to a feeder function, in this case print. It works for print as this specific function can take an arbitrary number of arguments, e.g. try print(1, 2, 3, 4, 5, sep=''). It will not, in contrast, work with list, which requires only one argument.
score: 9
upvote count: 9
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50925366
type: Answer
accepted answer of: http://stackoverflow.com/q/50925366

http://stackoverflow.com/q/50872534
upvote count: 1
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/88746904
tagged with: python
accepted answer: http://stackoverflow.com/a/50872620
downvote count: 0
possible better answer: http://stackoverflow.com/a/50872768
has body: I have two CSV files called master_registry.csv and master_reference.csv. By using those CSV I have created some new data frames called 'df' and 'df2'. By combining those 'df' and 'df2' data frames I have created a new data frame called 'new_df'. The problem is I want to find a value is inside this 'new_df' data frame. But when I'm trying to get the result It gives me an error. This is the code # reading csv from the directory df = pd.read_csv('application/master_registry.csv') df2 = pd.read_csv('application/master_reference.csv') # filtering some selected columns form the csv df = df.filter(items=['Master_ID', 'Provider First Name', 'Provider Middle Name', 'Provider Last Name (Legal Name)', 'Provider Credential Text', 'Provider Gender Code','Provider License Number State Code_1', 'Provider Business Practice Location Address City Name']) # creating new data frame with "full name" column df['Full_Name'] = df'Provider First Name', 'Provider Last Name (Legal Name)'.apply(lambda x: ' '.join(x), axis=1) new_df = df.set_index('Master_ID').join(df2.set_index('Master_ID')) # selecting rows according to the external values main = new_df[(new_df['Master_ID']==master_id)] print(main.values.tolist()) When I try the above code It gives me this error. C:\Users\ChampsoftWK26\Envs\jerich_core\lib\site-packages\pandas\core\ops.py:1164: FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison result = method(y) [2018-06-15 14:36:07,148] ERROR in app: Exception on /search/manual/results/by_npi [POST] Traceback (most recent call last): File "C:\Users\ChampsoftWK26\Envs\jerich_core\lib\site-packages\flask\app.py", line 2292, in wsgi_app response = self.full_dispatch_request() File "C:\Users\ChampsoftWK26\Envs\jerich_core\lib\site-packages\flask\app.py", line 1815, in full_dispatch_request rv = self.handle_user_exception(e) File "C:\Users\ChampsoftWK26\Envs\jerich_core\lib\site-packages\flask\app.py", line 1718, in …
has comment: http://stackoverflow.com/comment/88746730
has answer: http://stackoverflow.com/a/50872768
has answer: http://stackoverflow.com/a/50872620
has comment: http://stackoverflow.com/comment/88746785
type: AnsweredQuestion
score: 1
type: Question
has comment: http://stackoverflow.com/comment/88746907
has comment: http://stackoverflow.com/comment/88747071
answer count: 2
has title: How do I search if a value is inside the data frame
favorite count: 0
has comment: http://stackoverflow.com/comment/88746967
tagged with: pandas

http://stackoverflow.com/q/50890686
linked to: http://stackoverflow.com/q/50083638
has comment: http://stackoverflow.com/comment/88782952
tagged with: scrapy
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50927153
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/50891066
type: Question
has body: In my following file Reddit.py, it has this Spider: import scrapy class RedditSpider(scrapy.Spider): name = 'Reddit' allowed_domains = ['reddit.com'] start_urls = ['https://old.reddit.com'] def parse(self, response): for link in response.css('li.first a.comments::attr(href)').extract(): yield scrapy.Request(url=response.urljoin(link), callback=self.parse_topics) def parse_topics(self, response): topics = {} topics["title"] = response.css('a.title::text').extract_first() topics["author"] = response.css('p.tagline a.author::text').extract_first() if response.css('div.score.likes::attr(title)').extract_first() is not None: topics["score"] = response.css('div.score.likes::attr(title)').extract_first() else: topics["score"] = "0" if int(topics["score"]) &gt; 10000: author_url = response.css('p.tagline a.author::attr(href)').extract_first() yield scrapy.Request(url=response.urljoin(author_url), callback=self.parse_user, meta={'topics': topics}) else: yield topics def parse_user(self, response): topics = response.meta.get('topics') users = {} users["name"] = topics["author"] users["karma"] = response.css('span.karma::text').extract_first() yield users yield topics What it does that it gets all the URLs from the main page of old.reddit, Then scrape each URL's title, author and score. What I've added to it is a second part, Where it checks if the score is higher than 10000, If it is, Then the Spider goes to the user's page and scrape his karma from it. I do understand that I can scrape the karma from the topic's page, But I would like to do it this way, Since there is other part of the user's page I scrape That doesn't exist in the topic's page. What I want to do is to export the topics list which contains title, author, score into a JSON file named topics.json, Then if the topic's score is higher than 10000 to export the users list which contains name, karma into a JSON file named users.json. I only know how to use the command-line of scrapy runspider Reddit.py -o Reddit.js…
has comment: http://stackoverflow.com/comment/88783275
answer count: 2
has title: How can I get this Spider to export a JSON file for each Items List?
possible better answer: http://stackoverflow.com/a/50891066
score: 0
has answer: http://stackoverflow.com/a/50927153
tagged with: python
tagged with: python-3.x

http://stackoverflow.com/a/50974596
upvote count: 1
answers question: http://stackoverflow.com/q/50974128
has comment: http://stackoverflow.com/comment/88946605
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50974128
type: Answer
score: 1
has body: Plot inside the "for" loop: cmap = plt.get_cmap('PiYG') for i in range(80): z = np.concatenate((z,np.array([np.sin(x[i])**10 + np.cos(10 + y[i]*x[i]) * np.cos(x[i])]))) levels = MaxNLocator(nbins=15).tick_values(z.min(), z.max()) norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True) plt.pcolormesh(x, y, z, cmap=cmap, norm=norm) plt.show()

http://stackoverflow.com/comment/89975274
comment on: http://stackoverflow.com/a/51000045
has text: @mohsendppp: since you want to load all: what is wrong with `df = pd.read_json("review.json", ,lines=True)` ?
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/125052158
type: AnswerComment
has text: This will convert rgb to bgr too. So one must be careful when they are using both types of images.
type: Comment
score: 2
comment on: http://stackoverflow.com/a/70161454

http://stackoverflow.com/comment/89109338
type: QuestionComment
has text: Glad you got it working. Restyling the fields is a completely different question. I can't help you with that.
comment on: http://stackoverflow.com/q/50970667
score: 0
type: Comment

qwidget
tag name: qwidget
type: Tag
tags question: http://stackoverflow.com/q/50892264

http://stackoverflow.com/q/50975346
has comment: http://stackoverflow.com/comment/88946943
tagged with: in-place
has answer: http://stackoverflow.com/a/50975367
tagged with: python
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/88947148
has comment: http://stackoverflow.com/comment/88947416
has comment: http://stackoverflow.com/comment/88946797
type: UnansweredQuestion
has body: If I try to modify the 'board' list in-place in the way below, it doesn't work, it seems like it generate some new 'board' instead of modify in-place. def func(self, board): """ :type board: List[List[str]] """ board = [['A' for j in range(len(board[0]))] for i in range(len(board))] return I have to do something like this to modify it in-place, what's the reason? Thanks. for i in range(len(board)): for j in range(len(board[0])): board[i][j] = 'A'
has comment: http://stackoverflow.com/comment/88946905
has answer: http://stackoverflow.com/a/50975581
type: Question
has title: About the way to modify the list in-place in a function in Python

http://stackoverflow.com/a/50884362
type: Answer
accepted answer of: http://stackoverflow.com/q/50883019
answers question: http://stackoverflow.com/q/50883019
has body: if username_guess.get() == username: tkMessageBox.showinfo("COMPLETE", "You Have Now Logged In.", icon="info") After this line, you can call root.deiconify() to show the root window, and top.destroy() to kill the login window.
type: AcceptedAnswer
score: 0

http://stackoverflow.com/q/50895010
has comment: http://stackoverflow.com/comment/88790229
has comment: http://stackoverflow.com/comment/88790246
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50895056
accepted answer: http://stackoverflow.com/a/50895082
has answer: http://stackoverflow.com/a/50895056
has comment: http://stackoverflow.com/comment/88790122
type: Question
answer count: 2
linked to: http://stackoverflow.com/q/22697773
score: 0
has title: Reading text file using read_csv with regex dilimiter
tagged with: pandas
has answer: http://stackoverflow.com/a/50895082
tagged with: python
has body: I've been trying to read a text file university_towns.txt using read_csv, but as shown in the screenshot, on parsing the file using the regex delimiter as shown in the code below , I get an error of : ParserError: Expected 2 fields in line 89, saw 3. Error could possibly be due to quotes being ignored when a multi-char delimiter is used. Is there any way to fix this, it seems only the double quotes are at fault at one place , also kindly explain why this is happening? I also tried to use the quotechar argument, but didn't understand how to use it. My code for reading the file is as below: university_towns = pd.read_csv('university_towns.txt', sep= "\s\(", engine='python', header=None) university_towns.txt file image Annville (Lebanon Valley College)[2] Bethlehem (Lehigh University, Moravian College) Bloomsburg (Bloomsburg University of Pennsylvania)[2] Bradford (University of Pittsburgh at Bradford) California (California University of Pennsylvania)[2] Carlisle (Dickinson College) Cecil B. Moore, Philadelphia, also known as "Templetown" (Temple University) Clarion (Clarion University of Pennsylvania)[2] Collegeville (Ursinus College) Cresson (Mount Aloysius College)[2] East Stroudsburg (East Stroudsburg University of Pennsylvania)[2] Edinboro (Edinboro University of Pennsylvania)[2] Erie (Gannon University, Mercyhurst College, Penn State Erie) Gettysburg (Gettysburg College)[2] Greensburg (Seton Hill University, University of Pittsburgh at Greensburg) Grove City (Grove City College)[2] Huntingdon (Juniata College)[2] Indiana (Indiana University of Pennsylvania)[2] Johnstown (University of Pittsburgh at Johnstown) Kutztown (Kutztown University of Pennsylvania)[2] Lancaster (Franklin &amp; Marshall) Carrollton (University of West Georgia)[2]*Dahlonega (North Georgia College &amp; State University)[2] Above I've pasted some of the lines for the text file. Also, the last line is line 89.

http://stackoverflow.com/a/50895628
accepted answer of: http://stackoverflow.com/q/50895468
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50895468
type: Answer
score: 2
upvote count: 2
has body: This is not really a pandas question, as the pandas.to_excel function has very little to do with the formatting and markup used in the excel sheet. You can look at xlsxwriter which specifically formats xlsx files. This is a sample code for formatting hyperlinks, it is adapted from the documentation where you can read more. ############################################################################### # # Example of how to use the XlsxWriter module to write hyperlinks # # Copyright 2013-2018, John McNamara, jmcnamara@cpan.org # import xlsxwriter # Create a new workbook and add a worksheet workbook = xlsxwriter.Workbook('hyperlink.xlsx') worksheet = workbook.add_worksheet('Hyperlinks') # Format the first column worksheet.set_column('A:A', 30) # Add a sample alternative link format. red_format = workbook.add_format({ 'font_color': 'red', 'bold': 1, 'underline': 1, 'font_size': 12, }) # Write some hyperlinks worksheet.write_url('A1', 'http://www.python.org/') # Implicit format. worksheet.write_url('A3', 'http://www.python.org/', string='Python Home') worksheet.write_url('A5', 'http://www.python.org/', tip='Click here') worksheet.write_url('A7', 'http://www.python.org/', red_format) worksheet.write_url('A9', 'mailto:jmcnamara@cpan.org', string='Mail me') # Write a URL that isn't a hyperlink worksheet.write_string('A11', 'http://www.python.org/') workbook.close()

http://stackoverflow.com/q/50991334
has comment: http://stackoverflow.com/comment/88977802
has title: Taking arguments
tagged with: function
has comment: http://stackoverflow.com/comment/88978043
tagged with: http://stackoverflow.com/tag/c
score: 0
has body: I am trying to create a Python extension that takes arguements. This is my script: #include &lt;Python.h&gt; static PyObject * _message(PyObject *self, PyObject *args) { char *title, *message; if (!PyArg_ParseTuple(args, &amp;title, &amp;message)) return NULL; // Throw an error return Py_BuildValue(""); } static PyMethodDef methods[] = { {"Message", (PyCFunction) _message, METH_VARARGS, "Message(title, message) Take a message"}, {NULL, NULL, 0, NULL} }; static struct PyModuleDef functions = { PyModuleDef_HEAD_INIT, "test", "Take a message", "-1", methods }; PyMODINIT_FUNC PyInit_test(void) { PyObject *module = PyModule_Create(&amp;functions); return module; } Setup.py: from setuptools import setup, Extension module = Extension ( "test", sources = ['test.c']) setup( name = "test", version = "1.0", description = "Take message input", author = "Simon", ext_modules = [module]) However when I try to compile it I am left with an error: C:\Users\Simon\Desktop\PyTest&gt;python setup.py build running build running build_ext building 'test' extension C:\Program Files (x86)\Microsoft Visual Studio\2017\WDExpress\VC\Tools\MSVC\14.14.26428\bin\HostX86\x86\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MT -IC:\Users\Simon\AppData\Local\Programs\Python\Python36-32\include -IC:\Users\Simon\AppData\Local\Programs\Python\Python36-32\include "-IC:\Program Files (x86)\Microsoft Visual Studio\2017\WDExpress\VC\Tools\MSVC\14.14.26428\include" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\include\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17134.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17134.0\shared" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17134.0\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17134.0\winrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17134.0\cppwinrt" /Tctest.c /Fobuild\temp.win32-3.6\Release\test.obj test.c test.c(2): warning C4067: unexpected tokens following preprocessor directive - expected …
tagged with: arguments
has answer: http://stackoverflow.com/a/50991991
accepted answer: http://stackoverflow.com/a/50991991
has comment: http://stackoverflow.com/comment/88977465
has comment: http://stackoverflow.com/comment/88978374
has comment: http://stackoverflow.com/comment/88978617
tagged with: python
possible better answer: http://stackoverflow.com/a/50991822
tagged with: python-c-api
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50991822
has comment: http://stackoverflow.com/comment/88978462
has comment: http://stackoverflow.com/comment/88977957
linked to: http://stackoverflow.com/q/25337706
type: Question
answer count: 2

http://stackoverflow.com/comment/88859997
type: Comment
has text: I checked it. Ok thanks a lot. How to gain skill like you to solve any problem? How much experience do you have? How did u learn?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50872497

http://stackoverflow.com/q/50919517
tagged with: rolling-computation
tagged with: python
type: AnsweredQuestion
score: 2
tagged with: statsmodels
has answer: http://stackoverflow.com/a/70821246
type: Question
answer count: 2
downvote count: 0
has body: I have a DataFrame with two Series and I know how to get their cointegration using all data points... import pandas as pd import numpy as np import statsmodels.tsa.stattools as ts A = pd.Series(np.cumsum(np.random.normal(size=100)) + 50) B = pd.Series(A + 5 + np.random.normal(size=100)) ts.coint(A, B) However, I'd like to explore how this cointegration has changed over time by using a rolling window (let's say 60 days). How can I achieve this using a combination of statsmodels and pandas? Thanks in advance!
has title: Rolling statsmodels cointegration using pandas
has answer: http://stackoverflow.com/a/50920738
accepted answer: http://stackoverflow.com/a/50920738
tagged with: pandas
possible better answer: http://stackoverflow.com/a/70821246
favorite count: 0
upvote count: 2

http://stackoverflow.com/a/50958201
has body: Because you are using Apache, you can add to the Apache configuration the LimitRequestBody directive and specify the limit. The request will be rejected before it even gets to your Python code. https://httpd.apache.org/docs/2.4/mod/core.html#limitrequestbody
answers question: http://stackoverflow.com/q/50944442
score: 0
type: Answer

http://stackoverflow.com/q/50979415
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50979488
tagged with: mysql
tagged with: scrapy
type: Question
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/50979488
favorite count: 0
linked to: http://stackoverflow.com/q/51000140
tagged with: character
has title: MySQL statement python escape single quote '
upvote count: 2
tagged with: mysql-error-1064
has body: I have below MySQL statement with python but there is a single quote ' in one of the values hence I got below error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near L at line 1 The value to be inserted is Regal INT'L How to escape or to correct the MySQL statement? MySQL statement def query(self, item): return "INSERT INTO income_statement({columns}) VALUES ({values})".format( columns=', '.join(item.keys()), values=self.item_to_text(item) ) def item_to_text(self, item): return ', '.join("'" + str(v) + "'" for v in item.values() )
tagged with: python

http://stackoverflow.com/comment/88798764
score: 1
has text: It's very generous of Rory Daulton to lead you down the path, but you need to make more of an effort here, Rahul. This is one of the first chapters in an elementary physics text. Ordinary differential equations are certainly beyond introductory calculus. Euler integration would be good enough, now that we have computers where the small timesteps required for stability are not a hardship.
type: AnswerComment
comment on: http://stackoverflow.com/a/50896168
type: Comment

http://stackoverflow.com/comment/89000975
type: QuestionComment
has text: You can't accept more than one answer. Did you read all the answers to determine what was most helpful for you?
comment on: http://stackoverflow.com/q/51003564
score: 0
type: Comment

http://stackoverflow.com/a/50887221
accepted answer of: http://stackoverflow.com/q/50887187
answers question: http://stackoverflow.com/q/50887187
has comment: http://stackoverflow.com/comment/88776729
score: 4
upvote count: 4
type: AcceptedAnswer
downvote count: 0
has body: Django view should return httpresponse object. But your search view return form object instead. You can rewrite serch view to something like this to fix error: def search(request): if request.method == 'POST': form = SearchForm(data=request.POST) if form.is_valid(): #Do something for examlpe HttpResponseRedirect(reverse("name:second")) else: form = SearchForm() context = {} context['search_form'] = form return render(request, 'name/index.html', context)
type: Answer
has comment: http://stackoverflow.com/comment/88776785

http://stackoverflow.com/q/50934841
answer count: 1
tagged with: training-data
tagged with: scikit-learn
favorite count: 0
tagged with: python
has body: I am following this example to determine feature importance using Random Forests. When using numerous features and only a subset of these features, these are the results I observe, respectively: Is there a particular reason the error bars increase drastically when using all possible features? Is there any significance to a negative quantity? (Note: the particular labels on the x-axis in the two plots do not necessarily correspond.)
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50935459
upvote count: 1
downvote count: 1
type: Question
tagged with: feature-selection
tagged with: random-forest
has title: Error bars in feature selection increase when using more features?
score: 0
accepted answer: http://stackoverflow.com/a/50935459

http://stackoverflow.com/comment/89014409
comment on: http://stackoverflow.com/q/51010644
score: 0
has text: And also could you please specify reason for down voting, if you have one? I will modify the question if it needs to be.Thank you.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88967893
type: Comment
score: 3
comment on: http://stackoverflow.com/a/50986578
type: AnswerComment
has text: "when you do for i in L, then i is not the element of L itself, but a clone of it." => wrong. Well, mostly wrong... What `i` points to IS the list's element, but _rebinding_ the _name_ `i` doesn't change the list. See https://nedbatchelder.com/text/names.html for a more in-depth explanation.

http://stackoverflow.com/comment/88971693
comment on: http://stackoverflow.com/q/50988185
has text: no, they do not
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/88994800
comment on: http://stackoverflow.com/a/51000404
type: AnswerComment
score: 0
type: Comment
has text: Are you implying that I copied your answer?

web-scraping
tags question: http://stackoverflow.com/q/50924723
tags question: http://stackoverflow.com/q/50897213
tags question: http://stackoverflow.com/q/50949203
tags question: http://stackoverflow.com/q/50899824
tags question: http://stackoverflow.com/q/50971533
tags question: http://stackoverflow.com/q/50956573
tags question: http://stackoverflow.com/q/50944106
tags question: http://stackoverflow.com/q/50882896
tags question: http://stackoverflow.com/q/50911961
tags question: http://stackoverflow.com/q/50939921
tags question: http://stackoverflow.com/q/50863201
tags question: http://stackoverflow.com/q/50918071
tags question: http://stackoverflow.com/q/50957283
tags question: http://stackoverflow.com/q/51008798
tags question: http://stackoverflow.com/q/50898876
tags question: http://stackoverflow.com/q/50880811
tags question: http://stackoverflow.com/q/50894712
tags question: http://stackoverflow.com/q/50957861
tags question: http://stackoverflow.com/q/50855442
tags question: http://stackoverflow.com/q/50974695
tags question: http://stackoverflow.com/q/50967543
tags question: http://stackoverflow.com/q/50867356
tags question: http://stackoverflow.com/q/50866537
tags question: http://stackoverflow.com/q/50940424
tags question: http://stackoverflow.com/q/50897837
tags question: http://stackoverflow.com/q/50996122
tags question: http://stackoverflow.com/q/50870499
tags question: http://stackoverflow.com/q/50920152
tags question: http://stackoverflow.com/q/50959006
tags question: http://stackoverflow.com/q/50906465
tags question: http://stackoverflow.com/q/50870931
tags question: http://stackoverflow.com/q/51009982
tags question: http://stackoverflow.com/q/50882622
tags question: http://stackoverflow.com/q/50996404
tags question: http://stackoverflow.com/q/50873293
tags question: http://stackoverflow.com/q/50972112
tags question: http://stackoverflow.com/q/50980796
tags question: http://stackoverflow.com/q/51007603
tags question: http://stackoverflow.com/q/50912466
tags question: http://stackoverflow.com/q/51001782
tags question: http://stackoverflow.com/q/50919238
tags question: http://stackoverflow.com/q/50883369
tags question: http://stackoverflow.com/q/50862125
tag name: web-scraping
tags question: http://stackoverflow.com/q/50880175
tags question: http://stackoverflow.com/q/50909084
tags question: http://stackoverflow.com/q/50870393
type: Tag
tags question: http://stackoverflow.com/q/50914432
tags question: http://stackoverflow.com/q/50884181
tags question: http://stackoverflow.com/q/50894170
tags question: http://stackoverflow.com/q/50890519
tags question: http://stackoverflow.com/q/50884094
tags question: http://stackoverflow.com/q/50915665
tags question: http://stackoverflow.com/q/50914072
tags question: http://stackoverflow.com/q/50911887
tags question: http://stackoverflow.com/q/50897523
tags question: http://stackoverflow.com/q/51005742
tags question: http://stackoverflow.com/q/50998136
tags question: http://stackoverflow.com/q/50933724
tags question: http://stackoverflow.com/q/50884839
tags question: http://stackoverflow.com/q/50898312
tags question: http://stackoverflow.com/q/51009488
tags question: http://stackoverflow.com/q/50895680
tags question: http://stackoverflow.com/q/50920242
tags question: http://stackoverflow.com/q/50867153

http://stackoverflow.com/comment/88803937
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50895073
type: AnswerComment
has text: oh, I see in the middle now

http://stackoverflow.com/comment/88971645
has text: "but this seems like a nasty thing to do for this simple task." Seems like a simple solution for a simple task.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50988517
score: 4

http://stackoverflow.com/a/50948689
answers question: http://stackoverflow.com/q/50948490
has comment: http://stackoverflow.com/comment/88926041
has comment: http://stackoverflow.com/comment/88991381
downvote count: 0
type: Answer
has body: The newer regex module offers a "fuzzy" match possibility: import regex as re Test = ['ASDFGH', 'QWERTYU', 'ZXCVB'] Ref = ['ASDFGY', 'QWERTYI', 'ZXCAA', 'ASDFGI', 'ASDFGX'] for item in Test: rx = re.compile('(' + item + '){s&lt;=3}') for r in Ref: if rx.search(r): print(rf'{item} is similar to {r}') This yields ASDFGH is similar to ASDFGY ASDFGH is similar to ASDFGI ASDFGH is similar to ASDFGX QWERTYU is similar to QWERTYI ZXCVB is similar to ZXCAA You can control it via the {s&lt;=3} part which allows three or less substitutions. To have pairs, you could write pairs = [(origin, difference) for origin in Test for rx in [re.compile(rf"({origin}){{s&lt;=3}}")] for difference in Ref if rx.search(difference)] Which would yield for Test = ['ASDFGH', 'QWERTYU', 'ZXCVB'] Ref = ['ASDFGY', 'QWERTYI', 'ZXCAA', 'ASDFGI', 'ASDFGX'] the following output: [('ASDFGH', 'ASDFGY'), ('ASDFGH', 'ASDFGI'), ('ASDFGH', 'ASDFGX'), ('QWERTYU', 'QWERTYI'), ('ZXCVB', 'ZXCAA')]
score: 1
upvote count: 1

http://stackoverflow.com/q/50995707
tagged with: python
has answer: http://stackoverflow.com/a/50995856
possible better answer: http://stackoverflow.com/a/50995747
downvote count: 1
upvote count: 6
type: AnsweredQuestion
has title: Ignoring visible gpu device with compute capability 3.0. The minimum required Cuda capability is 3.5
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/56987465
accepted answer: http://stackoverflow.com/a/50995856
has body: I am running Tensorflow 1.5.0 on a docker container because i need to use a version that doesn't use the AVX bytecodes because the hardware i am running on is too old to support it. I finally got tensorflow-gpu to import correctly (after downgrading the docker image to tf 1.5.0) but now when i run any code to detect the GPU it says the GPU is not there. I looked at the docker log and Jupyter is spitting out this message Ignoring visible gpu device (device: 0, name: GeForce GTX 760, pci bus id: 0000:01:00.0, compute capability: 3.0) with Cuda compute capability 3.0. The minimum required Cuda capability is 3.5. The tensorflow website says that GPUs with compute capability of 3.0 is supported so why does it says it needs compute capability 3.5? Is there any way to get a docker image for tensorflow and jupyter that uses tf 1.5.0 but supports GPUs with compute capability?
tagged with: docker
answer count: 3
has answer: http://stackoverflow.com/a/50995747
favorite count: 0
score: 5

http://stackoverflow.com/a/50906634
has body: It is often not a good idea to adjust word2vec embeddings if you do not have sufficiently large corpus in your training. To clarify that, take an example where your corpus has television but not TV. Even though they might have word2vec embeddings, after training only television will be adjust and not TV. So you disrupt the information from word2vec. To solve this problem you have 3 options: You let the LSTM in the upper layer figure out what the word might mean based on its context. For example, I like choc. the LSTM can figure out it is an object. This was demonstrated by Memory Networks. Easy option, pre-process, canonicalise as much as you can before passing to the model. Spell checkers often capture these very well and are really fast. You can use character encoding along side word2vec. This is employed in many of the question answering models such as BiDAF where the character representation is merged with word2vec so you have some information relating characters to words. In this case, choc might be similar to chocolate.
type: Answer
answers question: http://stackoverflow.com/q/50906372
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/88963927
downvote count: 0

http://stackoverflow.com/a/50982420
has comment: http://stackoverflow.com/comment/88963571
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50982348
answers question: http://stackoverflow.com/q/50982348
has comment: http://stackoverflow.com/comment/88963482
has body: In Django 2.0 you can use query expresions with ordering: from django.db.models.functions import Length class IPv4Manage(models.Model): """ ipv4 """ ip = models.GenericIPAddressField(help_text="ip") ... class Meta: ordering = [Length('ip').asc()]
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 1

http://stackoverflow.com/comment/89007261
has text: @GenoChen With absolute path like this with open('/media/young/5e7be152-8ed5-483d-a8e8-b3fecfa221dc/text/mycodehtml/pracdl/golbin/TensorFlow-Tutorials/10_RNN/ChatBot/test.txt', 'r') as f:, it worked in VScode. Would you guide how to set VScode to find reletive path?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51006989

http://stackoverflow.com/a/50895319
type: Answer
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50892010
answers question: http://stackoverflow.com/q/50892010
has body: Fixed the TypeError: after figuring out that it was a compatibility problem, I tried to install djangorestframework 3.7.4 which is the first version supporting Django 2.0 (the versions 3.7.5, 3.7.6 and 3.7.7 are also compatible) N.B: I was using djangorestframework 3.8.2 Fixed the missing bootstrap.min.css 404 not found: I had this on my html : the correction was to change the link to : I thank you all for your support
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/q/50882499
favorite count: 0
type: UnansweredQuestion
tagged with: python
upvote count: 4
has title: inspect.ismethod() returns false for the instance method in the decorator
has comment: http://stackoverflow.com/comment/88767354
has body: I am trying to detect whether a function is instance method or it is module level function inside the python decorator using the inspect.ismethod(). It returns false for that. what is the reason? How do I detect whether the function is instance method or the module level function inside the decorator like below. Example: import inspect class A(object): @deco("somearg") def sample(self): print "abc" a = A() print inspect.ismethod(a.sample) # Returns True Above print returns true. My decorator is something like below. I need to pass the arguments to decorator in the actual code so it's inside the function: def deco(some_arg=None): def decorator(func): def wrapper(*args, **kwargs): print some_arg print inspect.ismethod(func) return wrapper return decorator Above inspect.ismethod() returns false. My python version is 2.7.13
type: Question
score: 4
has answer: http://stackoverflow.com/a/50882573
answer count: 1
downvote count: 0
tagged with: python-decorators

http://stackoverflow.com/q/50971083
tagged with: python
has comment: http://stackoverflow.com/comment/88956679
answer count: 0
has comment: http://stackoverflow.com/comment/88940208
has body: Please help me about how to register task on celery. Error log is: [2018-06-21 23:23:20,288: ERROR/MainProcess] Received unregistered task of type 'projects.tasks.hoge'. The message has been ignored and discarded. Did you remember to import the module containing this task? Or maybe you're using relative imports? Please see http://docs.celeryq.org/en/latest/internals/protocol.html for more information. The full contents of the message body was: b'[[2, true], {}, {"callbacks": null, "errbacks": null, "chain": null, "chord": null}]' (84b) Traceback (most recent call last): File "/home/ec2-user/.pyenv/versions/3.6.2/lib/python3.6/site-packages/celery/worker/consumer/consumer.py", line 561, in on_task_received strategy = strategies[type_] KeyError: 'project.tasks.hoge' It worked fine on different environment and same source code. Does anyone know why this occured?
tagged with: celery
type: Question
score: 0
has title: Task is not applying on Celery
has comment: http://stackoverflow.com/comment/89085639
type: UnansweredQuestion
tagged with: django

http://stackoverflow.com/comment/88767056
has text: use `str(your_float)`
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50882377

http://stackoverflow.com/q/50975543
favorite count: 0
tagged with: dask
has body: The following example doesn't work, unless asynchronous keyword is not used in Localcluster. I would like to control how many processes/workers are used and process functions in parallel and print the results as they are ready. What needs to be changed? import time from dask.distributed import Client, LocalCluster, as_completed def wait(sec): time.sleep(sec) return sec def main(): cluster = LocalCluster(n_workers=2, ncores=2, asynchronous=True) inputs = [5, 7, 3, 1] client = Client(cluster) futures = client.map(wait, inputs) for future, result in as_completed(futures, with_results=True): print(result) client.close() if __name__ == '__main__': main()
tagged with: python
type: AnsweredQuestion
has title: Dask async processing, print results as they arrive
score: 1
has answer: http://stackoverflow.com/a/50978379
accepted answer: http://stackoverflow.com/a/50978379
upvote count: 1
tagged with: cluster-computing
type: Question
answer count: 1
downvote count: 0
tagged with: asynchronous

http://stackoverflow.com/q/50949794
favorite count: 0
has answer: http://stackoverflow.com/a/50949985
tagged with: multidimensional-array
type: Question
tagged with: python
answer count: 1
has title: Why aren't my data being masked?
has comment: http://stackoverflow.com/comment/88897556
has comment: http://stackoverflow.com/comment/88897186
upvote count: 1
accepted answer: http://stackoverflow.com/a/50949985
tagged with: numpy
has comment: http://stackoverflow.com/comment/88897795
has body: data = [[0, 1, 1, 5, 5, 5, 0, 2, 2, 2, 2, 2, 2, 2, 6, 6, 6, 6, 6, 6, 6, 6], [1, 1, 1, 0, 5, 5, 5, 0, 2, 2, 0, 0, 2, 0, 0, 6, 6, 6, 0, 0, 6, 6], [1, 1, 1, 0, 0, 0, 0, 0, 2, 2, 0, 2, 2, 2, 0, 0, 2, 6, 0, 0, 6, 6]] The data object i have is a &lt;class 'numpy.ndarray'&gt; Knowing data is a numpy object i did the following: data = np.array(data) i want to set the numbers inside a list i give as input to 0, what i tried: data[~np.isin(data,[2,4])] = 0 i expect all the 2 and 4 occurrences in the previous matrix to be 0 and the rest to keep their values, what i got: TypeError: only integer scalar arrays can be converted to a scalar index also tried to give data as a numpy array using np.array gave error as well.
downvote count: 0
has comment: http://stackoverflow.com/comment/88897123
type: AnsweredQuestion
score: 1

http://stackoverflow.com/q/51002646
upvote count: 1
tagged with: ipython
tagged with: scrapy
has body: I am using iPython with Scrapy shell inside a virtualenv, but I can't save my project's variables (they get deleted everytime I leave the project) and %store won't work, returning "Line magic function %store not found". Currently, I have Python 2.7.12, iPython 5.7.0 and Scrapy 1.5.0, all working inside a virtualenv. There are some questions here about similar errors, such as this one, but I could not find a solution regarding storemagic/persistence specifically. Maybe this issue I am facing has something to do with running it from a virtual environment? I would like to add persistence to those variables, so they can later be called from a Scrapy spider. Reading the iPython documentation, I figured out storemagic was the way to do it, but it won't work for me inside Scrapy shell. Is there another way to do that? I can't figure out what's going on, would appreciate some help. Thanks
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/89008492
has comment: http://stackoverflow.com/comment/89008526
has title: Line magic function `%store` not found
tagged with: virtualenv
tagged with: storemagic
favorite count: 0
has comment: http://stackoverflow.com/comment/89001128
type: UnansweredQuestion
tagged with: python
answer count: 0
linked to: http://stackoverflow.com/q/31735624
score: 1

http://stackoverflow.com/a/50885267
has body: Inside the drop_duplicates() method of Dataframe you can provide a series of column names to eliminate duplicate records from your data. The following "Tested" code does the same : import pandas as pd df = pd.DataFrame() df.insert(loc=0,column='Column1',value=['cat', 'toy', 'cat']) df.insert(loc=1,column='Column2',value=['bat', 'flower', 'bat']) df.insert(loc=2,column='Column3',value=['xyz', 'abc', 'lmn']) df = df.drop_duplicates(subset=['Column1','Column2'],keep='first') print(df) Inside of the subset parameter, you can insert other column names as well and by default it will consider all the columns of your data and you can provide keep value as :- first : Drop duplicates except for the first occurrence. last : Drop duplicates except for the last occurrence. False : Drop all duplicates.
score: 1
answers question: http://stackoverflow.com/q/50885093
upvote count: 1
downvote count: 0
type: Answer

http://stackoverflow.com/q/50940542
tagged with: oop
has comment: http://stackoverflow.com/comment/88878898
score: -1
tagged with: class
has answer: http://stackoverflow.com/a/50940851
answer count: 3
has title: Why this code does print 28?
favorite count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/50940851
has body: This code prints 28 as an answer. I try to understand what's going on in the background, but cannot figure it out. I kindly ask, If you can, please explain. class Geom(object): def __init__(self, h=10, w=10): self.h, self.w =h,w def rectangle(self): rect = self.h*2+self.w*2 return rect a = Geom(4) print(a.rectangle()) &gt;&gt;28
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50940592
downvote count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/50940592
has answer: http://stackoverflow.com/a/50940634
type: Question

http://stackoverflow.com/a/50938015
type: Answer
answers question: http://stackoverflow.com/q/50937966
has comment: http://stackoverflow.com/comment/88874562
accepted answer of: http://stackoverflow.com/q/50937966
has body: While you shouldn't be creating a map object just for side effects, there is in fact a standard recipe for consuming iterators in the itertools docs: def consume(iterator, n=None): "Advance the iterator n-steps ahead. If n is None, consume entirely." # Use functions that consume iterators at C speed. if n is None: # feed the entire iterator into a zero-length deque collections.deque(iterator, maxlen=0) else: # advance to the empty slice starting at position n next(islice(iterator, n, n), None) For just the "consume entirely" case, this can be simplified to def consume(iterator): collections.deque(iterator, maxlen=0) Using collections.deque this way avoids storing all the elements (because maxlen=0) and iterates at C speed, without bytecode interpretation overhead. There's even a dedicated fast path in the deque implementation for using a maxlen=0 deque to consume an iterator. Timing: In [1]: import collections In [2]: x = range(1000) In [3]: %%timeit ...: i = iter(x) ...: for _ in i: ...: pass ...: 16.5 µs ± 829 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) In [4]: %%timeit ...: i = iter(x) ...: collections.deque(i, maxlen=0) ...: 12 µs ± 566 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) Of course, this is all based on CPython. The entire nature of interpreter overhead is very different on other Python implementations, and the maxlen=0 fast path is specific to CPython. See abarnert's answer for other Python implementations.
has comment: http://stackoverflow.com/comment/88874488
has comment: http://stackoverflow.com/comment/126619539
has comment: http://stackoverflow.com/comment/126621721
upvote count: 33
has comment: http://stackoverflow.com/comment/126621839
has comment: http://stackoverflow.com/comment/126621608
has comment: http://stackoverflow.com/comment/126755978
has comment: http://stackoverflow.com/comment/126755892
score: 33
has comment: http://stackoverflow.com/comment/88874333
has comment: http://stackoverflow.com/comment/126755901
has comment: http://stackoverflow.com/comment/88874504
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/126755897

http://stackoverflow.com/comment/88884654
type: AnswerComment
has text: @KevinStephenBiswas, [Update your question](https://stackoverflow.com/posts/50934941/edit), please, with new input & desired output - I can't read code in comments.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/50935145

http://stackoverflow.com/q/50996642
score: 1
has body: One of the columns in my data frames are identifier names with a specific naming convention. When it was entered, it wasn't entered correctly. I wanted to ask how I can find specific keywords to input in its own column in python. Maybe some sort of loop? Example: types = ['XYZ', 'OPQ', 'MNO', 'ABC'] current df: ID ID Name 45 I_name_ls_XYZ_random 46 I_22_name_ABC_random 47 I_name_ls_XYZ_random_45 48 I_name_ls_MNO_random 49 I_ls_OPQ_random_name 50 I_name_ls_ABC_random 51 I_name_ls_XYZ_random 52 I_name_MNO_random Wanted result: ID ID Name types 45 I_name_ls_XYZ_random XYZ 46 I_22_name_ABC_random ABC 47 I_name_ls_XYZ_random_45 XYZ 48 I_name_ls_MNO_random MNO 49 I_ls_OPQ_random_name OPQ 50 I_name_ls_ABC_random ABC 51 I_name_ls_XYZ_random XYZ 52 I_name_MNO_random MNO
type: Question
has answer: http://stackoverflow.com/a/50996670
tagged with: dataframe
answer count: 2
has answer: http://stackoverflow.com/a/50996713
tagged with: pandas
upvote count: 1
tagged with: string
favorite count: 0
tagged with: series
has title: Create a column based on if a string is a substring in pandas Dataframe
type: UnansweredQuestion
tagged with: python
downvote count: 0

http://stackoverflow.com/comment/88984866
type: Comment
has text: oh I see. So this line of code "window.location.href = "?user=" + selectedUser" is in the JavaScript file.
comment on: http://stackoverflow.com/a/50994930
type: AnswerComment
score: 0

http://stackoverflow.com/comment/88764988
score: 0
comment on: http://stackoverflow.com/q/50881318
type: QuestionComment
type: Comment
has text: @anishtain4 Oh, sorry. The coordinates of `frame` are just the indexes. And not replace. I want to add it.

http://stackoverflow.com/a/50950131
has body: As mentioned in the comments, you have nested dictionaries, ie. you got to loop over them with e.g. for key, values in data.items() and then verify that the key corresponds to your product_name. see also iterating over dictionaries
type: Answer
answers question: http://stackoverflow.com/q/50947689
score: 0

gmail
type: Tag
tag name: gmail
tags question: http://stackoverflow.com/q/50981100

http://stackoverflow.com/q/50960539
linked to: http://stackoverflow.com/q/50109910
has title: How do I disable geckodriver's log on Selenium (Python 3)?
downvote count: 0
favorite count: 0
has body: I have not been able to find the answer to this. This particular answer only tells we can relocate it. How do I relocate/disable GeckoDriver's log file in selenium, python 3? Is there no way to permanently disable it?
has answer: http://stackoverflow.com/a/77124449
tagged with: python-3.x
type: Question
score: 12
answer count: 2
tagged with: geckodriver
tagged with: python
tagged with: selenium
has comment: http://stackoverflow.com/comment/88918031
tagged with: gecko
upvote count: 12
has answer: http://stackoverflow.com/a/56501199
type: UnansweredQuestion

http://stackoverflow.com/a/50916413
upvote count: 70
has comment: http://stackoverflow.com/comment/88833133
has comment: http://stackoverflow.com/comment/88834205
has comment: http://stackoverflow.com/comment/88833303
type: Answer
has comment: http://stackoverflow.com/comment/88833021
has comment: http://stackoverflow.com/comment/88833053
has comment: http://stackoverflow.com/comment/88833085
has comment: http://stackoverflow.com/comment/88832970
has comment: http://stackoverflow.com/comment/104633896
accepted answer of: http://stackoverflow.com/q/50915911
has body: The update_or_create(defaults=None, **kwargs) has basically two parts: the **kwargs which specify the "filter" criteria to determine if such object is already present; and the defaults which is a dictionary that contains the fields mapped to values that should be used when we create a new row (in case the filtering fails to find a row), or which values should be updated (in case we find such row). The problem here is that you make your filters too restrictive: you add several filters, and as a result the database does not find such row. So what happens? The database then aims to create the row with these filter values (and since defaults is missing, no extra values are added). But then it turns out that we create a row, and that the combination of the cluster and added already exists. Hence the database refuses to add this row. So this line: Model.objects.update_or_create(field1=val1, field2=val2, defaults={ 'field3': val3, 'field4': val4 }) Is to semantically approximately equal to: try: item = Model.objects.get(field1=val1, field2=val2) except Model.DoesNotExist: Model.objects.create(field1=val1, field2=val2, field3=val3, field4=val4) else: item = Model.objects.filter( field1=val1, field2=val2, ).update( field3 = val3 field4 = val4 ) (but the original call is typically done in a single query). You probably thus should write: Vmt.objects.update_or_create( cluster=c, creation_time='test creaetion time', defaults = { 'current_pm_active': 6, 'current_pm_total': 5, } ) (or something similar)
type: AcceptedAnswer
downvote count: 0
score: 70
answers question: http://stackoverflow.com/q/50915911
has comment: http://stackoverflow.com/comment/88833224

http://stackoverflow.com/comment/88777936
score: 0
has text: Googling your error message [brings up this](https://stackoverflow.com/a/30086501/8881141): " ..., these need to be in strictly ascending order. " Which `TT` obviously violates.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50888068

http://stackoverflow.com/comment/88785212
score: 0
type: QuestionComment
type: Comment
has text: couldn't you just call `subprocess.Popen(["C:\\Windows\\explorer.exe", folder_selected])`?
comment on: http://stackoverflow.com/q/50892257

http://stackoverflow.com/q/50946913
type: AnsweredQuestion
has title: MXNET reshape calling ctypes
score: 0
has body: Here trying to learn MXNET with “The Straight Dope”. On Linear Algebra - Tensors, I get ctypes error when running, X = nd.arange(24).reshape((2, 3, 4)) The error is, C:\Anaconda2\lib\site-packages\mxnet\ndarray\ndarray.pyc in reshape(self, *shape, **kwargs) 1060 c_array(ctypes.c_int64, shape), 1061 reverse, -&gt; 1062 ctypes.byref(handle))) 1063 return NDArray(handle=handle, writable=self.writable) 1064 WindowsError: exception: access violation writing 0x00007FFB00000000 Why is this happening and how can I solve it?
tagged with: machine-learning
type: Question
tagged with: ctypes
tagged with: neural-network
tagged with: mxnet
has answer: http://stackoverflow.com/a/50992681
answer count: 1
accepted answer: http://stackoverflow.com/a/50992681
tagged with: python

http://stackoverflow.com/comment/88950917
has text: your explanation is a little bit confused, some more information will be useful (`excelOut()` code? code working?...). I also think that you missed a `=` between `args` and `(dfc_data...`
comment on: http://stackoverflow.com/q/50977340
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89002223
score: 1
type: QuestionComment
type: Comment
has text: This is one of the reasons to stop using old-style printf formatting and switch to using [format strings](https://docs.python.org/3/library/string.html#formatstrings) or (when using Python 3.6+ and you are formatting in-situ using literals) [formatted string literals](https://docs.python.org/3/reference/lexical_analysis.html#f-strings).
comment on: http://stackoverflow.com/q/51004248

http://stackoverflow.com/q/50953377
has comment: http://stackoverflow.com/comment/88907107
type: UnansweredQuestion
tagged with: python
tagged with: selenium-webdriver
score: 2
downvote count: 0
tagged with: selenium
tagged with: google-chrome
has answer: http://stackoverflow.com/a/52036343
type: Question
has comment: http://stackoverflow.com/comment/88907077
has comment: http://stackoverflow.com/comment/88912014
upvote count: 2
has comment: http://stackoverflow.com/comment/88904703
answer count: 1
has body: So I'm running Selenium from Python on the Mac and running into an error with headless Chrome. Here is my headless chrome setup. I'm loading a default chrome profile that has one extension: ModHeader My setup is as follows chrome_options = webdriver.ChromeOptions() chrome_options.add_argument('headless') chrome_options.add_argument("--no-sandbox") chrome_options.add_argument('--disable-gpu') chrome_options.add_argument('--proxy-server=%s' % PROXY) chrome_options.add_argument("user-agent={}".format(USER_AGENT)) chrome_options.add_argument('--window-size=1420,1080') chrome_options.add_argument("user-data-dir=/Users/test/Library/Application Support/Google/Chrome/") driver = webdriver.Chrome(chrome_options=chrome_options) I want to use ProxyMesh with a specific IP address for requests. So I access localstorage to set the proper header in ModHeader driver.execute_script( "localStorage.setItem('profiles', JSON.stringify([{ " + " title: 'Selenium', hideComment: true, appendMode: '', " + " headers: [ " + " {enabled: true, name: 'X-ProxyMesh-IP', value: '%s', comment: ''}"%ip_address + " ], " + " respHeaders: [], " + " filters: [] " + "}])); ") The problem, which doesn't occur when I don't run headless Chrome, is that when I try to run the driver.execute_script I run into the following error. Message: move target out of bounds: Failed to read the 'localStorage' property from 'Window': Access is denied for this document. Are you not able to access localstorage using headless chrome? Is there something I need to change with my configuration? Any ideas would be appreciated?
has title: Accessing LocalStorage in Headless Chrome Using Selenium
favorite count: 0
has comment: http://stackoverflow.com/comment/88909268

http://stackoverflow.com/comment/88800467
type: QuestionComment
has text: Why do you have two identical models in the first place?
comment on: http://stackoverflow.com/q/50900153
score: 0
type: Comment

python-re
type: Tag
tag name: python-re
tags question: http://stackoverflow.com/q/50919509

http://stackoverflow.com/comment/88945316
type: Comment
comment on: http://stackoverflow.com/a/50974339
has text: @Vishal Sure thing. Glad we could help!
score: 0
type: AnswerComment

http://stackoverflow.com/a/50874007
has comment: http://stackoverflow.com/comment/88750265
has comment: http://stackoverflow.com/comment/88749831
has comment: http://stackoverflow.com/comment/88749891
answers question: http://stackoverflow.com/q/50873757
has body: That's pretty much the definition of 2D convolution. scipy has you covered. I copy a to preserve the borders; the convolution in valid mode will make a smaller array (without the borders), which I then paste inside the prepared "frame". import numpy as np from scipy.signal import convolve2d a = np.array([[100, 100, 100, 100, 100], [100, 0, 0, 0, 100], [100, 0, 0, 0, 100], [100, 0, 0, 0, 100], [100, 100, 100, 100, 100]]) b = np.array([[0, 0.25, 0], [0.25, 0, 0.25], [0, 0.25, 0]]) r = np.copy(a) r[1:-1, 1:-1] = convolve2d(a, b, mode='valid') r # =&gt; array([[100, 100, 100, 100, 100], # [100, 50, 25, 50, 100], # [100, 25, 0, 25, 100], # [100, 50, 25, 50, 100], # [100, 100, 100, 100, 100]])
has comment: http://stackoverflow.com/comment/88750341
has comment: http://stackoverflow.com/comment/88749562
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/88749507
score: 6
has comment: http://stackoverflow.com/comment/88749725
upvote count: 6
has comment: http://stackoverflow.com/comment/88749782

http://stackoverflow.com/q/50946163
has title: python re can't find this grouped name
score: 1
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/50948462
tagged with: named
has body: I try to give advice on the format of paper reference. For example, for academic dissertation, the format is: author. dissertation name[D]. place where store it: organization who hold the copy, year in which the dissertation published. obviously, there may be some punctuation in every items except for year. for example Smith. The paper name. The subtitle of paper[D]. United States: MIT, 2011 often, place where store it and year are missed, for example Smith. The paper name. The subtitle of paper[D]. US, 2011 Smith. The paper name. The subtitle of paper[D]. US: MIT I want to program like this: import re reObj = re.compile( r'.*\[D\]\. \s* ((?P&lt;PLACE&gt;[^:]*):){0,1} \s* (?P&lt;HOLDER&gt;[^:]*) (?P&lt;YEAR&gt;,\s*(1|2)\d{3}){0,1}', re.VERBOSE ) txt = '''Smith. The paper name. The subtitle of paper[D]. US: MIT, 2011 Smith. The paper name. The subtitle of paper[D]. US, 2011 Smith. The paper name. The subtitle of paper[D]. US: MIT'''.split('\n') for i in txt: if reObj.search(i): if reObj.search(i).group('PLACE')==None: print('missing place') if reObj.search(i).group('YEAR')==None: print('missing year') else: print('bad formation') but I found that no YEAR are gotten for i in txt: print(i) print(reObj.search(i).group('HOLDER')) outputs Smith. The paper name. The subtitle of paper[D]. US: MIT, 2011 MIT, 2011 Smith. The paper name. The subtitle of paper[D]. US, 2011 US, 2011 Smith. The paper name. The subtitle of paper[D]. US: MIT MIT for i in txt: print(i) print(reObj.search(i).group('YEAR')) outputs Smith. The paper name. The subtitle of paper[D]. US: MIT, 2011 None Smith. The paper name. The subtitle of paper[D]. US, 2011 None Smith. The paper name. The subtitle of paper[D]. US: MIT None So, why my named group fails and how to fix it? thanks
has comment: http://stackoverflow.com/comment/88889875
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/88959518
has answer: http://stackoverflow.com/a/50948462
type: AnsweredQuestion

http://stackoverflow.com/a/50942389
has comment: http://stackoverflow.com/comment/88882522
has comment: http://stackoverflow.com/comment/88883179
score: 0
accepted answer of: http://stackoverflow.com/q/50942277
type: Answer
has comment: http://stackoverflow.com/comment/88884885
has comment: http://stackoverflow.com/comment/88883258
has comment: http://stackoverflow.com/comment/88882356
has comment: http://stackoverflow.com/comment/88931384
has comment: http://stackoverflow.com/comment/88883467
has comment: http://stackoverflow.com/comment/88882486
has comment: http://stackoverflow.com/comment/88882535
has body: I suggest you to try to install it using pip / pip3. Create your conda environment, here's a random example: conda -create -n ENVIRONMENTNAME python=3.6 numpy pandas and then... If you are using Python2: pip install tfbio If you are using Pyton3: pip3 install tfbio
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88883517
answers question: http://stackoverflow.com/q/50942277
has comment: http://stackoverflow.com/comment/88885668

http://stackoverflow.com/q/50975586
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
answer count: 0
upvote count: 1
has title: tensorflow: comment in inception v3 image_processing.py makes no sense to me
tagged with: tensorflow
type: Question
score: 1
has comment: http://stackoverflow.com/comment/88948173
tagged with: deep-learning
has body: In image_preprocessing.image_preprocessing, the code ends: # Finally, rescale to [-1,1] instead of [0, 1) image = tf.subtract(image, 0.5) image = tf.multiply(image, 2.0) return image This makes no sense to me for two reasons. First, I can't figure out why the image prior to the rescale is in [0,1). It looks like the image will have been converted by decode_jpeg, which does the obvious thing, and then resized using tf.images.resize_images, which often converts to floats, but they seem to me to be in the range [0,256). Second, I can't figure out what good this linear rescale does in any event. It seems to me that if you want to rescale, you should probably do something like scikit-learn's StandardScaler, so that you reconvert the data to be zero-centered and have uniform standard deviation. Of course, that's probably a mistake here because the magnitude of color changes is useful in image recognition. My overall impression is that the comment is wrong, and that the code doing the "adjustment" is in fact irrelevant, because linear transformations don't matter before the first step of a CNN. Am I missing something?

http://stackoverflow.com/a/50987669
answers question: http://stackoverflow.com/q/50983996
score: 4
type: AcceptedAnswer
type: Answer
upvote count: 4
has body: For me, this code does work, but MJPG does round the odd resolution to an even resolution. H264 did not work with that resolution at all. int main(int argc, char* argv[]) { // start camera cv::VideoCapture cap(0); // read a single image to find camera resolution cv::Mat image; cap &gt;&gt; image; if (image.empty()) { std::cout &lt;&lt; "Could not find/open camera. Press Enter to exit." &lt;&lt; std::endl; std::cin.get(); return 0; } cv::Size targetSize(199, 171); cv::VideoWriter writer("out.avi", CV_FOURCC('M','J','P','G'), 25, targetSize, true); // does create a 198x170 video file. //cv::VideoWriter writer("out.avi", -1, 25, targetSize, true); // does not work for x264vfw for example with an error message. while (cv::waitKey(30) != 'q') { cap &gt;&gt; image; if (!image.empty()) { cv::imshow("captured image", image); // resize the actual image to a target size cv::Mat writableImage; cv::resize(image, writableImage, targetSize); writer.write(writableImage); } } // release the camera cap.release(); writer.release(); std::cout &lt;&lt; "Press Enter to exit." &lt;&lt; std::endl; std::cin.get(); return 0; } In general, many codecs are restricted to some pixel-block-constraints like having a multiple of 2, 4, 8, 16 or 32 in each dimension. Either because of the algorithm itself or some hardware instruction optimizations.
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50983996

http://stackoverflow.com/comment/88953446
type: AnswerComment
has text: I tried to check the problem but apparently the `k.id` is not working..
comment on: http://stackoverflow.com/a/50977563
type: Comment
score: 0

http://stackoverflow.com/q/50897392
tagged with: crc32
downvote count: 0
has body: I'm trying to generate CRC32 checksums in Ruby and Python for the same string and get different results. Python from zlib import crc32 x = "SheetJS" crc32(x) #=&gt; -1647298270 NodeJS var CRC32 = require('crc-32'); var x = "SheetJS"; CRC32.str(x); #=&gt; -1647298270 Ruby require 'zlib' x = "SheetJS" Zlib::crc32(x) #=&gt; 2647669026
type: Question
tagged with: zlib
has title: CRC32 checksums are different in Zlib Ruby and Python libraries
has answer: http://stackoverflow.com/a/50897522
upvote count: 2
accepted answer: http://stackoverflow.com/a/50897522
answer count: 1
favorite count: 0
tagged with: ruby
tagged with: crc
tagged with: python
score: 2
type: AnsweredQuestion

http://stackoverflow.com/comment/88860298
has text: Something like `np.linspace(0, len(the_array), 100)` to get the indices? You can also force the dtype of the output to `int` to be used as indices.
score: 1
comment on: http://stackoverflow.com/q/50930655
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89387425
has text: While this code snippet may be the solution, [including an explanation](https://meta.stackexchange.com/questions/114762/explaining-entirely-%E2%80%8C%E2%80%8Bcode-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.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51201681
score: 3

http://stackoverflow.com/a/50965017
score: -1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50964954
type: Answer
accepted answer of: http://stackoverflow.com/q/50964954
upvote count: 0
downvote count: 1
has body: GoDaddy has some documentation about this Python on server

http://stackoverflow.com/q/50870870
downvote count: 0
has body: Scenario is as follows: I need to implement a command line argument system that allows both -p &lt;value&gt; and -p (no value for -p given) Is there any way to achieve this using argparse, or will I have to manually parse sys.argv? Thank u so much!!!
possible better answer: http://stackoverflow.com/a/66226151
accepted answer: http://stackoverflow.com/a/50871450
has comment: http://stackoverflow.com/comment/88761159
tagged with: argparse
linked to: http://stackoverflow.com/q/31815660
tagged with: argv
favorite count: 0
tagged with: python
has title: python argument with or without value, specified or not
type: AnsweredQuestion
score: 7
has answer: http://stackoverflow.com/a/50871450
upvote count: 7
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/66226151

symmetric-difference
tags question: http://stackoverflow.com/q/50871370
type: Tag
tags question: http://stackoverflow.com/q/50941693
tag name: symmetric-difference

http://stackoverflow.com/q/50955381
linked to: http://stackoverflow.com/q/3250749
type: Question
has title: Get python progress bars to behave properly in cygwin
tagged with: cygwin
has body: I'm running anaconda python in cygwin. When I use keras and chainer from a normal command prompt, they both print out progress bars to show the status of a training run and update them in place. However, in cygwin, I get a new line for each step making the output unreadable. Is there any fix for this? This might be related to this question that says: "all Cygwin pty-based terminals (mintty, rxvt and xterm) are recognized as pipes by Windows, not as the console".
score: 0
has comment: http://stackoverflow.com/comment/89066860
tagged with: progress-bar
has comment: http://stackoverflow.com/comment/89010953
type: UnansweredQuestion
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/89050488

http://stackoverflow.com/comment/88868165
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50934420
has text: A small comment: Your function is very confusing, in my opinion. I would recommend you to initiate the if statement earlier.
score: 0

http://stackoverflow.com/q/50915226
tagged with: python-3.6
has body: Here is my starting point. This works as is. l1 = [1, 2, 3, 4] l2 = [5, 6, 7, 8] l3 = [9, 10, 11, 12] def interleave(iterable1, iterable2): for item1, item2 in zip(iterable1, iterable2): yield item1 yield item2 print(interleave(l1, l2)) print('-' * 30) print(list(interleave(l1, l2))) If I want to expand it to use all three lists, I can do this: l1 = [1, 2, 3, 4] l2 = [5, 6, 7, 8] l3 = [9, 10, 11, 12] def interleave(*args): for item1, item2, item3 in zip(*args): yield item1 yield item2 yield item3 print(interleave(l1, l2, l3)) print('-' * 30) print(list(interleave(l1, l2, l3))) However, I 'solved' the issue of receiving any number of input iterables using *args, but my item assignment is still manual. I want to be able to say: def interleave(*args): for *items in zip(*args): yield items To allow me to unpack any number of input variables into *items, but I get this error: SyntaxError: starred assignment target must be in a list or tuple I don't want to say *items = &lt;something&gt;. I want to have *items receive any number of input variables. If I have six lists I don't want to say item1, item2, ..., item6, followed by the same number of yields. That really isn't very scalable. Is there a way to do what I am after?
has answer: http://stackoverflow.com/a/50915331
has comment: http://stackoverflow.com/comment/88830560
has comment: http://stackoverflow.com/comment/88830574
has answer: http://stackoverflow.com/a/50915322
tagged with: python-3.x
type: Question
answer count: 2
tagged with: arguments
tagged with: python
score: 0
has title: Unpack *args for use in a for loop
type: UnansweredQuestion

http://stackoverflow.com/comment/89150233
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50976109
has text: What version of python? After 3.6, dictionaries maintain insertion order.
score: 0

http://stackoverflow.com/comment/88898918
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/50950574
has text: When you call `for i in customers:` `customers` is not in scope of that function.
type: Comment

http://stackoverflow.com/a/50856241
upvote count: 5
type: Answer
downvote count: 0
score: 5
answers question: http://stackoverflow.com/q/50856214
has body: Use the datetime.replace() method to create a new instance, with specific attributes set to your desired value: now = datetime.now().replace(second=0, microsecond=0) Demo: &gt;&gt;&gt; from datetime import datetime &gt;&gt;&gt; datetime.now() datetime.datetime(2018, 6, 14, 12, 16, 4, 738362) &gt;&gt;&gt; datetime.now().replace(second=0, microsecond=0) datetime.datetime(2018, 6, 14, 12, 16)

http://stackoverflow.com/comment/89602210
has text: did you ever figure out this problem? I have a similar situation. See https://stackoverflow.com/questions/51297195/trying-to-feed-a-list-of-strings-to-feed-dict-with-tensorflow
comment on: http://stackoverflow.com/q/50940768
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88892245
type: AnswerComment
comment on: http://stackoverflow.com/a/50946365
score: 0
type: Comment
has text: Try the updated code based on the API docs for MySQL. What I have you earlier was not valid in MySQL it seems. And yes need to call fetchall. Also, that does not have to be in a loop. I am out and about so having a hard time formatting the answer on the phone. Will keep trying for a bit though. In the mean time you can check it in the database directly if you want.

http://stackoverflow.com/comment/89000283
has text: I'm also surprised that the result is 1, 3, 5, 7, because I thought running two workers would deliver 5, 7, 3, 1? How is the distribution done to the workers?
type: Comment
comment on: http://stackoverflow.com/a/50978379
score: 0
type: AnswerComment

http://stackoverflow.com/q/50947665
score: 0
tagged with: bash
tagged with: python
has comment: http://stackoverflow.com/comment/88894676
type: UnansweredQuestion
has body: I am wanting to create a few hundred bash shell scripts where the only difference is the value of a single variable. My script looks something like: ~/programs/program -i ~/data/input.NUM -o ~/results/output.NUM where NUM stipulates the input/ output. The only programming language I'm familiar with is python. Is there any way to do this via some sort of for loop for example? I've yet to find a way to even read in bash scripts into python.
has title: Iteratively creating bash shell scripts with change in variables (in Python?)
type: Question
has answer: http://stackoverflow.com/a/50949036
answer count: 1
has comment: http://stackoverflow.com/comment/88892935
has comment: http://stackoverflow.com/comment/88892717

svd
type: Tag
tags question: http://stackoverflow.com/q/50930899
tags question: http://stackoverflow.com/q/50884533
tags question: http://stackoverflow.com/q/50915223
tag name: svd

http://stackoverflow.com/comment/88879096
type: AnswerComment
has text: @TaohidulIslam, an ideomatic solution, not the best one any way, he is actually creating 2 intermediate lists out of nowhere
type: Comment
comment on: http://stackoverflow.com/a/50940596
score: 2

http://stackoverflow.com/comment/88840641
score: 0
type: AnswerComment
has text: Thanks,can you please post the code to page and grab latest and compare on each resultset,and to your other point i need to use this everyday and i dont have control on source s3 buckets to enable S3 inventory :(
type: Comment
comment on: http://stackoverflow.com/a/50920463

http://stackoverflow.com/q/50976485
has comment: http://stackoverflow.com/comment/88949621
tagged with: python
has comment: http://stackoverflow.com/comment/89097139
has answer: http://stackoverflow.com/a/51051463
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50976701
has comment: http://stackoverflow.com/comment/88949019
type: Question
tagged with: multiprocessing
linked to: http://stackoverflow.com/q/5355827
accepted answer: http://stackoverflow.com/a/51051463
tagged with: python-multiprocessing
score: 0
has title: Python Multiproccessing Pool - Sharing one variable per process?
answer count: 2
has comment: http://stackoverflow.com/comment/88949037
has comment: http://stackoverflow.com/comment/88949146
has answer: http://stackoverflow.com/a/50976701
has body: I have been trying to find a simple example where I share one constant variable per process launched in my process pool. Most examples show you how to share variables across processes, which is not what I want. import multiprocessing import time data = ( {"var":1, "shared": None}, {"var":2, "shared": None}, {"var":3, "shared": None}, {"var":4, "shared": None} ) def mp_worker(input): print input # print " Processs %s\tWaiting %s seconds" % (inputs, the_time) # time.sleep(int(the_time)) # print " Process %s\tDONE" % inputs def mp_handler(): p = multiprocessing.Pool(2) p.map(mp_worker, data) if __name__ == '__main__': mp_handler() For example, if I run this code, I would like to have my "shared" component intialized once for each process. I would like to do something like this (This doesnt work): from multiprocessing import Pool, Process class Worker(Process): def __init__(self): print 'Worker started' # do some initialization here super(Worker, self).__init__() def compute(self, data): print 'Computing things!' return data * data if __name__ == '__main__': # This works fine worker = Worker() #print worker.compute(3) # workers get initialized fine pool = Pool(processes = 4, initializer = Worker) data = range(10) # How to use my worker pool? # result = pool.map(Worker.compute, data) result = pool.map(Worker.compute, data)

http://stackoverflow.com/a/50933463
score: 0
has comment: http://stackoverflow.com/comment/88865733
type: Answer
has body: If fields or tables have spaces or other special characters in their names, they need delimited with `. INSERT INTO test (`Column 1`,`Column 2`) ... It is also a good habit to get into because it prevents hard to diagnose issues with using identifiers that might be confused with reserved or keywords.
answers question: http://stackoverflow.com/q/50933434

http://stackoverflow.com/comment/88863257
has text: You can use such a flag like in a producer worker approach. Or since you have only two threads you can think of a multiprocess pipe. Where you have a parent process and a child process. Then you can send a termination criteria to the child process when it is set in the parent process and both can be terminated http://danielhnyk.cz/python-producers-queue-consumed-by-workers/
comment on: http://stackoverflow.com/q/50911444
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50931874
type: Question
tagged with: arangodb
upvote count: 1
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50934271
accepted answer: http://stackoverflow.com/a/50934271
tagged with: python
tagged with: pyarango
tagged with: nosql
type: AnsweredQuestion
downvote count: 0
has title: Relationship between 2 collections Arangodb
score: 1
tagged with: aql
has body: I have 2 collections : User Tweet I want store in User the list of tweet_id and in each tweet the user_id. In my json Tweets files I have the tweet author champ.I try with AQL but I did not succeed, can you help me ? Thanks ps: I'm French student sorry for this broken English

http://stackoverflow.com/q/50950943
tagged with: windows
has title: How to make my python 3 desktop application portable?
tagged with: python
tagged with: portable-python
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51068169
accepted answer: http://stackoverflow.com/a/51068169
upvote count: 1
type: Question
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50954758
score: 1
has body: I have tried portable python but the latest version is 3.2.5. (need 3.6+) I cannot install libraries on it, even the get-pip.py doesn't work. I'm trying to figure out how to make my project portable on windows systems that do not have python installed. Also I want the minimum possible libraries(core python modules) to keep the project as lean as possible,
linked to: http://stackoverflow.com/q/44488174
answer count: 2
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/50954758
has comment: http://stackoverflow.com/comment/133402019

http://stackoverflow.com/comment/88882620
comment on: http://stackoverflow.com/a/50881081
has text: Thanks a lot! I'll use client.submit, as it a little bit easier
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50872762
tagged with: python
upvote count: 6
has comment: http://stackoverflow.com/comment/88747502
score: 6
has comment: http://stackoverflow.com/comment/88752935
type: Question
has answer: http://stackoverflow.com/a/50875365
tagged with: sorting
has answer: http://stackoverflow.com/a/50872904
has answer: http://stackoverflow.com/a/50872956
answer count: 3
has body: How to sort a list to end up with: ['a', 'aa', 'aaa', 'A', 'AA', 'AAA', 'b', 'bb', 'bbb', 'B', 'BB', 'BBB'] Assume a shuffled version of it for convenience: ['bb', 'a', 'B', 'BB', 'AAA', 'BBB', 'b', 'aa', 'aaa', 'A', 'AA', 'bbb'] I tried sorting by ignoring case: l = sorted(l, key=lambda x: x.lower()) which results in ['a', 'A', 'aa', 'AA', 'aaa', 'AAA'] From answers below, there are two solutions for the mixed case, I'm not sure which is better. L = ['ABC1', 'abc1', 'ABC2', 'abc2', 'Abc'] l = sorted(L, key=lambda x: "".join([y.lower() + y.swapcase() for y in x])) print(l) l = sorted(L, key=lambda x: [(c.lower(), c.isupper()) for c in x]) print(l)
downvote count: 0
has title: Python Sort - Semi Ignore Case (a, aa, A, AA, b, bb, B, BB...)
favorite count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/5292303

manage.py
tags question: http://stackoverflow.com/q/50916493
tag name: manage.py
type: Tag

http://stackoverflow.com/comment/88992548
type: QuestionComment
comment on: http://stackoverflow.com/q/50999263
score: 0
has text: if you need it for models FK you can use string `app.ModelName` other case read https://stackoverflow.com/questions/17226016/simple-cross-import-in-python
type: Comment

http://stackoverflow.com/a/51542562
type: Answer
accepted answer of: http://stackoverflow.com/q/50880303
answers question: http://stackoverflow.com/q/50880303
has comment: http://stackoverflow.com/comment/108108412
score: 5
upvote count: 5
has body: Not really an answer, but the best workaround I've discovered: from pyspark.sql.functions import udf from pyspark.sql.types import StringType, ArrayType import spacy def get_entities_udf(): def get_entities(text): global nlp try: doc = nlp(unicode(text)) except: nlp = spacy.load('en') doc = nlp(unicode(text)) return [t.label_ for t in doc.ents] res_udf = udf(get_entities, StringType(ArrayType())) return res_udf documents_df = documents_df.withColumn('entities', get_entities_udf()('text'))
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/50892429
has title: Populating a variably nested dictionary with multiple API calls
has answer: http://stackoverflow.com/a/50915102
tagged with: medical
score: 0
accepted answer: http://stackoverflow.com/a/50915102
answer count: 1
tagged with: python
type: AnsweredQuestion
has body: I am using a public API at www.gpcontract.co.uk to populate a large variably nested dictionary representing a hierarchy of UK health organisations. Some background information The top level of the hierarchy is the four UK countries (England, Scotland, Wales and Northern Ireland), then regional organisations all the way down to individual clinics. The depth of the hierarchy is different for each of the countries and can change depending on the year. Each organisation has a name, orgcode and dictionary listing its child organisations. Unfortunately, the full nested hierarchy is not available from the API, but calls to http://www.gpcontract.co.uk/api/children/[organisation code]/[year] will return the immediate child organisations of any other. So that the hierarchy can be easily navigated in my app, I want to generate an offline dictionary of this full hierarchy (on a per year basis) which will be saved using pickle and bundled with the app. Getting this means a lot of API calls, and I am having trouble converting the returned JSON into the dictionary object I require. Here is an example of one tiny part of the hierarchy (I have only shown a single child organisation as an example). JSON hierarchy example { "eng": { "name": "England", "orgcode": "eng", "children": {} }, "sco": { "name": "Scotland", "orgcode": "sco", "children": {} }, "wal": { "name": "Wales", "orgcode": "wal", "children": {} }, "nir": { "name": "Northern Ireland", "orgcode": "nir", "children": { "blcg": { "name": "Belfast Local Commissioning Group", "orgcode": "blcg", "children": { "abc": { "name": "Random Clinic", "orgcode": "abc", "children": {} } } } } } } Here’s the script I’m using to make the API calls and populate the dictionary: My script import json, pickle, urllib.request, urllib.error, urllib.parse # Organisation hierarchy may vary between years. Set the year here. year = 2017 # This function returns a list containing a dictionary for each child organisation with keys for name and orgcode d…
tagged with: http://stackoverflow.com/tag/json
type: Question

http://stackoverflow.com/comment/88906132
type: Comment
type: QuestionComment
score: 2
has text: You want just `if` statements not `elif`. If there's a `en dash` in `string`, that doesn't mean you want to ignore the `em dash` in string too, does it? If each thing you want to replace is a single character, you should use [`str.translate`](https://docs.python.org/3/library/stdtypes.html#str.translate)
comment on: http://stackoverflow.com/q/50954147

http://stackoverflow.com/comment/88821908
type: QuestionComment
has text: @will7200 Nuclide is open source https://github.com/facebook/nuclide
comment on: http://stackoverflow.com/q/50879713
score: 0
type: Comment

http://stackoverflow.com/q/50962259
score: 0
has comment: http://stackoverflow.com/comment/88921983
answer count: 1
accepted answer: http://stackoverflow.com/a/50996141
has comment: http://stackoverflow.com/comment/88954201
tagged with: python
has body: Our company has an API for Windows only(server), I've wrote some python code to convert raw data to pd.DataFrame on server. I hope to send this dataframe to another python program running on CentOS 7(client). I would be grateful if anyone could give me a solution. According to my research, I built a socket server on Windows. The dataframe looks like this: Date | Ticker1 | Ticker 2| -------------------------- May11| 100.01 | 143.12 | Here is my code on server: records_to_send=df.to_records().tostring() conn.send(records_to_send) But when it comes to decoding, np.frombuffer() can't recognize the dtype I set. Even if I just run the following code on server: np.frombuffer(df.to_records().to_string(),df.to_records().dtype) would raise a ValueError: ValueError: cannot create an OBJECT array from memory buffer
type: AnsweredQuestion
tagged with: tcp
has title: Share pandas.DataFrame between Windows and Linux?
has answer: http://stackoverflow.com/a/50996141
type: Question
tagged with: lan
tagged with: dataframe

http://stackoverflow.com/q/50871840
tagged with: loops
type: Question
has answer: http://stackoverflow.com/a/50871906
score: -2
upvote count: 1
answer count: 1
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88745305
downvote count: 3
has body: I want to use the Python keyword dict to return a dictionary with every word as true of a given sentence. The code snippet is: return dict((word, True) for word in words) Now, the ambiguity occurs when both the codes return same dictionaries: 1. return dict((word, True) for word in words) 2. return dict([(word, True) for word in words]) Why doesn't the second snippet return a dict with list of words inside?
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/88745379
type: AnsweredQuestion
has title: Python dict ambiguity
tagged with: list
accepted answer: http://stackoverflow.com/a/50871906

http://stackoverflow.com/a/50935565
accepted answer of: http://stackoverflow.com/q/50935514
answers question: http://stackoverflow.com/q/50935514
type: AcceptedAnswer
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/88904057
has body: Put apple inside an iterable, i.e. a list or tuple: cursor.execute(""" LOCK TABLE apples IN SHARE ROW EXCLUSIVE MODE; INSERT INTO apples(apple) SELECT %s WHERE NOT EXISTS ( SELECT * FROM apples WHERE apple = %s ); """, (apple,)))
has comment: http://stackoverflow.com/comment/88880671

http://stackoverflow.com/q/50977867
tagged with: pytest
tagged with: selenium
has answer: http://stackoverflow.com/a/53457149
has comment: http://stackoverflow.com/comment/88973346
type: Question
has comment: http://stackoverflow.com/comment/88953637
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/88953406
has comment: http://stackoverflow.com/comment/88994254
has body: Right now I'm using pytest and selenium to run tests on Jenkins. When I run the code below locally it creates a screenshot after each test, which is working great. @pytest.mark.hookwrapper def pytest_runtest_makereport(item, call): pytest_html = item.config.pluginmanager.getplugin('html') outcome = yield report = outcome.get_result() if 'selenium' not in item.fixturenames or 'selenium' not in item.funcargs: return driver = item.funcargs['selenium'] extra = getattr(report, 'extra', []) if report.when == 'call' or report.when == "setup": extra.append(pytest_html.extras.url(driver.current_url, name = "Go To URL Tested")) if not report.skipped: report_directory = os.path.dirname(item.config.option.htmlpath) file_name = f"{item.originalname}.png" screenshot_was_saved = driver.get_screenshot_as_file(f"{report_directory}\\{file_name}") if file_name: report.screenshot = html.a(html.img(src = file_name, onclick = "window.open(this.src)", align = "right", style = "max-height: 150px;"), href = "#") report.extra = extra But when I run that same code in my build pipeline on Jenkins, the images don't get created. The value that is returned from the get_screenshot_as_file method is False. There are no exceptions being returned and the tests pass. The Jenkins agent has permission to write files because the directory where I'm dumping to HTML report gets created. The index.html for the report gets created as well. Everything is there except for the images. Does anyone have experience with something like this? I even tried running the chrome driver in headless mode and that didn't make a difference. Any help would be appreciated.
has comment: http://stackoverflow.com/comment/88972235
favorite count: 0
has comment: http://stackoverflow.com/comment/88996335
has title: How to capture screenshots with Selenium when running tests on a Jenkins agent
tagged with: jenkins
upvote count: 2
type: UnansweredQuestion
tagged with: python
tagged with: selenium-webdriver
score: 2

http://stackoverflow.com/a/50886262
has comment: http://stackoverflow.com/comment/88774713
score: 3
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50886079
answers question: http://stackoverflow.com/q/50886079
has comment: http://stackoverflow.com/comment/88774627
has comment: http://stackoverflow.com/comment/89956918
upvote count: 3
has comment: http://stackoverflow.com/comment/88774790
has comment: http://stackoverflow.com/comment/88774597
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90027340
has comment: http://stackoverflow.com/comment/88774716
has body: Consider the following approach: We define a list of question and answer pairs. We do this in one place so it's easy to maintain and we don't have to search all over the file to make changes or re-use this code for a different questionset. We create an ask_question function that we can call for all of our questions. This way, if we want to make a change about how we implement our question logic, we only have to make it in one spot (and not in each of the questionXX functions). We compare user input to our answer using == and not in (in will do something else, not what you expect). We create an object to keep track of our answer results. Here, it's an instance of ResultsStore, but it can be anything really, let's just try to get away from global variables. Use a loop when prompting for answers. The loop will repeat if the answer given was incorrect (and if retry_on_fail is False). Allow for the user to enter some "skip" keyword to skip the question. Display the results once the "test" is complete. Here, we do that by defining and calling the store.display_results() method. So, what about: from easygui import enterbox question_answer_pairs = [ ("1 + 1 = ?", "2"), ("2 * 3 = ?", "6"), ("which type of metabolism provides the maximum amount of ATP needed for contraction?", "aerobic") ] VERSION = 'A&amp;P EXAM 3 REVIEW' class ResultStore: def __init__(self): self.num_correct = 0 self.num_skipped = 0 self.num_wrong = 0 def show_results(self): print("Results:") print(" Correct:", self.num_correct) print(" Skipped:", self.num_skipped) print(" Wrong: ", self.num_wrong) def ask_question(q, a, rs, retry_on_fail=True): while True: resp = enterbox(msg=q, title=VERSION) # Force resp to be a string if nothing is entered (so .lower() doesn't throw) if resp is None: resp = '' if resp.lower() == a.lower(): rs.num_correct += 1 return True if resp.lower() == "skip": rs.num_skipped += 1 return None # If we get here, we haven't returned (so the answer was neither correct nor # "skip"). Inc…
has comment: http://stackoverflow.com/comment/89957332
type: Answer

http://stackoverflow.com/comment/88820585
comment on: http://stackoverflow.com/q/50906128
type: QuestionComment
has text: Have you tried this? https://stackoverflow.com/questions/37010083/syntax-for-row-to-json-with-sqlalchemy
score: 0
type: Comment

http://stackoverflow.com/a/50861193
upvote count: 1
score: 1
has body: The problem is that pygame.Rects can only have ints as their coordinates and floats get truncated. If you want floating point values as the velocities, you have to store the actual position as a separate attribute (or two as in the first example below), add the velocity to it every frame and then assign the new position to the rect. class Enemy(pygame.sprite.Sprite): def __init__(self, pos): # You can pass the position as a tuple, list or vector. super().__init__() self.image = pygame.Surface((20, 20)) self.image.fill((255, 0, 0)) pygame.draw.circle(self.image, (COLOUR4), (10, 10), 10) # The actual position of the sprite. self.pos_x = pos[0] self.pos_y = pos[1] # The rect serves as the blit position and for collision detection. # You can pass the center position as an argument. self.rect = self.image.get_rect(center=(self.pos_x, self.pos_y)) self.dx = 2 self.dy = 1 def update(self): self.pos_x += self.dx self.pos_y += self.dy self.rect.center = (self.pos_x, self.pos_y) I recommend using vectors, since they are more versatile and concise. from pygame.math import Vector2 class Enemy(pygame.sprite.Sprite): def __init__(self, pos): # ... self.pos = Vector2(pos) self.velocity = Vector2(2, 1) def update(self): self.pos += self.velocity self.rect.center = self.pos
has comment: http://stackoverflow.com/comment/88756402
has comment: http://stackoverflow.com/comment/88759404
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50859819
answers question: http://stackoverflow.com/q/50859819
type: Answer

http://stackoverflow.com/comment/88869640
score: 2
has text: You only formatted one string, but you have two. Also I'm pretty sure Python's cursor object does not allow having multiple statements. You need to break the lock table apart.
comment on: http://stackoverflow.com/q/50935514
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50896965
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88800312
tagged with: python
tagged with: performance
score: 0
type: Question
tagged with: stat
has comment: http://stackoverflow.com/comment/88793804
has answer: http://stackoverflow.com/a/50897385
has body: When handling large amounts of data, minimizing the number of database requests and doing bulk operations instead helps a lot in terms of performance. Question: is it possible to retrieve the mtimes of 10,000 files at once/in bulk on Linux? I hope to minimize system calls. Couldn't find something here: http://www.gnu.org/software/libc/manual/html_node/index.html PS: currently, I retrieve those filenames using python:os.walk.
tagged with: linux
has comment: http://stackoverflow.com/comment/88794045
tagged with: system-calls
answer count: 1
has title: Linux bulk mtime
has comment: http://stackoverflow.com/comment/88793651
has comment: http://stackoverflow.com/comment/88803052

http://stackoverflow.com/q/50976837
type: UnansweredQuestion
has body: I'm writing a small program as part of a school assignment but i've been having trouble with sql statements. I was wondering if it were possible to use variables defined in the python code in sql statements. X = variable Y = other_variable db.execute("""SELECT X FROM TABLE WHERE Value = Y""") like such.... I have read around this froum a bit but I can't understand much of it as I am relatively new to using sql with python
score: -3
has answer: http://stackoverflow.com/a/50979771
tagged with: python
downvote count: 3
type: Question
has comment: http://stackoverflow.com/comment/88949709
has title: using python variables as columns in sql statements
tagged with: sql
upvote count: 0
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/88821639
comment on: http://stackoverflow.com/a/50909823
score: 1
type: AnswerComment
has text: this is awesome! Thanks!
type: Comment

http://stackoverflow.com/comment/88717004
has text: Am I correct in saying that the `weights` dataframe has the same number of rows as the `df` dataframe?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50857266

http://stackoverflow.com/q/50893573
favorite count: 0
score: -1
tagged with: py2neo
possible better answer: http://stackoverflow.com/a/50893615
has title: neo4j CYPHER - at ON MATCH SET create new nodes on condition
tagged with: cypher
tagged with: python
has answer: http://stackoverflow.com/a/50899381
downvote count: 1
type: AnsweredQuestion
tagged with: pubmed
has comment: http://stackoverflow.com/comment/88795163
type: Question
answer count: 2
has body: To import XML data into a neo4j DB I first parse the XML to a python dictionary and then use CYPHER queries: WITH $pubmed_dict as pubmed_article UNWIND pubmed_article as particle ... FOREACH (author IN particle.MedlineCitation.Article.AuthorList.Author | MERGE (a:Author {last_name: COALESCE(author.LastName, 'LAST NAME MISSING!')}) ON CREATE SET a.first_name = author.ForeName, a.affiliation = author.AffiliationInfo.Affiliation ON MATCH SET a.first_name = author.ForeName, a.affiliation = author.AffiliationInfo.Affiliation MERGE (p)<-[:WROTE]-(a) ) Unfortunately, Authors don't have unique IDs in the database, so it might be that different authors have the same last names but different initials or affiliations. ... Smith A L AL University X ... Smith A L AL University BUMBABU My intention was to MERGE on author.LastName but ON MATCH check if the author has the same ForeName OR the same Affiliation and if not create a new node instead. How would I do that using CYPHER queries? EDIT 1 Node Key constraints are the solution, which is an Enterprise Edition feature, though. Looking for a workaround for that. EDIT 2 This code is working almost perfectly: WITH $pubmed_dict as pubmed_article UNWIND pubmed_article as particle MERGE (p:Publication {pmid: particle.MedlineCitation.PMID.text}) ON CREATE SET p.title = COALESCE (particle.MedlineCitation.Article.Journal.Title, particle.MedlineCitation.Article.ArticleTitle) ON MATCH SET p.title = COALESCE (particle.MedlineCitation.Article.Journal.Title, particle.MedlineCitation.Article.ArticleTitle) FOREACH (author IN particle.MedlineCitation.Article.AuthorList.Author | MERGE (a:Author {last_name: COALESCE(author.LastName, 'LAST NAME MISSING!'), first_name: COALESCE(author.ForeName, 'FIRST NAME MISSING!')}) MERGE (p)<-[:WROTE]-(a) ) To sum it up: For every author I want to create a new author IF LastName OR ForeName OR Affiliation are different. I also need NEW Nodes for authors where LAST NAME MISSING! and FIRST NAME MISSING! Is it poss…
upvote count: 0
accepted answer: http://stackoverflow.com/a/50899381
has comment: http://stackoverflow.com/comment/88841002
has answer: http://stackoverflow.com/a/50893615
tagged with: neo4j

sensors
type: Tag
tags question: http://stackoverflow.com/q/50938170
tag name: sensors

pivot-table
tag name: pivot-table
tags question: http://stackoverflow.com/q/50959350
tags question: http://stackoverflow.com/q/50893052
tags question: http://stackoverflow.com/q/50955736
type: Tag

http://stackoverflow.com/a/50878992
type: Answer
has comment: http://stackoverflow.com/comment/88762585
has body: x.loc[x['column 1']==y['column 1'], 'column 1'] = y['column 2']
answers question: http://stackoverflow.com/q/50878949
score: 0

http://stackoverflow.com/comment/88951176
type: QuestionComment
has text: your move method calls itself before it has a chance to finish. This is likely your problem.
comment on: http://stackoverflow.com/q/50973015
score: 0
type: Comment

http://stackoverflow.com/comment/88871509
type: QuestionComment
score: 0
has text: why did you tag this with multithreading?
comment on: http://stackoverflow.com/q/50934463
type: Comment

http://stackoverflow.com/comment/88924780
has text: @MohanBabu Actually, forget the example I linked (which depends on your Python implementation/version and random chance); that was silly. Just consider `{2, 'a'}`. That set _has_ no smallest value, and yet `pop` works just fine.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50963976
score: 0

http://stackoverflow.com/comment/108335599
comment on: http://stackoverflow.com/q/50961759
has text: Did you find any solution? I am trying to add html elements dynamically based on selected drop down option. Can you tell me how to do this?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88839625
has text: ok... it seems I chose a bad option. Thanks for your comment, I'll try with kivy.
type: Comment
comment on: http://stackoverflow.com/q/50919871
score: 0
type: QuestionComment

http://stackoverflow.com/comment/88948742
has text: If your array elements are 3D arrays _of the same size_, then it is automatically a 4D array.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50976373

http://stackoverflow.com/a/50983775
has comment: http://stackoverflow.com/comment/89024511
score: 3
type: Answer
upvote count: 3
answers question: http://stackoverflow.com/q/50983386
has body: Use pandas groupby function. import io import pandas as pd data = io.StringIO(''' 2017-11-03 07:30:00,NaN 2017-11-03 09:18:00,NaN 2017-11-03 10:00:00,NaN 2017-11-03 11:08:00,NaN 2017-11-03 14:39:00,NaN 2017-11-03 14:53:00,NaN 2017-11-03 15:00:00,NaN 2017-11-03 16:00:00,NaN 2017-11-03 17:03:00,NaN 2017-11-03 17:42:00,800.0 2017-11-04 07:27:00,600.0 2017-11-04 10:10:00,NaN 2017-11-04 11:48:00,NaN 2017-11-04 12:58:00,500.0 2017-11-04 13:40:00,NaN 2017-11-04 15:15:00,NaN 2017-11-04 16:21:00,NaN 2017-11-04 17:37:00,500.0 2017-11-04 21:37:00,NaN 2017-11-05 03:00:00,NaN 2017-11-05 06:30:00,NaN 2017-11-05 07:19:00,NaN 2017-11-05 08:31:00,200.0 2017-11-05 09:31:00,500.0 2017-11-05 12:03:00,NaN 2017-11-05 12:25:00,200.0 2017-11-05 13:11:00,500.0 2017-11-05 16:31:00,NaN 2017-11-05 19:00:00,500.0 2017-11-06 08:08:00,NaN ''') column_names = ['date', 'val'] df = pd.read_csv(data, sep=',', header = None, names = column_names) df['date'] = pd.to_datetime(df['date']) df = df.groupby(df['date'].dt.date)'val'.sum() df.plot()
downvote count: 0

http://stackoverflow.com/comment/88719719
type: Comment
has text: Possible duplicate of [Pandas expand rows from list data available in column](https://stackoverflow.com/questions/39011511/pandas-expand-rows-from-list-data-available-in-column)
comment on: http://stackoverflow.com/q/50858129
score: 0
type: QuestionComment

http://stackoverflow.com/comment/88967590
score: 0
has text: Wouldn't `--only-binary` (tell pip to not use source packages) be an option for you?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50982701

http://stackoverflow.com/a/50923421
has body: Such a long question... Too long for me to understand well. But I think you misunderstand how handlers work. Actually logger itself doesn't output anything but handlers do. So let's say if you set DEBUG on dev logger, it will pass logs >= DEBUG to all handlers. And then debug_console handler will process logs >= DEBUG but info_file_handler will only process logs >= INFO. Setting DEBUG on dev logger won't let info_file_handler output logs &lt; INFO. So you do can have two separate levels which one is >= DEBUG and goes to console while another is >= INFO and goes to file. I am presuming I understand you rightly...
answers question: http://stackoverflow.com/q/50923061
type: Answer
has comment: http://stackoverflow.com/comment/88865284
score: 0

http://stackoverflow.com/comment/88887586
has text: you can bring stdin, stdout, stderr = ssh.exec_command(command1) for line in stdout: inside a loop or delay it using sleep commands.
comment on: http://stackoverflow.com/q/50944952
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89146166
type: Comment
comment on: http://stackoverflow.com/a/50997436
has text: inp=Input(shape=(121,)) layer=Dense(82)(inp) layer=BatchNormalization(axis=-1)(layer) layer=Activation('relu')(layer) layer=Dropout(0.3)(layer) layer=Dense(54)(layer) layer=BatchNormalization(axis=-1)(layer) layer=Activation('relu')(layer) layer=Dropout(0.3)(layer) layer=Dense(2)(layer) layer=Activation('softmax')(layer) model=Model(inputs=inp,outputs=layer,name='Classifier')
type: AnswerComment
score: 0

http://stackoverflow.com/a/50931100
has comment: http://stackoverflow.com/comment/88861441
type: AcceptedAnswer
has body: you must change your lambda as follows: command=lambda dir=_src+directory: GotoDir(dir) in order to capture the correct arguments for each lambda function created within the for loop
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50931048
answers question: http://stackoverflow.com/q/50931048

http://stackoverflow.com/comment/88727117
score: 0
type: Comment
has text: @ShivamSharma Although, in the question you asked in the edit, you replace count(1) by count(obj). This makes the counter start at obj. You *always* want it to start at 1.
type: AnswerComment
comment on: http://stackoverflow.com/a/50858604

http://stackoverflow.com/comment/88830869
comment on: http://stackoverflow.com/q/50879154
has text: Does this help? https://djangosnippets.org/snippets/2533/
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/134281903
has text: What a shame that Python does not offer JSON Converter for any type it uses. Python feels like 2 centuries ago... :-(
comment on: http://stackoverflow.com/a/57915246
type: AnswerComment
score: 1
type: Comment

http://stackoverflow.com/comment/88783335
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50891248
score: 3
has text: Take out your second question and put it into a separate one, please ask one question per post. Also, please provide a [mcve].

http://stackoverflow.com/comment/89049147
comment on: http://stackoverflow.com/a/51028341
has text: Exactly what I wanted. Much appreciated!
type: Comment
score: 1
type: AnswerComment

http://stackoverflow.com/a/50937229
accepted answer of: http://stackoverflow.com/q/50900340
answers question: http://stackoverflow.com/q/50900340
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88873622
has body: using pandas, here's how I tackled it just now. assuming the data is stored in a dictionary called data import pandas as pd labels = pd.DataFrame.from_records(data['speaker_labels']) transcript_tstamps = pd.DataFrame.from_records( [t for r in data['results'] for a in r['alternatives'] for t in a['timestamps']], columns=['word', 'from', 'to'] ) # this list comprehension more-efficiently de-nests the dictionary into # records that can be used to create a DataFrame df = labels.merge(transcript_tstamps) # produces a dataframe of speakers to words based on timestamps from &amp; to # since I knew I wanted to merge on the from &amp; to columns, # I named the columns thus when I created the transcript_tstamps data frame # like this: confidence final from speaker to word 0 0.475 False 6.18 0 6.63 the 1 0.475 False 6.63 0 6.95 weather 2 0.475 False 6.95 0 7.53 is 3 0.499 False 7.73 0 8.11 sunny 4 0.472 False 8.21 0 8.50 it's 5 0.472 False 8.50 0 8.66 time 6 0.472 False 8.66 0 8.81 to 7 0.472 False 8.81 0 8.99 sip 8 0.472 False 8.99 0 9.02 in 9 0.472 False 9.02 0 9.25 some 10 0.472 False 9.25 0 9.32 cold 11 0.472 False 9.32 0 9.68 beer 12 0.441 False 10.52 2 10.88 sure 13 0.364 False 10.92 2 11.19 that 14 0.372 False 11.68 2 11.82 sounds 15 0.372 False 11.82 2 12.11 like 16 0.383 False 12.32 2 12.96 a 17 0.428 False 12.99 2 13.80 plan after the speaker &amp; word data are joined, it is necessary to group successive words by the same speaker together to derive the current speaker. for instance, if the speaker array looked like [2,2,2,2,0,0,0,2,2,2,0,0,0,0], we would need to group the first four 2 together, then the next three 0, then the three 2 and then the remaining 0. sort the data by ['from', 'to'] and then set up a dummy variable for this called current_speaker like this: df = df.sort_values(['from', 'to']) df['current_speaker'] = (df.speaker.shift() != df.speaker).cumsum() from here, group by the current_speaker, aggregate the words into a sentence &amp; convert to json. …
type: Answer
has comment: http://stackoverflow.com/comment/88901720
has comment: http://stackoverflow.com/comment/88917068
upvote count: 3
has comment: http://stackoverflow.com/comment/88903621
has comment: http://stackoverflow.com/comment/88872953
has comment: http://stackoverflow.com/comment/88973963
has comment: http://stackoverflow.com/comment/88946118
score: 3
has comment: http://stackoverflow.com/comment/88916456

http://stackoverflow.com/a/50961618
has comment: http://stackoverflow.com/comment/111714375
has body: From the csv.reader documentation: Return a reader object which will iterate over lines in the given csvfile. csvfile can be any object which supports the iterator protocol and returns a string each time its __next__() method is called — file objects and list objects are both suitable. (Emphasis mine.) What you have is a wrapper around the file object. The file pointer does all the dirty work of efficiently iterating over the lines of your file, and the csv module's Reader parses those lines as they're read in. So yes, +1 for memory friendliness and efficiency.
answers question: http://stackoverflow.com/q/50961529
downvote count: 0
has comment: http://stackoverflow.com/comment/119633785
has comment: http://stackoverflow.com/comment/119634490
type: Answer
score: 11
upvote count: 11

http://stackoverflow.com/q/50872574
has title: pyspark read csv file with regular expression
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/88750185
has body: I'm trying to read csv files from a directory with a particular pattern I want to match all the files with that contains this string "logs_455DD_33 t should match anything like " machine_logs_455DD_33.csv logs_455DD_33_2018.csv machine_logs_455DD_33_2018.csv I've tried the following regex but it doesn't match files with the above format . file = "hdfs://data/logs/{*}logs_455DD_33{*}.csv" df = spark.read.csv(file)
type: AnsweredQuestion
downvote count: 0
possible better answer: http://stackoverflow.com/a/50878824
score: 1
has answer: http://stackoverflow.com/a/50878824
type: Question
accepted answer: http://stackoverflow.com/a/50873208
tagged with: apache-spark-sql
tagged with: pyspark
has answer: http://stackoverflow.com/a/50873208
answer count: 2
tagged with: apache-spark
upvote count: 1
favorite count: 0

http://stackoverflow.com/q/50917856
answer count: 1
has comment: http://stackoverflow.com/comment/88837038
has answer: http://stackoverflow.com/a/50994169
score: 0
has comment: http://stackoverflow.com/comment/88836978
tagged with: python
has comment: http://stackoverflow.com/comment/88863688
has comment: http://stackoverflow.com/comment/88857181
has comment: http://stackoverflow.com/comment/88836309
has comment: http://stackoverflow.com/comment/88837022
type: UnansweredQuestion
has title: embedding python in a json file
has comment: http://stackoverflow.com/comment/88836394
has comment: http://stackoverflow.com/comment/88836261
has comment: http://stackoverflow.com/comment/88835981
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/88863415
type: Question
has body: In my application I am using json as the main API. It stores a set of commands to process files. This works great except part of my requirements is that I need to embed python. I have a clunky solution, but am looking for a better one. Here is an example of my approach: { "file key" : { "instruction1" : { "commandList" : [ { "conditionalPythonBlock" : [ "myval = int(dict['count'])", "retval = myval &gt; 0" ] } ]} } } I wrote a routine to collapse the "conditionalPythonBlock" into one multi line string which can then be executed. The multi line approach is necessary for correct indentation. The 'dict' variable in 'dict['mycount']' is local context in the parser of this file. The retval is also a local variable in the context of the parser. Anyone have a more elegant solution? Thanks!

http://stackoverflow.com/q/50903075
has title: Trying to make a Python code to print E-mail onto a website with IMAP, localhost doesn't respond
tagged with: web-applications
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/50941074
has comment: http://stackoverflow.com/comment/88822554
tagged with: imap
has body: So I've been trying to make a code to print my Gmail inbox onto a website. I want to further develop this to only contain certain data from the email and write it onto a database. However, it does not seem to me that there is anything wrong with the code, but the localhost:8080 (The port I'm using) does not load at all. The browser has the loading icon when trying to access the page, but it does not load, even after hours. Command line does not respond with any errors. I also have the GMAIL imap settings correctly, and I have tried it with Outlooks email as well. Here is the code: import webapp2 import smtplib import time import imaplib import email class ReadMail(webapp2.RequestHandler): def get(self): mail = imaplib.IMAP4('xxx@gmail.com',993) mail.login('email@gmail.com','password') type, data = mail.search(None, 'ALL') mail_ids = data[0] id_list = mail_ids.split() first_email_id = int(id_list[0]) latest_email_id = int(id_list[-1]) for i in range(latest_email_id,first_email_id, -1): typ, data = mail.fetch(i, '(RFC822)' ) for response_part in data: if isinstance(response_part, tuple): msg = email.message_from_string(response_part[1]) email_subject = msg['subject'] email_from = msg['from'] self.response.headers["Content-Type"] = "text/plain" self.response.write("From:" + email_from) self.response.write("Subject:" + email_subject) routes = [('/', ReadMail),] app = webapp2.WSGIApplication(routes, debug=True) App.yml is correctly setup as well. This code works with something really simple, such as only containing a print "this". Hopefully someone can help with my problem, thanks in advance!
tagged with: email
downvote count: 0
answer count: 1
tagged with: web
favorite count: 0
has answer: http://stackoverflow.com/a/50941074
tagged with: python
type: AnsweredQuestion
score: 1

http://stackoverflow.com/comment/88882855
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50934729
has text: @OregonJim, this practical solution doesn't seem very doable though... Let's say, I have the data on an external hard drive. What are the best precautions I could take to avoid leaks and what risks will I have to take ? I really have to know what I'm doing here because I am legally responsible for what happen
score: 0

http://stackoverflow.com/comment/88794696
type: QuestionComment
type: Comment
has text: here output of pip3 --version pip 10.0.1 from /usr/lib/python3.6/site-packages/pip (python 3.6)
comment on: http://stackoverflow.com/q/50897358
score: 0

http://stackoverflow.com/comment/88730362
comment on: http://stackoverflow.com/q/50863691
score: 0
type: Comment
type: QuestionComment
has text: The expected output is a string representation without hyphens all concatenated

http://stackoverflow.com/a/67032410
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50865803
has body: df1=df_interr.groupBy("Item_group","Item_name","price").count().filter("count > 1")

http://stackoverflow.com/comment/88803342
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50897541
has text: I think you forgot columm`s average

http://stackoverflow.com/a/51963931
has body: Your error lies in the interpretation of terms given on your quoted page (which is admittedly misleading). So n in the reference corresponds to your nb_units, which can be appreciated by the fact that this variable enters quadratically into the given formula, and thus corresponds to the recurrent connectivity, which plays out between the nb_units LSTM cells only. So, setting output_size = n = 10 in your formula above for params will give the desired 480 parameters.
type: Answer
answers question: http://stackoverflow.com/q/50947079
score: 0

http://stackoverflow.com/q/50901391
accepted answer: http://stackoverflow.com/a/50901450
score: -1
has comment: http://stackoverflow.com/comment/88804935
upvote count: 2
downvote count: 3
has comment: http://stackoverflow.com/comment/88803088
answer count: 1
has answer: http://stackoverflow.com/a/50901450
favorite count: 0
has title: Library for reading blk00000.dat file either using Python or NodeJS
tagged with: python
tagged with: node.js
type: AnsweredQuestion
tagged with: blockchain
has comment: http://stackoverflow.com/comment/88802640
has body: I would like to know if there are any libraries that would be able to read blk00000.dat file. It can be either in Python or NodeJS libraries. Please recommend me some of the ones that you guys think is useful for working with blockchain.
type: Question

http://stackoverflow.com/q/50913322
downvote count: 2
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/88827055
has comment: http://stackoverflow.com/comment/88826888
has body: Say I have this Python dict: dict = { ((0,0), 'A'): 0.0, ((0,0), 'B'): 0.7, ... ((2,4), 'C'): 0.2, ...} I want to find the maximum value for a given nested tuple like (0,0). Something like: max(dict((0,0), *). In this case it should return 0.7, how to do this?
accepted answer: http://stackoverflow.com/a/50913682
score: 0
has answer: http://stackoverflow.com/a/50913917
has answer: http://stackoverflow.com/a/50913653
answer count: 3
has title: Finding max in Python dict with nested tuple keys
possible better answer: http://stackoverflow.com/a/50913653
tagged with: max
type: AnsweredQuestion
tagged with: nested
has answer: http://stackoverflow.com/a/50913682
has comment: http://stackoverflow.com/comment/88828194
favorite count: 0
tagged with: tuples
type: Question
upvote count: 2

http://stackoverflow.com/q/50998203
tagged with: loops
type: Question
has answer: http://stackoverflow.com/a/50998375
has body: My code is here I want to open a youtube link and it will get refresh after 10 seconds here my code but it cant execute please help me : import os import time import webbrowser cycles=12 num=3 delay=0.10 chromedir = 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s' website = input("http:\youtu.be/RsWCo_xGXxY") hits=cycles*num print("You will access " +website+ " " , hits, " times") for i in range(cycles): for i in range(0,num): webbrowser.get(chromedir).open(website) time.sleep(delay) os.system("tskill /A iexplore") os.system("tskill /A Chrome")
has comment: http://stackoverflow.com/comment/88990442
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88990541
has comment: http://stackoverflow.com/comment/88990571
has comment: http://stackoverflow.com/comment/88990565
tagged with: python
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88990467
upvote count: 2
score: 0
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/88990709
has title: open a website and refresh it as per the time using spyder (python)
has comment: http://stackoverflow.com/comment/88990458
has comment: http://stackoverflow.com/comment/88990568
has comment: http://stackoverflow.com/comment/88990574

http://stackoverflow.com/comment/88820066
type: AnswerComment
comment on: http://stackoverflow.com/a/50910005
score: 0
type: Comment
has text: Python has not to be edited. The python is a bogus example. OP intent is to bruteforce a program. You can't edit the program to make it custom bruteforce-able. The goal is rather to find a way to feed the single password and iterate.

http://stackoverflow.com/q/50884136
has body: I'm new to Python and I was trying to create a quiz but I don't know how to make the procedure. The quiz is a phrase with gaps and you need to put the right word in the gaps. If the word is correct, print the phrase with the correct word in the gap. If wrong, print try again. I'm trying something like this: phrase = 'HTML is HyperText __1__ __2__.' answers = ['Markup','Language'] def quiz(p,a): """ I can do it manually with if statements, but this is not a good idea."""" Can someone help me?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88770198
downvote count: 2
has comment: http://stackoverflow.com/comment/88770493
tagged with: loops
type: Question
has title: How to make a Quiz with Loops in Python?
tagged with: automation
upvote count: 0
has answer: http://stackoverflow.com/a/50892869
score: -2
has comment: http://stackoverflow.com/comment/88770276
has comment: http://stackoverflow.com/comment/88770208
answer count: 1
has comment: http://stackoverflow.com/comment/88770186
favorite count: 0
accepted answer: http://stackoverflow.com/a/50892869
linked to: http://stackoverflow.com/q/23294658
has comment: http://stackoverflow.com/comment/88770258
tagged with: python
has comment: http://stackoverflow.com/comment/88784617
has comment: http://stackoverflow.com/comment/88770358

http://stackoverflow.com/q/50979828
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88955587
score: 1
tagged with: openpyxl
upvote count: 1
has title: How to find a value in excel sheet and then write another value in a different cell in the same row with openpyxl
has body: I am trying to search for a specific value in rows of an excel file. Upon finding a matching value, I would like to write another value in the column next to the found value in the same row. For instance, if I am looking for the word "test" and find it in cell A3, I would then want to print a specified value, say 6, in cell B3. If it makes a difference, I do anticipate only having to search the A column for the value and always printing the other value to the B column in the same row. Here is the code I have so far. wb = openpyxl.load_workbook(path) ws = wb.get_sheet_by_name('Sheet') for row in ws.iter_rows(): for cell in row: if cell.value == "test": ws.cell(row=cell, column=2).value = 6 wb.save(path) Any help would be greatly appreciated!
tagged with: excel
type: Question
accepted answer: http://stackoverflow.com/a/50981351
has comment: http://stackoverflow.com/comment/88955484
possible better answer: http://stackoverflow.com/a/50979960
answer count: 2
has answer: http://stackoverflow.com/a/50979960
downvote count: 0
has comment: http://stackoverflow.com/comment/88955602
favorite count: 0
has answer: http://stackoverflow.com/a/50981351

http://stackoverflow.com/q/50966406
tagged with: python
upvote count: 1
has title: How can i make the car visible on top of the background?
possible better answer: http://stackoverflow.com/a/50966633
has answer: http://stackoverflow.com/a/50966633
has answer: http://stackoverflow.com/a/50968477
downvote count: 0
tagged with: racing
type: AnsweredQuestion
tagged with: layer
has body: I was confused about how to make the user's car be visible on top of the background. At the moment, when you move the car the track and car move as they should, but the car is under the racetrack. I have tried different blitting orders and i attempted the LayeredUpdates function but it didn't help. I may have been doing it wrong as i am very new to python/pygame. So i would like to know how to get the car to be driving on the track. Thank you import math import random import pygame pygame.mixer.pre_init(44100,16,2,4096) pygame.init() screen = pygame.display.set_mode((1280, 800)) rect = screen.get_rect() clock = pygame.time.Clock() #music pygame.mixer.music.load("Wice.mp3") pygame.mixer.music.set_volume(0.5) pygame.mixer.music.play(-1) WHITE = pygame.Color('white') VEHICLE1 = pygame.Surface((40, 70), pygame.SRCALPHA) VEHICLE1.fill((130, 180, 20)) #blitting car onto 'rectangle car' VEHICLE1 = pygame.image.load("YellowLambo.png") screen.blit(VEHICLE1,(0,0)) pygame.display.update() VEHICLE2 = pygame.Surface((40, 70), pygame.SRCALPHA) VEHICLE2.fill((200, 120, 20)) #blitting computer's car VEHICLE2 = pygame.image.load("RedLambo.png") screen.blit(VEHICLE2,(0,0)) BACKGROUND = pygame.Surface((1280, 800)) BACKGROUND.fill((127, 69, 2)) BACKGROUND = pygame.image.load("track1.png").convert() screen.blit(BACKGROUND,(0,0)) pygame.display.update() class Entity(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) class VehicleSprite(Entity): MAX_FORWARD_SPEED = 10 MAX_REVERSE_SPEED = 2 ACCELERATION = 0.05 TURN_SPEED = 0.000000000001 def __init__(self, image, position): Entity.__init__(self) self.src_image = image self.image = image self.rect = self.image.get_rect(center=position) self.position = pygame.math.Vector2(position) self.velocity = pygame.math.Vector2(0, 0) self.speed = self.direction = 0 self.k_left = self.k_right = self.k_down = self.k_up = 0 def update(self, time): # SIMULATION self.speed += self.k_up + self.k_down # To clamp the speed. self.spe…
tagged with: pygame
score: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/50968477
type: Question
answer count: 2

http://stackoverflow.com/comment/88778822
comment on: http://stackoverflow.com/q/50888683
type: Comment
score: 1
type: QuestionComment
has text: See Zev's explanation. and use http://regex101.com for testing of regex - you even get an explanation for any pattern you provide. I find it better then pythex - and it also got a `python` regex switch

http://stackoverflow.com/comment/88985746
type: Comment
type: QuestionComment
has text: You can't declare an editable dependency in setup script. You can pass a path to the dependency source files, e.g. via `dependency_links` or `pip`'s `find-links`, but it will install the dependency in normal, non-editable mode.
comment on: http://stackoverflow.com/q/50957833
score: 0

http://stackoverflow.com/q/51007157
type: AnsweredQuestion
downvote count: 3
has comment: http://stackoverflow.com/comment/89007529
type: Question
possible better answer: http://stackoverflow.com/a/51007185
has body: Example: File will be called "Sentences.dat". It will have these lines. Name #3 is Bob Name #7 is Marie Name #8 is Kate Name #2 is George I want to save these to a dictionary, where their number is the key and their name is the value. This is what I have so far. file = open("Sentences.dat","r") dictNames = {} line = 1 while True: content = file.readlines()[line] split = content.split() dictNames[split[1]] = split[3] line = line + 1
has answer: http://stackoverflow.com/a/51007185
accepted answer: http://stackoverflow.com/a/51007183
score: -1
has title: How to obtain second and fourth word from each line in a file
answer count: 3
has answer: http://stackoverflow.com/a/51007243
has comment: http://stackoverflow.com/comment/89007551
favorite count: 0
has comment: http://stackoverflow.com/comment/89007538
upvote count: 2
has answer: http://stackoverflow.com/a/51007183
tagged with: python

http://stackoverflow.com/a/50984516
has comment: http://stackoverflow.com/comment/89008994
has comment: http://stackoverflow.com/comment/89005127
upvote count: 1
type: AcceptedAnswer
downvote count: 0
has body: I've tried your given code. I was getting NaN right from the first step. And I've checked the official documentation. logits: Unscaled log probabilities of shape [d_0, d_1, ..., d_{r-1}, num_classes] and dtype float32 or float64. Changed enc = tf.ones((1,20,1024), dtype=tf.float16) to enc = tf.ones((1,20,1024), dtype=tf.float32) and it worked!
answers question: http://stackoverflow.com/q/50975389
type: Answer
accepted answer of: http://stackoverflow.com/q/50975389
score: 1

http://stackoverflow.com/a/51005443
answers question: http://stackoverflow.com/q/51005426
upvote count: 1
score: 1
has body: This would do it. You would add each number that you generate to a new list. You then access the first 200 items in the list using slice notation, and print it out. import random list = ['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'] new_list = [] for i in range(400): k = random.randint(0, 25) print(list[k], end='') new_list.append(list[k]) if i % 100 == 0: print('') print(new_list[:200]) I will add, however, that generating 400 random letters, and printing 100 per line across 4 lines (which seems to be what your complex for loop is doing), would be achieved faster and more idiomatically using the following: import random letters = ['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'] random_400 = random.choices(letters, k=400) for i in range(len(letters)/100+1): print " ".join(letters[i*100:(i+1)*100]) + "\n"
downvote count: 0
type: Answer

http://stackoverflow.com/comment/92047594
type: Comment
type: QuestionComment
has text: Did you found the solution? Passing the value from one page to another? In my case I want to pass the hyperlink value to another page.
score: 0
comment on: http://stackoverflow.com/q/50977636

http://stackoverflow.com/q/50856859
tagged with: pandas
tagged with: function
answer count: 1
has title: Create a new pandas columns from multiple columns
downvote count: 0
favorite count: 0
tagged with: python
tagged with: lambda
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50856918
score: 1
upvote count: 1
has body: Here is the dataframe MatchId EventCodeId EventCode Team1 Team2 Team1_Goals Team2_Goals xG_Team1 xG_Team2 CurrentPlaytime 0 865314 1029 Goal Home Northampton Crawley Town 2 2 2.067663207769023 0.8130662505484256 457040 1 865314 1029 Goal Home Northampton Crawley Town 2 2 2.067663207769023 0.8130662505484256 1405394 2 865314 2053 Goal Away Northampton Crawley Town 2 2 2.067663207769023 0.8130662505484256 1898705 3 865314 2053 Goal Away Northampton Crawley Town 2 2 2.067663207769023 0.8130662505484256 4388278 4 865314 1029 Goal Home Northampton Crawley Town 2 2 2.067663207769023 0.8130662505484256 4507898 5 865314 1030 Cancel Goal Home Northampton Crawley Town 2 2 2.067663207769023 0.8130662505484256 4517728 6 865314 1029 Goal Home Northampton Crawley Town 2 2 2.067663207769023 0.8130662505484256 4956346 7 865314 1030 Cancel Goal Home Northampton Crawley Town 2 2 2.067663207769023 0.8130662505484256 4960633 8 865316 2053 Goal Away Coventry Bradford 0 0 1.0847662440468118 1.2526705617472387 447858 9 865316 2054 Cancel Goal Away Coventry Bradford 0 0 1.0847662440468118 1.2526705617472387 456361 The new columns will be created as follows: for EventCodeId = 1029 and EventCode = Goal Home new_col1 = CurrentPlaytime/3*10**4 for EventCodeId = 2053 and ventCode = Goal Away new_col2 = CurrentPlaytime/3*10**4 For every other EventCodeId and EventCode new_co1 and new_col2 will take 0. Here is how I have started but couldn't go any further. please help new_col1 = [] new_col2 = [] def timeslot(EventCodeId, EventCode, CurrentPlaytime): if x == 1029 and y == 'Goal Home': new.Col1.append(z/(3*10**4)) elif x == 2053 and y == 'Goal Away': new_col2.append(z/(3*10**4)) else: new_col1.append(0) new_col2.append(0) return new_col1 return new_col2 df1['new_col1', 'new_col2'] = df1.apply(lambda x,y,z: timeslot(x['EventCodeId'], y['EventCode'], z['CurrentPlaytime']), axis=1) TypeError: ("&lt;lambda&gt;() missing 2 required positional arguments: 'y' and 'z'", 'occurred at index 0')
type: Question
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/50856918

http://stackoverflow.com/q/50862291
type: UnansweredQuestion
has title: mongodb binary regex pymongo
tagged with: binary
type: Question
tagged with: python
has body: Can i use regex find in pymongo on fields created with bson.binary.Binary? I have some objects created with collection.insert_one({"data": bson.binary.Binary(some_bin_data)}). I'm trying collection.find({"data": {"$regex": str(rg)}}), collection.find({"data": {"$regex": bson.regex.Regex(rg)}}) and collection.find({"data": {"$regex": re.compile(rg)}}) to filter objects with a regex but they don't work. I can't find nothing about it in the pymongo docs. Alternatively, there is another way to store binary data in a mongodb field and use regex?
score: 0
tagged with: pymongo
has comment: http://stackoverflow.com/comment/89489074
answer count: 1
tagged with: mongodb
has answer: http://stackoverflow.com/a/51250689
tagged with: bson

http://stackoverflow.com/q/50954569
score: 0
answer count: 1
has body: I am trying to merge arrays like following code: import numpy as np from numpy import column_stack as column_stack from matplotlib.pyplot import plot as plot from matplotlib.pyplot import show as show N = 120 Yq = np.arange(0,N-1) YY = Yq[N//2:]-N + Yq + Yq[:N//2]+N #YY = column_stack( (Yq[N//2:]-2*PI, Yq, Yq[:N//2]+2*PI)) plot(YY) show() I tried '+' and column_stack(), but neither works. How do I make it work to merge three arrays? Thanks.
tagged with: arrays
type: AnsweredQuestion
has title: merging multiple arrays together giving error
has answer: http://stackoverflow.com/a/50954693
type: Question
accepted answer: http://stackoverflow.com/a/50954693
tagged with: python
tagged with: list

http://stackoverflow.com/comment/89008636
has text: I just want to know what will be the best approach to move forward. I can split them into two columns, so that only numbers will be there. OR Do I have to maintain this format (As it is mentioned as an Independent Variable in the data set). But if I maintain this format then it will be very hard for me to convert it into numbers.. Please give me ideas whether to maintain this format or I can split as per my requirement.
score: 0
comment on: http://stackoverflow.com/q/51007631
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50938119
downvote count: 3
tagged with: django-models
type: Question
has answer: http://stackoverflow.com/a/50938424
accepted answer: http://stackoverflow.com/a/50938424
answer count: 1
has title: create time stamps tuple python
has comment: http://stackoverflow.com/comment/88874485
favorite count: 0
upvote count: 0
has body: I would like to create a tuple of time stamps. Where If I define a function like def time_stamps(starttime,endtime,intervals): #start time of tuple like 08:00:00 #End time of tuple like 21:00:00 #With Intervals of 60 or 30 0r 90 minutes. #example : if i call the function #x = time_stamps(08:00:00,21:00:00,00:30:00) #It should generate a tuple like this #('08:00:00','08:30:00','09:00:00',....,'20:30:00','21:00:00) I am lost.Please Help. Thank you
score: -3
tagged with: django
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88874499
has comment: http://stackoverflow.com/comment/88874540

http://stackoverflow.com/q/50881652
score: 0
has answer: http://stackoverflow.com/a/50881811
tagged with: pandas
answer count: 1
linked to: http://stackoverflow.com/q/27365467
tagged with: python
has title: Pandas histogram of dates with empty bins
type: UnansweredQuestion
tagged with: matplotlib
has body: My use case is very simliar to this post, but my data is not continuous through each bin. I'm attempting to create multiple figures over the same time span to show activity (or lack thereof) over 18 months. I thought I hit the jackpot with the df.groupby(df.date.month).count() approach, but since my data is irregular I get different bins per dataset. My question, then, is how would I go about creating some kind of master x-axis with fixed bins (month,year) and plot each dataset against these bins. I think I'm missing some fundamental understanding of either Pandas or MPL, and I apologize for what I'm sure is a silly question. First post, go easy... Since I can't comment yet, I'll edit here: I have 18 months generated with pd.period_range. I also have a DataFrame full of observations with timestamps within those months. Some of months have zero observations. How do I effectively count and chart the observations by month?
linked to: http://stackoverflow.com/q/43500894
type: Question

http://stackoverflow.com/q/50862085
type: Question
type: AnsweredQuestion
score: 3
tagged with: docker-compose
has body: I'm building an image with some Python packages, here is my Dockerfile: FROM openjdk:8-alpine RUN apk update &amp;&amp; apk add bash gcc musl-dev RUN apk add python3 python3-dev RUN apk add py3-pip RUN apk add libxslt-dev libxml2-dev ENV PROJECT_HOME /opt/app RUN mkdir -p /opt/app RUN mkdir -p /opt/app/modules # This is needed for Jep, otherwise it doesn't run ENV LD_LIBRARY_PATH /usr/lib/python3.6/site-packages/jep ENV LD_PRELOAD /usr/lib/libpython3.6m.so RUN pip3 install jep RUN pip3 install googleads RUN pip3 install gspread RUN pip3 list COPY target/my-server-1.0-SNAPSHOT.jar $PROJECT_HOME/my-server-1.0-SNAPSHOT.jar WORKDIR $PROJECT_HOME CMD ["java", "-Dspring.data.mongodb.uri=mongodb://my-mongo:27017/mydb","-jar","./my-server-1.0-SNAPSHOT.jar"] Now, even though I see the installed packages at build time (and it's a big list that pip3 list returns..., when I start the container, I don't see on it any of the packages installed out of jep. /opt/app # pip3 list jep (3.7.1) pip (9.0.1) setuptools (28.8.0) /opt/app # This is how i'm building the image: docker build -t my-server . And this is how I'm checking the installed libs: bash -c "clear &amp;&amp; docker exec -it my-server sh" pip3 list The interesting part is that the same "pip3 list" command ran at build time returns the whole list of libs, but inside of the container, just a few of them... UPDATE 1 It turns out that if I start the container manually, I indeed see all the libs, but I've been (and I have to) starting the container with docker-compose. And somehow when I do that I don't see all the libs, this is my docker-compose config for that image: services: my-server: build: . restart: always container_name: my-server ports: - 8200:8200 working_dir: /opt/app volumes: - $HOME/data/Modules:/opt/app/modules depends_on: - mongo Any help is appreciated, Thanks!
has comment: http://stackoverflow.com/comment/88727468
has comment: http://stackoverflow.com/comment/88728262
has comment: http://stackoverflow.com/comment/88728350
has comment: http://stackoverflow.com/comment/88728045
has comment: http://stackoverflow.com/comment/88729010
has comment: http://stackoverflow.com/comment/88726907
answer count: 1
favorite count: 0
tagged with: docker
upvote count: 3
has title: Python libraries missing in docker container after they were installed on img build
has comment: http://stackoverflow.com/comment/88728871
tagged with: docker-for-mac
tagged with: python
has comment: http://stackoverflow.com/comment/88728000
has answer: http://stackoverflow.com/a/50863694
accepted answer: http://stackoverflow.com/a/50863694
downvote count: 0
tagged with: pip
has comment: http://stackoverflow.com/comment/88728820
has comment: http://stackoverflow.com/comment/88728154

http://stackoverflow.com/a/50950369
has comment: http://stackoverflow.com/comment/88900570
has comment: http://stackoverflow.com/comment/107545025
type: Answer
has comment: http://stackoverflow.com/comment/88899143
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/88898977
answers question: http://stackoverflow.com/q/50948608
has comment: http://stackoverflow.com/comment/88900724
has comment: http://stackoverflow.com/comment/114825251
has body: taking a closer look at the website and your code it appears that the problem occurs due to your header, the way you are sending one of your requests, and a post request that you aren't sending. Problem 1: Header as we can see your header is fairly big. Even though a big header isn't equal to a bad header but in your case you are sending a fair amount of useless items in the header that may potentially confuse the server so I try replacing you header with the following one: headers = {'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Content-Type':'application/x-www-form-urlencoded', 'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:54.0) Gecko/20100101 Firefox/54.0'} as you see I have removed quite a few things from it. Problem 2: Wrong way of sending a request (in your case): The whole goal of requests.session() is to keep track of all the cookies and prevent you from manually injecting them into each of your requests. thus you should change this: get_data=s.get(url=url_get,headers=headers, cookies=s.cookies) to this: get_data=s.get(url=url_get,headers=headers) (The cookies will be inserted into automatically each time you use requests.session when sending a request) Problem 3: The Request That you didn't send as noted before your problem occurs because you forgot to send a post request. I won't go into details on this but the request you are missing is this one: s.get(url='https://www.timeform.com/horse-racing/account/sign-in', headers=headers) All in all, after all these changes your code should look something like this: import requests url_get='https://www.timeform.com/horse-racing/result/brighton/2018-06-11/0200/6/1/phoenix-arts-club-fillies-handicap' url_post_pgin='https://www.timeform.com/horse-racing/account/handlelogin?returnUrl=%2Fhorse-racing%2F' url_post_pgin2='https://www.timeform.com/horse-racing/account/sign-in' payload = {"EmailAddress":"mymail@gmail.com","Password":"XXXXXXXXX","RememberMe":"true"} headers = {'Acce…
has comment: http://stackoverflow.com/comment/88899982
has comment: http://stackoverflow.com/comment/88900745
has comment: http://stackoverflow.com/comment/88899373
downvote count: 0

http://stackoverflow.com/q/50924057
has title: how to use multiple DB connections in python unit test
tagged with: sqlalchemy
has comment: http://stackoverflow.com/comment/88847688
type: Question
score: 0
tagged with: postgresql
tagged with: python
has comment: http://stackoverflow.com/comment/88850875
answer count: 0
has comment: http://stackoverflow.com/comment/88847838
type: UnansweredQuestion
has body: I need to use multiple connections in my python test code. But the problem I'm facing is that the second connection does not see statements executed in the first one. As far as I understand autocommit should be ON by default. Here is the code import testing.postgresql from sqlalchemy import create_engine def test_simple(): with testing.postgresql.Postgresql() as postgresql: try: engine = create_engine(postgresql.url()) conn = engine.connect().connection with conn.cursor() as cur: cur.execute("""CREATE TABLE country (id integer, name text); INSERT INTO country(id, name) VALUES (1, 'Mali'); INSERT INTO country(id, name) VALUES (2, 'Congo'); """) # OK cur.execute('select * from country') countries = cur.fetchall() print(str(countries)) # ERROR psycopg2.ProgrammingError: relation "country" does not exist conn1 = engine.connect().connection with conn1.cursor() as cur1: cur1.execute('select * from country') countries1 = cur1.fetchall() print(str(countries1)) finally: conn.close() conn1.close() How can I use multiple connections in my test?

http://stackoverflow.com/comment/88770480
comment on: http://stackoverflow.com/a/50880104
score: 0
type: AnswerComment
type: Comment
has text: hi @Patrick i updated `on_command_error` which i added for `commands.CommandInvokeError` above.

http://stackoverflow.com/q/50899951
has answer: http://stackoverflow.com/a/50900518
accepted answer: http://stackoverflow.com/a/50900313
has comment: http://stackoverflow.com/comment/88800245
downvote count: 1
has body: How would you 1) insert 1's between any two adjacent 5's? and then 2) insert a value into the second list at the same index as the 1 that was inserted into the first list? For example, list1 = [ 5, 1, 5, 5, 5, 1, etc.] would become list1 = [ 5, 1, 5, 1, 5, 1, 5, 1, etc.] And, list2 = [ val, val, val, val, val, val, etc.] would become list2 = [ val, val, val, Nval, val, Nval, etc.] (Nval up above = the added value) I'm a beginner so help is greatly appreciated :O)
type: Question
possible better answer: http://stackoverflow.com/a/50900414
has comment: http://stackoverflow.com/comment/88800897
has comment: http://stackoverflow.com/comment/88799861
tagged with: arrays
has title: How do you insert a number in between two adjacent numbers?
has comment: http://stackoverflow.com/comment/88800248
has comment: http://stackoverflow.com/comment/88800217
has comment: http://stackoverflow.com/comment/89052567
linked to: http://stackoverflow.com/q/509211
has answer: http://stackoverflow.com/a/50900313
favorite count: 0
has answer: http://stackoverflow.com/a/50900597
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88799845
answer count: 5
tagged with: python
has answer: http://stackoverflow.com/a/50900710
has comment: http://stackoverflow.com/comment/88799827
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50900414
upvote count: 2
score: 1
has comment: http://stackoverflow.com/comment/88800123

http://stackoverflow.com/q/51011311
has title: Automatic input in web tool and save the output files using Python
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/89015577
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89015532
tagged with: web-crawler
tagged with: webautomation
type: Question
has body: Here is a web-based tool for some chemical computation link here. Entering the data in the input box as follows, then enter "run", a data report can be exported. For example, relative humidity: 0.45, H+: 0.2, SO42-: 1.1, NH4+: 3, NO3-: 1 Saving the output data table The generated table shown like follows is what I want to acquire. Since I have a lot of dataset as the input data， is there any method to import those data, and save the output results. Any advice or tutorial would be appreciated.

pyodbc
tags question: http://stackoverflow.com/q/50862705
type: Tag
tags question: http://stackoverflow.com/q/50873007
tag name: pyodbc

http://stackoverflow.com/q/50871343
upvote count: 1
answer count: 1
tagged with: matplotlib
type: UnansweredQuestion
tagged with: bezier
has answer: http://stackoverflow.com/a/50873999
downvote count: 0
score: 1
has body: I started from a similar problem as mentioned here: Draw rounded fancyarrowpatch with midpoint arrow in matplotlib Just that I would like to add a label to an arrow, ideally in variable places. I tried to reconstruct coordinates with the path vertices, but the labels still were all over the place. Then, I tried to follow the description of the connectionstyle arc3 (https://matplotlib.org/api/_as_gen/matplotlib.patches.ConnectionStyle.html?highlight=connectionstyle) class Arc3(rad=0.0) Creates a simple quadratic bezier curve between two points. The curve is created so that the middle control point (C1) is located at the same distance from the start (C0) and end points(C2) and the distance of the C1 to the line connecting C0-C2 is rad times the distance of C0-C2. I reconstructed this and noticed that the Curve drawn by FancyArrowPatch is NOT the same as a quadratic Bezier curve with the specified points. Minimal example: import numpy import matplotlib from matplotlib import pyplot as plt import matplotlib.path as mpath import matplotlib.patches as mpatches from matplotlib.patches import FancyArrowPatch, Circle fig = plt.figure(frameon=False) ax = fig.add_subplot(111, frame_on=False) rad=0.3 shrink=0.3 # Setting up circles as start and end points size = 0.1 n1 = Circle([0,0], radius=size, alpha=0., fill=False, linewidth=0.1) n2 = Circle([1,1], radius=size, alpha=0., fill=False, linewidth=0.1) ax.add_patch(n1) ax.add_patch(n2) # Create a fancy arrow between start and end point e = FancyArrowPatch(n1.center, n2.center, connectionstyle='arc3,rad=%s' % rad, arrowstyle='simple', clip_on=False, linewidth=2., shrinkA=shrink,shrinkB=shrink ) ax.add_patch(e) # Start point vs=numpy.asarray(n1.center) # End point ve=numpy.asarray(n2.center) # Connection vector start-&gt;end vD=ve-vs # Perpendicular vector to vD vp=numpy.asarray([vD[1],-vD[0]]) # Control point: same distance from start and end point, and rad*|vD| from the connection line between start and end vc=vs+0.5*vD+rad*vp P…
has comment: http://stackoverflow.com/comment/88749453
favorite count: 0
linked to: http://stackoverflow.com/q/35177675
type: Question
has comment: http://stackoverflow.com/comment/88749097
tagged with: python
has title: connectionstyle arc3 (FancyArrowPatch) and path CURVE3 - two quadratic Bezier curves, different outcomes?

http://stackoverflow.com/q/51006989
score: 12
has answer: http://stackoverflow.com/a/60690526
has body: When I load files via Visual Studio Code, VScode can't find directory. I can run code without issue with terminal, result is: young@young-desktop:/media/young/5e7be152-8ed5-483d-a8e8-b3fecfa221dc/text/mycodehtml/pracdl/golbin/TensorFlow-Tutorials/10_RNN/ChatBot$ python text_load_text.py ['fij\n', 'feijfaef\n', 'ef\n', 'awef\n', 'awe\n', 'g\n', 'aweg\n', 'ae\n', 'wg\n', 'awe\n', 'h\n', 'aw\n', 'h\n', 'aw\n', 'ef\n', 'aweg\n', 'wea\n', 'gaw\n', 'eg\n', '\n'] But with VScode: young@young-desktop:/media/young/5e7be152-8ed5-483d-a8e8-b3fecfa221dc/text/mycodehtml/pracdl/golbin/TensorFlow-Tutorials$ cd /media/young/5e7be152-8ed5-483d-a8e8-b3fecfa221dc/text/mycodehtml/pracdl/golbin/TensorFlow-Tutorials ; env "PYTHONIOENCODING=UTF-8" "PYTHONUNBUFFERED=1" /home/young/anaconda3/bin/python /home/young/.vscode/extensions/ms-python.python-2018.6.0/pythonFiles/PythonTools/visualstudio_py_launcher.py /media/young/5e7be152-8ed5-483d-a8e8-b3fecfa221dc/text/mycodehtml/pracdl/golbin/TensorFlow-Tutorials 39707 34806ad9-833a-4524-8cd6-18ca4aa74f14 RedirectOutput,RedirectOutput /media/young/5e7be152-8ed5-483d-a8e8-b3fecfa221dc/text/mycodehtml/pracdl/golbin/TensorFlow-Tutorials/10_RNN/ChatBot/text_load_text.py Traceback (most recent call last): File "/media/young/5e7be152-8ed5-483d-a8e8-b3fecfa221dc/text/mycodehtml/pracdl/golbin/TensorFlow-Tutorials/10_RNN/ChatBot/text_load_text.py", line 8, in &lt;module&gt; with open('test.txt', 'r') as f: FileNotFoundError: [Errno 2] No such file or directory: 'test.txt' What causes this issue? test.txt file originally is intended to be located in ./data/test.txt So I tested with open('./data/test.txt', 'r') as f: But it failed with VScode So I tried to move test.txt file to working directory with trying: with open('test.txt', 'r') as f: and with open('./test.txt', 'r') as f: But all failed with VScode.
has answer: http://stackoverflow.com/a/76928484
linked to: http://stackoverflow.com/q/12201928
has comment: http://stackoverflow.com/comment/137114918
has answer: http://stackoverflow.com/a/64188757
has comment: http://stackoverflow.com/comment/89007261
has answer: http://stackoverflow.com/a/58653565
answer count: 7
favorite count: 0
linked to: http://stackoverflow.com/q/18062759
has title: Visual Studio Code: FileNotFoundError: [Errno 2] No such file or directory
type: UnansweredQuestion
tagged with: path
tagged with: python
downvote count: 1
upvote count: 13
has answer: http://stackoverflow.com/a/51007081
has comment: http://stackoverflow.com/comment/89007213
has answer: http://stackoverflow.com/a/68401059
has answer: http://stackoverflow.com/a/52729875
type: Question

http://stackoverflow.com/comment/88764935
type: Comment
has text: What are the coordinates of `frame`? So you just want to replace a part of `frame` with `data`?
comment on: http://stackoverflow.com/q/50881318
type: QuestionComment
score: 0

http://stackoverflow.com/comment/88848542
type: QuestionComment
score: 0
has text: Index the collection and sort it on the first stage.
type: Comment
comment on: http://stackoverflow.com/q/50921048

http://stackoverflow.com/q/50905438
type: Question
has comment: http://stackoverflow.com/comment/89346651
tagged with: cluster-analysis
downvote count: 0
has comment: http://stackoverflow.com/comment/88833330
has comment: http://stackoverflow.com/comment/89344632
favorite count: 0
answer count: 0
type: UnansweredQuestion
tagged with: python
score: 3
has title: How to implement a clustering process, using a genetic algorithm in python?
tagged with: genetic-algorithm
upvote count: 3
has comment: http://stackoverflow.com/comment/88820078
has body: I'm a novice in python coding. I have a question regarding clustering using genetic algorithm in python. I would like to cluster the station based on not only distance but also the other index of the cluster. I want to maximize the total index of all clusters. I have 900 bike stations GPS coordinate data. I have already created a distance matrix of [all stations] x [all stations]. Units are in [km]. Basic idea - draw random circles of clusters. If I want to cluster in 50 clusters, then the code should generate 50 different circles of clusters. The station inside the circlen, it will be labeled in clustern. The example is shown in the image below There are some restrictions to generate circles, the cluster circles should not be overlapping. - to satisfy this condition, distance between two center of the circles should be larger than the sum of radii. ( but I don't know how to code with python ) the radius of circle limits in size. ( It should be found in hyperparameter, but minimum of 1 km and maximum of 4 km is the first candidate ) While clustering, stations that cannot go into the circle cluster will occur. For this case we should allocate these stations to the nearest circle based on the distance. After we successfully generate the random not overlapping 50 cluster circles, I want to find the best combination of the circles which can maximize my own index. Genetic algorithm gene : { x1, y1, r1, x2, y2, r2, x3, y3, r3, ... x50, y50, r50 } [ xn, yn ] is the center of the circle and rn is the radius of the circle. The center of the cluster should be a station rather than a point within the map. Meaning that each 50 clusters center point should be a station. rn generate randomly within the boundary. For example, if I want to make a cluster 1km &lt; rn &lt; 4km, than r can be generated randomly in a 100 [m] interval. So, r can get a values like in { 1.1km, 1.2km, ... 3.9km, 4km } Division point will be: { x1, y1, r1,/ x2, y2, r2,/ x3, y3, r3,/ ... / x50, y50, r50 } Fi…

http://stackoverflow.com/q/50915610
tagged with: python
favorite count: 0
tagged with: mapping
upvote count: 2
type: UnansweredQuestion
downvote count: 1
has body: I have tried mutliple things (maps, filters, joins), but nothing seems to work. What I am trying to do is best described by the following table: (I need to get the "required" column) colA colB colC ref required 1 a1 b1 c1 colA a1 2 a2 b2 c2 colA a2 3 a3 b3 c3 colB b3 4 a4 b4 c4 colB b4 5 a5 b5 c5 colC c5 6 a6 b6 c6 colC c6 The above is just an example - in the real example I have >50 columns, so doing conditions is not going to work... Any suggestions how to do this?
score: 1
tagged with: dataframe
tagged with: slice
type: Question
has comment: http://stackoverflow.com/comment/88831289
answer count: 2
has answer: http://stackoverflow.com/a/50915654
has comment: http://stackoverflow.com/comment/88831212
has answer: http://stackoverflow.com/a/50915753
tagged with: pandas
has title: Pandas - create column based on column names referenced in another column

http://stackoverflow.com/q/50961538
has comment: http://stackoverflow.com/comment/88919942
tagged with: python
has answer: http://stackoverflow.com/a/50962284
has comment: http://stackoverflow.com/comment/88919984
has comment: http://stackoverflow.com/comment/88919891
has comment: http://stackoverflow.com/comment/88920050
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/88920310
has body: What is the best practice to try to open the file and retry after n seconds? Currently, I do: import os from os import path import shutil dir_path = path.abspath(path.join("foo", "bar")) destination_path = path.abspath(path.join("foo", "dest_dir")) for f in dir_path: try: # try to open the file if the file isn't used any longer file_opened = open(f, 'r') # move the file on successful opening shutil.move(file_opened, destination_path) file_opened.close() except IOError: return False So, at the moment I do not handle the exception. I think about creation of extra function to open the file and recall the function on excepth with time.sleep(n) However, I am sure there must be something else ... I do not use with open(f, 'rb') as file_opened: do whatever` EDIT: One process creates the file and I want Python process to move the file once I am sure the file writting / creation is completed. So, I have added shutil.move in the above code to show the whole situation. EDIT: Please find below the code I have developed to solve the problem. I ended with writing own custom solution to handle it: import os from os import path import psutil from retry import retry import shutil from subprocess import check_output,Popen, PIPE import glob import time class FileHandler: def __init__(self, fn_source, dir_source): self.file_source_name = fn_source self.file_source_path = path.join(dir_source, self.file_source_name) self.dir_dest_path = path.join(dir_source, "test") self.file_dest_path = path.join(self.dir_dest_path, self.file_source_name) def check_file(self): if os.path.exists(self.file_source_path): try: os.rename(self.file_source_path, self.file_source_path) print("file renamed") return True except: print("can not rename the file..retrying") time.sleep(1) self.check_file() else: print("source file does not exist...retrying") time.sleep(5) self.check_file() def check_destination(self): if os.path.exists(self.file_source_path) and not os.path.exists(self.file_dest_path): return True e…
upvote count: 3
tagged with: file
type: Question
has title: Python retry to open the file
answer count: 2
accepted answer: http://stackoverflow.com/a/50962284
possible better answer: http://stackoverflow.com/a/50962175
has comment: http://stackoverflow.com/comment/88920480
has answer: http://stackoverflow.com/a/50962175
has comment: http://stackoverflow.com/comment/88920028
has comment: http://stackoverflow.com/comment/88920004
tagged with: ioerror
downvote count: 0
has comment: http://stackoverflow.com/comment/88919983
favorite count: 0
linked to: http://stackoverflow.com/q/11114492
has comment: http://stackoverflow.com/comment/88920135

http://stackoverflow.com/q/50901119
has answer: http://stackoverflow.com/a/50901132
accepted answer: http://stackoverflow.com/a/50901132
has answer: http://stackoverflow.com/a/50901911
type: Question
score: 3
possible better answer: http://stackoverflow.com/a/50901130
has title: How to print only the unique items in a list, those occurring once?
has answer: http://stackoverflow.com/a/50901130
upvote count: 3
answer count: 3
favorite count: 0
tagged with: python-3.x
has body: def get_distinct(original_list): distinct_list = [] for i in original_list: if i not in distinct_list: distinct_list.append(each) return distinct_list list_1 = [1,2,3,4,4,5,6,6] print(get_distinct(list_1)) So I want it to print 1, 2, 3, 5 instead of 1,2,3,4,5,6
tagged with: python
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/88802236

http://stackoverflow.com/q/50977303
has title: Decorated function return multiple value
has comment: http://stackoverflow.com/comment/88950624
answer count: 1
has comment: http://stackoverflow.com/comment/88950625
accepted answer: http://stackoverflow.com/a/50977435
favorite count: 0
tagged with: python
score: 2
has body: I have the following decorator: def my_deco(limit=None): def wrap_outer(func): def wrap_inner(*args, **kwargs): return func(*args, **kwargs) return wrap_inner return wrap_outer It call the actual decorated function by func(*args, **kwargs) If a function return multiple values, this will return a single tuple that contains 3, and 4. How do I keep the multiple value returning behavior, instead of a tuple? @my_deco() def f(): return 3, 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88950792
upvote count: 3
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/50977435

multi-gpu
type: Tag
tags question: http://stackoverflow.com/q/50900736
tag name: multi-gpu

http://stackoverflow.com/a/50945256
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/50938332
type: Answer
has body: Go to run/debug configuration Click on green colored '+' button that is for "Add new Configuration " Select Python-tests > py.test Enter path to your script to Target Input. Enable key options (It's a checkbox) and give parameters into it. Refer this snapshot.
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50938332
type: AcceptedAnswer

http://stackoverflow.com/comment/88766001
type: QuestionComment
score: 0
has text: Check your grouping of your conditions in your liquid check for F and C
comment on: http://stackoverflow.com/q/50881837
type: Comment

http://stackoverflow.com/comment/124887686
type: AnswerComment
score: 0
type: Comment
has text: testing that, the metadata from get_blob() is None, other properties from blob are available.
comment on: http://stackoverflow.com/a/53264701

http://stackoverflow.com/comment/88915444
comment on: http://stackoverflow.com/a/50959017
type: AnswerComment
score: 0
type: Comment
has text: Okay just making sure, I'll add something to that effect.

http://stackoverflow.com/comment/88927624
type: Comment
comment on: http://stackoverflow.com/q/50965492
type: QuestionComment
has text: Can there be unpaired `(` and `)` in the entries? `asd(gh, e(a(b))`?
score: 0

http://stackoverflow.com/q/50899676
has body: Lets say I have a the following pandas data frame with the following columnar structure and the dataframe is titled df index column1 column2 column3 0 2 5 apple 1 4 3 apple 2 6 1 orange 3 8 6 apple 4 10 5 orange I would like to search the dataframe such that it will recognize every row where df['column3'] == orange and extract the value of df['column2'] in that row and insert it into the below function and then change the existing value of df[column2'] by the output of the function. def func(x): return x * 2.0 Thus far I have implemented the following, which works, but I suspect it is not the most pythonic way of doing this, and probably does not have the most efficient execution speed. Any advice would be appreciated. for i in range(len(df.index)): if df.loc[i, 'column3'] == 'orange': df.loc[i, 'column2'] = func(df.column2)
type: UnansweredQuestion
tagged with: pandas
has comment: http://stackoverflow.com/comment/88800720
has title: What is the Pythonic way to query a dataframe row for a keyword and manipulate the same row based on column values
favorite count: 0
has answer: http://stackoverflow.com/a/50899698
tagged with: series
tagged with: python-3.x
type: Question
tagged with: python
upvote count: 2
score: 0
downvote count: 2
answer count: 1
tagged with: performance

http://stackoverflow.com/comment/88904814
score: 0
type: Comment
has text: Okay, hope you will will do great in the future. If my answer does your work then you can accept it by pressing on the tick mark.
comment on: http://stackoverflow.com/a/50953524
type: AnswerComment

deep-learning
tags question: http://stackoverflow.com/q/50924072
tags question: http://stackoverflow.com/q/51003745
tags question: http://stackoverflow.com/q/50986580
tags question: http://stackoverflow.com/q/50945370
tags question: http://stackoverflow.com/q/50910828
tags question: http://stackoverflow.com/q/50933860
tags question: http://stackoverflow.com/q/51009991
tags question: http://stackoverflow.com/q/50941379
tags question: http://stackoverflow.com/q/50890836
tags question: http://stackoverflow.com/q/50978361
tags question: http://stackoverflow.com/q/50976749
tags question: http://stackoverflow.com/q/50924451
tags question: http://stackoverflow.com/q/50975586
tags question: http://stackoverflow.com/q/51007818
tags question: http://stackoverflow.com/q/50882282
tags question: http://stackoverflow.com/q/50913225
tags question: http://stackoverflow.com/q/51010312
tags question: http://stackoverflow.com/q/51008505
tags question: http://stackoverflow.com/q/50982503
tags question: http://stackoverflow.com/q/50867992
tags question: http://stackoverflow.com/q/50882259
tags question: http://stackoverflow.com/q/50978134
tags question: http://stackoverflow.com/q/50884631
tags question: http://stackoverflow.com/q/50988050
tags question: http://stackoverflow.com/q/50876996
tags question: http://stackoverflow.com/q/50888221
tags question: http://stackoverflow.com/q/50917450
tags question: http://stackoverflow.com/q/50995005
tags question: http://stackoverflow.com/q/50860861
tags question: http://stackoverflow.com/q/50898628
tags question: http://stackoverflow.com/q/50870437
tags question: http://stackoverflow.com/q/50860182
tags question: http://stackoverflow.com/q/50965217
type: Tag
tags question: http://stackoverflow.com/q/51004832
tags question: http://stackoverflow.com/q/50947079
tags question: http://stackoverflow.com/q/50886684
tags question: http://stackoverflow.com/q/50928148
tags question: http://stackoverflow.com/q/50897244
tags question: http://stackoverflow.com/q/50866554
tags question: http://stackoverflow.com/q/50968321
tags question: http://stackoverflow.com/q/50874279
tags question: http://stackoverflow.com/q/50930376
tags question: http://stackoverflow.com/q/51000841
tags question: http://stackoverflow.com/q/51010350
tags question: http://stackoverflow.com/q/51008267
tags question: http://stackoverflow.com/q/50979275
tag name: deep-learning
tags question: http://stackoverflow.com/q/50944672
tags question: http://stackoverflow.com/q/50901731
tags question: http://stackoverflow.com/q/50863494
tags question: http://stackoverflow.com/q/50967536
tags question: http://stackoverflow.com/q/51001996
tags question: http://stackoverflow.com/q/50991189

http://stackoverflow.com/comment/88999594
score: 0
type: AnswerComment
has text: Thank you again so much!
comment on: http://stackoverflow.com/a/51002141
type: Comment

http://stackoverflow.com/q/50877347
tagged with: peek
has title: es demux error: cannot peek when trying to make my computer speak with Python
type: UnansweredQuestion
tagged with: text-to-speech
upvote count: 1
has comment: http://stackoverflow.com/comment/88761298
score: 1
tagged with: google-speech-api
tagged with: speech-synthesis
type: Question
downvote count: 0
has body: I'm trying to get my computer to talk with google translate speech functionality on Ubuntu Utility Ubuntu16.04. I found a way to do it usning the voice library speak and this repository, but I have an error with VLC and I have not found a similar error on the Internet. ... # for text to speech import webbrowser as wb import speak # running music from pygame import mixer ... class ActionTranslate(Action): def name(self): return 'action_translate' def run (self,dispatcher,tracker,domain): try: # What Google thinks you said text = tracker.get_slot('sentenceToTranslate') if tracker.get_slot('voice') is 'en': lang = 'en' else: lang = 'ko' # Google saying what he thinks you said speak.speak(text, lang) f_text = 'https://www.google.co.in/search?q=' + text wb.get(chrome_path).open(f_text) except Exception as e: print (e) But I obtained this error: INFO:requests.packages.urllib3.connectionpool:Starting new HTTP connection (1): api.voicerss.org could not locate runnable browser [00007ff164c0c2b8] es demux error: cannot peek [00007ff164c0c2b8] es demux error: cannot peek [mp3 @ 0x7ff164c5d860] Header missing I know that peek refers to: a non-destructive operation performed on sequential, collection-like data structures that have the notion of "top element" or "next element", such as stacks, queues and streams. The peek operation returns the value of the "top" (or "next") element without "consuming" that element
tagged with: python
favorite count: 0
answer count: 0

http://stackoverflow.com/comment/88953697
has text: Hi, I've tried using you what you suggest but i still get a traceback error
type: AnswerComment
comment on: http://stackoverflow.com/a/50978436
type: Comment
score: 0

http://stackoverflow.com/a/50958336
answers question: http://stackoverflow.com/q/50957010
has body: You don't need a loop. You can read the whole file into a list with readlines(), modify a specific element of the list, then write it back out to the file with writelines(). with open("filename.txt", "r+") as f: lines = f.readlines() lines[2] = "k5=np.linspace(0,5,10)\n" f.seek(0) f.writelines(lines) f.truncate() f.seek() goes back to the beginning of the file, so that f.writelines() overwrites it. Then we use f.truncate() to remove any excess content if the replacement is shorter than the original file contents. Don't forget the \n in the new contents of lines[2]. writelines() doesn't put newlines between the strings in its argument.
upvote count: 0
type: Answer
downvote count: 2
score: -2

http://stackoverflow.com/q/50883019
answer count: 1
has title: Creating a Tkitner application with multiple windows
score: 1
favorite count: 0
tagged with: tkinter
accepted answer: http://stackoverflow.com/a/50884362
upvote count: 1
tagged with: python
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/50884362
downvote count: 0
has body: I want to be able to open up another window and destroy the current login window, only once the login details are correct. I have set the current login window as the top level and withdrew the root window, I'm guessing I now need to destroy the Toplevel and recall the root, but the exact method of doing this I am unsure about. Any help would be appreciated. from Tkinter import * import tkMessageBox import time #Login details username = ("admin") password = ("") #Login attempt def try_login(): print("Trying to login...") if username_guess.get() == username: tkMessageBox.showinfo("COMPLETE", "You Have Now Logged In.", icon="info") else: tkMessageBox.showinfo("-- ERROR --", "Please enter valid infomation!", icon="warning") #Gui Things root = Tk() top = Toplevel() top.configure(bg='lightgrey') top.resizable(width=FALSE, height=FALSE) top.title("Log-In") top.geometry("200x160") # change window icon top.wm_iconbitmap(r'C:\Python27\py.ico') top.wm_title('APP') #Time and Date time1 = '' clock = Label(top, font=('times', 10, 'bold'), bg='lightgrey') clock.pack(side="bottom", fill='both', expand=False, ipadx=0, ipady=0) def tick(): global time1 time2 = time.strftime("%d-%m-%Y %H:%M") if time2 != time1: time1 = time2 clock.config(text=time2) clock.after(200, tick) tick() #Creating the username &amp; password entry boxes username_text = Label(top, text="Username:", bg='lightgrey') username_guess = Entry(top) password_text = Label(top, text="Password:", bg='lightgrey') password_guess = Entry(top, show="*") #attempt to login button attempt_quit = Button(top, text="Quit", command=top.destroy).pack(side="bottom", fill='both', expand=False, padx=0, pady=0) attempt_login = Button(top, text="Login", command=try_login).pack(side="bottom", fill='both', expand=False, padx=0, pady=0) username_text.pack() username_guess.pack() password_text.pack() password_guess.pack() #Hides the root window root.withdraw() #Top Starter top.mainloop()
tagged with: window

http://stackoverflow.com/a/50887515
type: Answer
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/88777985
has body: It seem that the training and testing sets have different dimensions. Is it possible you trained with 8 features and testing on 7?
answers question: http://stackoverflow.com/q/50886294
downvote count: 0

http://stackoverflow.com/comment/92896228
comment on: http://stackoverflow.com/a/52705862
has text: Using a two-step MessageToDict followed by conversion to JSON is an excellent suggestion; for me, it works better than MessageToJson when applied to Google's Vision API responses, because (at least in my hands) applying MessageToJson to the API's Protocol Buffer responses produces a string.
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50949089
has answer: http://stackoverflow.com/a/51426978
accepted answer: http://stackoverflow.com/a/51426978
has comment: http://stackoverflow.com/comment/89820296
tagged with: python
type: AnsweredQuestion
has title: Translating Log Normal and Log Normal Truncated Simulations in @Risk to Python
linked to: http://stackoverflow.com/q/12937824
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/88896591
has body: I have been given a task of translating the simulations inside of the Excel plug-in @Risk to Python. The functionalities closely line up with numpy's random number simulation given a distribution type and mu, sigma, or high and low values. An example for what I am doing is here. In the linked example, mu=2 and sigma=1. Using numpy I get the same distribution as @Risk. dist = np.random.lognormal(2, 1, 1000) However, when I use numpy with the following parameters - I can no longer replicate the @Risk distributions. mu=0.4, sigma=0.16 in @Risk: Histogram for 1000 rsamples and in Python: histogram for 1000 rsamples The result is two completely different distributions for the same mu and sigma. So I am very confused now on what numpy is expecting for mu and sigma inputs. I've read through the docs linked here, but why would one set of parameters give me the matching distributions, and another set of values will not. What am I missing here?
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/88895816
has comment: http://stackoverflow.com/comment/89821024

http://stackoverflow.com/comment/88914893
has text: @tdelaney seems i am not the first person to recognize that this really is a problem: https://stackoverflow.com/a/1063055/2437514
comment on: http://stackoverflow.com/q/50950939
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88932203
has text: Yes. Indeed I meant that. And also I just read the Note below that page, that `"**kwargs is not supported in sklearn, it may cause unexpected issues."` Upon further inspection, it looks like it has been handled correctly and should work. How are you detecting that its not activating?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50956103

http://stackoverflow.com/comment/89005957
type: QuestionComment
comment on: http://stackoverflow.com/q/51006278
has text: `pip install quantecon` has to be in the Command Line
score: 0
type: Comment

http://stackoverflow.com/a/50954403
has body: I'm assuming from your phrasing that you're running different apps on servers A and B. If they were the same app, using the same celery broker and backend, then named queues with one queue being served by a celery worker that's only running on B could give you the effect you want. If A and B are running different code, a safe approach is to have the asynchronous task on A make an HTTP request to and endpoint on B, with that endpoint calling the function and sending the answer back in an HTTP response for the async task in A to deal with. Elaborating: A slow-running async task (say, in tasks.py) @celery.task def slow_running_task(): ... that's configured to run in a specific queue CELERY_ROUTES = { 'tasks.slow_running_task': {'queue': 'slow'}, ... can be run on a specific server by only running a celery worker with -Q slow on that server. There are nuances. It's worth skimming the celery docs.
score: 0
has comment: http://stackoverflow.com/comment/88907039
answers question: http://stackoverflow.com/q/50944047
type: Answer

http://stackoverflow.com/a/50940045
answers question: http://stackoverflow.com/q/50939921
type: Answer
has body: you error is that you want to get img from Response, not from source code r=requests.get("http://"+ url) # data=r.img # it is wrong # change instead of `img` to `text` data = r.text # here we need to get `text` from `Response` not `img` # and the code soup=BeautifulSoup(data) for link in soup.find_all('img'): print link.get('src')
score: 0

zero
tags question: http://stackoverflow.com/q/50973041
type: Tag
tag name: zero

http://stackoverflow.com/comment/88951997
has text: I don't know the sampling rate of either time series. So I'm not sure how I would interpolate.
score: 0
comment on: http://stackoverflow.com/q/50976950
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88915200
type: QuestionComment
type: Comment
has text: why do you think it has a method with that name? Have you tried reading some documentation to see a list of available methods?
score: 0
comment on: http://stackoverflow.com/q/50958876

http://stackoverflow.com/q/50978507
type: Question
tagged with: performance
has comment: http://stackoverflow.com/comment/88953635
has comment: http://stackoverflow.com/comment/88975957
upvote count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: sockets
linked to: http://stackoverflow.com/q/855544
tagged with: python
has comment: http://stackoverflow.com/comment/88953454
has body: I have an issue with a script I want to create for a Raspberry Pi using Python. To test the script I'm running Python 3.6 on a Windows 64 bit machine. I want to send "1" to my local address (192.168.1.101 / 127.0.0.1) on port 1235, using TCP. When I use putty in RAW mode, i can send this data to my server and I get the right response instantly. But when I try to do this using Python on Windows I get a steady 2 minute delay. I can also see the command is only received by the server 2 minute after I send it. And after those two minutes I get an instant reply. The code: import socket message = '\x31'.encode() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('192.168.1.101', 1235)) s.send(message) ; print ("send ready") ; data = s.recv(80) ; s.close(); print ("received"), repr(data) #forgive me the ; ... I'm on a command line for testing. #response is: 1 send ready #2 minute delay ("None, "b"140,1,1,test\\r\n'") I have been trying things like SOCKET_DGRAM, RAW TCP NO DELAY, SO_SNDBUF, etc., but I can't find where this is coming from.
answer count: 0
downvote count: 0
score: 1
has title: Python socket extremely slow

http://stackoverflow.com/comment/88811089
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50905636
score: 0
has text: are you using a virtualenv ?

http://stackoverflow.com/comment/88785848
has text: @Code-Apprentice added and example a part from my code. Check now
comment on: http://stackoverflow.com/q/50892601
score: 0
type: QuestionComment
type: Comment

django-rest-framework
tags question: http://stackoverflow.com/q/50858231
tags question: http://stackoverflow.com/q/50890662
tags question: http://stackoverflow.com/q/50938691
tags question: http://stackoverflow.com/q/50991920
tags question: http://stackoverflow.com/q/50994516
tags question: http://stackoverflow.com/q/50915002
tags question: http://stackoverflow.com/q/50915625
tags question: http://stackoverflow.com/q/50917685
tags question: http://stackoverflow.com/q/50866961
tags question: http://stackoverflow.com/q/50916834
tags question: http://stackoverflow.com/q/50870442
tags question: http://stackoverflow.com/q/50892879
type: Tag
tags question: http://stackoverflow.com/q/50862127
tags question: http://stackoverflow.com/q/50975343
tags question: http://stackoverflow.com/q/50947349
tags question: http://stackoverflow.com/q/50887035
tags question: http://stackoverflow.com/q/50952966
tags question: http://stackoverflow.com/q/50981243
tags question: http://stackoverflow.com/q/50882673
tags question: http://stackoverflow.com/q/50934112
tags question: http://stackoverflow.com/q/50972893
tag name: django-rest-framework
tags question: http://stackoverflow.com/q/50997484
tags question: http://stackoverflow.com/q/50983848
tags question: http://stackoverflow.com/q/50973569
tags question: http://stackoverflow.com/q/50977447
tags question: http://stackoverflow.com/q/50938688
tags question: http://stackoverflow.com/q/50895202
tags question: http://stackoverflow.com/q/51005163
tags question: http://stackoverflow.com/q/50883288
tags question: http://stackoverflow.com/q/50984323
tags question: http://stackoverflow.com/q/50864438
tags question: http://stackoverflow.com/q/50878730
tags question: http://stackoverflow.com/q/51010940
tags question: http://stackoverflow.com/q/50874486
tags question: http://stackoverflow.com/q/50974662
tags question: http://stackoverflow.com/q/50971992
tags question: http://stackoverflow.com/q/50928262
tags question: http://stackoverflow.com/q/51001598
tags question: http://stackoverflow.com/q/50899191
tags question: http://stackoverflow.com/q/50892010

http://stackoverflow.com/q/50892257
answer count: 2
has comment: http://stackoverflow.com/comment/88785704
downvote count: 0
has comment: http://stackoverflow.com/comment/88785717
possible better answer: http://stackoverflow.com/a/50892647
favorite count: 0
has comment: http://stackoverflow.com/comment/88785212
has comment: http://stackoverflow.com/comment/88785712
tagged with: python
has answer: http://stackoverflow.com/a/50892590
accepted answer: http://stackoverflow.com/a/50892590
score: 2
has comment: http://stackoverflow.com/comment/88785295
type: AnsweredQuestion
has title: beginner-opening explorer to show folder contents
has answer: http://stackoverflow.com/a/50892647
type: Question
upvote count: 2
has body: I've been tinkering with Python 3.66 a few days now on windows 7. Making good progress, but I am totally stuck on how to make windows explorer open with my desired folder contents showing. I have tried at least 7 different solutions from related questions on here but none seem to work. They all open explorer fine, but never with my Folder_selected variable. The explorer bit is the final line of code. Here is the (badly coded I suspect) source: #FRenum-v.04 #renumbers a folder of files to 01 onward preserving file extenders. #Steve Shambles june 2018, my 2nd ever python program from tkinter import filedialog from tkinter import * import os import os.path import subprocess #user selects directory root = Tk() root.withdraw() #stop tk window opening folder_selected = filedialog.askdirectory() #open file requestor #change dir to folder selected by user, os.chdir (folder_selected) #path is now the dir path=(folder_selected) # read user selected dir files = os.listdir(folder_selected) # inc is counter to keep track of what file we are working on inc = 1 for file in files: #store file extender in string file_ext file_ext = os.path.splitext(file)[1] # build new filename, starting with a "0" then #value of inc then add file extender created_file=("0"+str(inc)+ file_ext) #if file does not exist rename it if not os.path.exists(created_file): os.rename(file,created_file) #next one please, until done inc = inc+1 #add to counter #open explorer showing folder of renamed files subprocess.Popen(["C:\\Windows\\explorer.exe"]) #these do not work properly, opens in c: or my docs #subprocess.Popen(["C:\\Windows\\explorer.exe"+ folder_selected]) #subprocess.Popen(["C:\\Windows\\explorer.exe", folder_selected]) #subprocess.Popen(["C:\\Windows\\explorer.exe","folder_selected"]) #todo #--------- #ignore sub-folders #confirm requestor #undo feature #find out how to stop dos box showing in compiles prg

http://stackoverflow.com/comment/89005154
type: Comment
comment on: http://stackoverflow.com/q/51005573
has text: In the description you mention off-diagonals but your code seems to only address the two main diagonals. Could you please clarify?
score: 0
type: QuestionComment

http://stackoverflow.com/comment/89007383
has text: I would use plot date, but I am having a problem defining the values. I have changed my question to clarify something I haven't. my data, which are lists, are stored in a text file. What you did was define the values as the lists I showed. But what I forgot to mention is that the ones I showed is a sample of a 2GB file with such lists. Is there a way I can define values by using my variable word which represents my data coming from the file?
type: Comment
comment on: http://stackoverflow.com/a/50969963
score: 0
type: AnswerComment

http://stackoverflow.com/q/50991909
tagged with: python
tagged with: dictionary
tagged with: python-3.x
type: UnansweredQuestion
upvote count: 1
has answer: http://stackoverflow.com/a/50992012
type: Question
tagged with: ordereddictionary
has body: I currently am using a set of weather data and am trying to find the minimum and maximum values from the data. I have read the file into an ordered dictionary and can output all my numbers, but I have had a hard time trying to output the correct minimum and maximums. Below is a sample of one of the data: OrderedDict([('STATION', 'USW00003894'), ('NAME', 'CLARKSVILLE OUTLAW AIRPORT, TN US'), ('DATE', '2002-07-20'), ('PRCP', 0.0), ('SNOW', None), ('SNWD', None), ('TAVG', 79.0), ('TMAX', 89.0), ('TMIN', 69.0)]) OrderedDict([('STATION', 'USW00003894'), ('NAME', 'CLARKSVILLE OUTLAW AIRPORT, TN US'), ('DATE', '2002-07-21'), ('PRCP', 0.12), ('SNOW', None), ('SNWD', None), ('TAVG', 82.0), ('TMAX', 92.0), ('TMIN', 71.0)]) OrderedDict([('STATION', 'USW00003894'), ('NAME', 'CLARKSVILLE OUTLAW AIRPORT, TN US'), ('DATE', '2002-07-22'), ('PRCP', 0.0), ('SNOW', None), ('SNWD', None), ('TAVG', 80.0), ('TMAX', 90.0), ('TMIN', 70.0)]) There are a few missing values, which I have replaced with the none data type and I would like not to include either the None or the zero values in my calculations. Below is the code I have so far: with open('Clarksville_weather_history.txt', newline='') as clarksWeather: reader = csv.DictReader(clarksWeather) for row in reader: if len(row['PRCP']) &gt; 0: row['PRCP'] = float(row['PRCP']) else: row['PRCP'] = None if len(row['SNOW']) &gt; 0: row['SNOW'] = float(row['SNOW']) else: row['SNOW'] = None if len(row['SNWD']) &gt; 0: row['SNWD'] = float(row['SNWD']) else: row['SNWD'] = None if len(row['TAVG']) &gt; 0: row['TAVG'] = float(row['TAVG']) else: row['TAVG'] = None if len(row['TMAX']) &gt; 0: row['TMAX'] = float(row['TMAX']) else: row['TMAX'] = None if len(row['TMIN']) &gt; 0: row['TMIN'] = float(row['TMIN']) else: row['TMIN'] = None #result = min(reader, key=lambda x:x['PRCP']) #print(result) Any help or guidance would be appreciated. All the methods I have tried do not allow me to parse the data efficiently. I am new to this language and there doesn'…
score: 1
has title: How do I find the Min and Max values for rows within a dictionary while using DictReader in Python 3
answer count: 1
downvote count: 0
favorite count: 0
tagged with: http://stackoverflow.com/tag/csv

http://stackoverflow.com/a/50889453
type: Answer
score: 0
has body: It makes no sense to open more than about 3-4 connections, if network latency is bottleneck or more connections than CPU cores, if CPU is bottleneck.
answers question: http://stackoverflow.com/q/50888082

http://stackoverflow.com/comment/88937744
score: 0
has text: @FHTMitchell, thanks for your suggestions! Thanks! It works.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50970266

http://stackoverflow.com/q/50976878
downvote count: 0
answer count: 0
score: 1
has title: Flask REST app on Heroku randomizes variables
has comment: http://stackoverflow.com/comment/88950172
type: Question
tagged with: heroku
duplicate of: http://stackoverflow.com/q/32815451
upvote count: 1
has body: I have created a program with the ESP8266 to periodically request to my flask application a integer variable to turn on and off a LED. When I run it locally the app works as it should but when I deploy it on Heroku, the first time I change the value of the status it starts swaping from 1 to 0 randomly forever. Here is the code of the Flask app from flask import Flask, jsonify, render_template, redirect import time ########################################################## app = Flask(__name__) ledStatus = 1 ########################################################## @app.route('/led-status') def getStatus(): return jsonify (ledStatus = ledStatus) @app.route('/button') def getButton(): return render_template('button.html', ledStatus=ledStatus) @app.route('/led-swap') def swapStatus(): global ledStatus if ledStatus == 1: ledStatus = 0 else: ledStatus = 1 time.sleep(0.5) return redirect("/button") ########################################################## if __name__ == "__main__": app.run() Thanks in advance.
tagged with: flask
favorite count: 0
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/32815451
has comment: http://stackoverflow.com/comment/88950491

http://stackoverflow.com/comment/88735102
has text: This should help https://stackoverflow.com/a/41573727/2836621
score: 0
comment on: http://stackoverflow.com/q/50865560
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51004506
score: 13
tagged with: pandas-groupby
tagged with: pandas
has answer: http://stackoverflow.com/a/51004537
tagged with: python
upvote count: 13
has title: Pandas dataframe to dict of dict
tagged with: dictionary
possible better answer: http://stackoverflow.com/a/51004565
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51004537
has answer: http://stackoverflow.com/a/51004565
has body: Given the following pandas data frame: ColA ColB ColC 0 a1 t 1 1 a2 t 2 2 a3 d 3 3 a4 d 4 I want to get a dictionary of dictionary. But I managed to create the following only: d = {t : [1, 2], d : [3, 4]} by: d = {k: list(v) for k,v in duplicated.groupby("ColB")["ColC"]} How could I obtain the dict of dict: dd = {t : {a1:1, a2:2}, d : {a3:3, a4:4}}
type: Question
answer count: 2
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/88774134
type: AnswerComment
comment on: http://stackoverflow.com/a/50886159
type: Comment
has text: Thanks @Michael for quick and detailed response. Yes I am replying with a 'custom' message as a response to a user. 'Tweet' in this case is nothing but a string.
score: 0

http://stackoverflow.com/comment/88805695
type: Comment
comment on: http://stackoverflow.com/a/50902400
type: AnswerComment
has text: @AmbrishDhaka As above where? Does the code in my answer not do what you want, or not work for you in some other way?
score: 0

http://stackoverflow.com/comment/89008422
type: AnswerComment
type: Comment
has text: Browser emulation might not be as "heavy" as you think. You don't necessarily have to emulate the big ones(Chrome/Firefox) if what you want to do is just click a button. There are many ghost browser implementations that are lightweight. Take a look here https://github.com/dhamaniasad/HeadlessBrowsers
comment on: http://stackoverflow.com/a/51007639
score: 0

http://stackoverflow.com/comment/88981786
type: QuestionComment
score: 2
has text: What platform are you on, what Python are you using, and how did you install it? If you're on Linux, you may have installed a distro Python package that splits pip out into a separate package, like `python-pip`, in which case you need to install that. If you're on macOS, you may be using Apple's pre-installed Python, which doesn't come with pip (in which case you really should install a separate Python instead, but if you really want to, you can install pip for that one). And so on.
comment on: http://stackoverflow.com/q/50993566
type: Comment

yield-keyword
tags question: http://stackoverflow.com/q/50949010
tags question: http://stackoverflow.com/q/50911425
type: Tag
tags question: http://stackoverflow.com/q/50960220
tag name: yield-keyword

http://stackoverflow.com/a/56074651
has body: I found another use-case for the code shared by @d_bergeron, where I wanted to copy a slide from another presentation into the one I generated with python-pptx: As an argument, I pass in the Presentation() object I created using python-pptx (prs = Presentation()). from pptx import Presentation import copy def copy_slide_from_external_prs(prs): # copy from external presentation all objects into the existing presentation external_pres = Presentation("PATH/TO/PRES/TO/IMPORT/from.pptx") # specify the slide you want to copy the contents from ext_slide = external_pres.slides[0] # Define the layout you want to use from your generated pptx SLD_LAYOUT = 5 slide_layout = prs.slide_layouts[SLD_LAYOUT] # create now slide, to copy contents to curr_slide = prs.slides.add_slide(slide_layout) # now copy contents from external slide, but do not copy slide properties # e.g. slide layouts, etc., because these would produce errors, as diplicate # entries might be generated for shp in ext_slide.shapes: el = shp.element newel = copy.deepcopy(el) curr_slide.shapes._spTree.insert_element_before(newel, 'p:extLst') return prs
score: 7
upvote count: 7
downvote count: 0
answers question: http://stackoverflow.com/q/50866634
type: Answer

http://stackoverflow.com/q/51011010
type: UnansweredQuestion
has body: I am quite new to kivy. While practicing with online examples, I noticed that many of their widget classes don't have constructors. I just want to ask what is significance of constructors in kivy widgets, n when to use them.
tagged with: python
has answer: http://stackoverflow.com/a/51012327
type: Question
score: 0
has title: Constructors in kivy
answer count: 1
tagged with: kivy
tagged with: python-3.x

http://stackoverflow.com/q/51002694
has comment: http://stackoverflow.com/comment/88999246
has comment: http://stackoverflow.com/comment/88999080
answer count: 1
favorite count: 0
has title: os.getenv() is not pulling a variable I previously declare
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88999232
score: 3
has comment: http://stackoverflow.com/comment/88999027
has comment: http://stackoverflow.com/comment/88999185
has comment: http://stackoverflow.com/comment/88999026
has body: I'm new to python and I cannot seem to figure out why I cannot get the os.getenv() function to work. It keeps returning None which is the default value if something is not there. Here is my code: import os import datetime import plaid from flask import Flask from flask import render_template from flask import request from flask import jsonify app = Flask(__name__) PLAID_CLIENT_ID='entercharhere' PLAID_ENV='sandbox' #edit here os.environ['PLAID_CLIENT_ID']='entercharhere' os.environ['PLAID_ENV']='sandbox' print(PLAID_CLIENT_ID) # Fill in your Plaid API keys - https://dashboard.plaid.com/account/keys PLAID_CLIENT_ID = os.getenv('PLAID_CLIENT_ID') # Use 'sandbox' to test with Plaid's Sandbox environment (username: user_good, # password: pass_good) # Use `development` to test with live users and credentials and `production` # to go live PLAID_ENV = os.getenv('PLAID_ENV','sandbox') print(PLAID_CLIENT_ID) The output I am receiving is entercharhere and None EDIT I wound up switching my declaration of variables to send them to the environment using this: os.environ['PLAID_CLIENT_ID']='entercharhere' os.environ['PLAID_ENV']='sandbox' Is this the best way to do it?
downvote count: 1
has answer: http://stackoverflow.com/a/51002833
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/88999067
has comment: http://stackoverflow.com/comment/88999451
has comment: http://stackoverflow.com/comment/88999245

http://stackoverflow.com/q/50974924
tagged with: python
tagged with: list
downvote count: 0
type: Question
type: AnsweredQuestion
score: 1
possible better answer: http://stackoverflow.com/a/50975491
has answer: http://stackoverflow.com/a/50975491
tagged with: numpy
answer count: 2
has comment: http://stackoverflow.com/comment/88946859
has title: Numpy list comprehension iterating over 2D array
upvote count: 1
tagged with: arrays
tagged with: iteration
favorite count: 0
has answer: http://stackoverflow.com/a/50975495
has comment: http://stackoverflow.com/comment/88946062
accepted answer: http://stackoverflow.com/a/50975495
has body: I have a bit of code that loads up a long (100k-1mil) set of lines, it has an index in the first column followed by 18 values, for a total of 19 floats per line. This all is put into a numpy array. I need to do some simple processing on the matrix to keep the index column and get out 1s and 0s depending on conditions of whether values are positive or negative, but the criterion varies as the columns are sequential pairs of values with different reference values. The code below goes through the columns 2-19 first by evens then odds to check the values, and then creates a temporary list to put into the array I want to have at the end. I know there's a simpler way to do this, with list comprehension and possibly lambda, but I'm not proficient enough with this to figure it out. So I'm hoping someone can help me reduce the length of this code into something more compact. More efficient would be great too, but I know that the compact methods don't always increase efficiency. It will however help me better understand list comprehension, with and without numpy. Sample values for reference: 0.000 72.250 -158.622 86.575 -151.153 85.807 -149.803 84.285 -143.701 77.723 -160.471 96.587 -144.020 75.827 -157.071 87.629 -148.856 100.814 -140.488 10.000 56.224 -174.351 108.309 -154.148 68.564 -155.721 83.634 -132.836 75.030 -177.971 100.623 -146.616 61.856 -150.885 92.147 -150.124 91.841 -153.112 20.000 53.357 -153.537 58.190 -160.235 77.575 176.257 93.771 -150.549 77.789 -161.534 103.589 -146.363 73.623 -159.441 99.315 -129.663 92.842 -138.736 And here is the code snippet: datain = numpy.loadtxt(testfile.txt) #load data dataout = numpy.zeros(datain.shape) # initialize empty processing array dataout[:, 0] = datain[:, 0] # assign time values from input data to processing array dataarray = numpy.zeros(len(datain[0])) phit = numpy.zeros((len(dataarray)-1)/2) psit = numpy.zeros((len(dataarray)-1)/2) for i in range(len(datain)): dataarray = numpy.copy(datain[i]) phit[:] = dataarray[1::2]…

http://stackoverflow.com/q/50867475
accepted answer: http://stackoverflow.com/a/50867524
possible better answer: http://stackoverflow.com/a/50867735
has comment: http://stackoverflow.com/comment/88737345
has answer: http://stackoverflow.com/a/50867735
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/88737369
has body: I will make a function with parameter "n". I want a function to return "n" as either 0 or 1. If 0, then the user input will be considered less than or equal to 0. If 1, then the user input will be considered greater than 0. This is what I have so far and I'm not sure how to correct my mistakes. def main(): n = int(input("Enter a value: ")) integer(n) def integer(n): if n &lt;= 0: return n*0 elif n &gt; 0: return n*0 + 1 def integer(n=0): print("That value is less than or equal to 0") def integer(n=1): print("That value is greater than 0") main()
has title: Returning function values to determine what will be printed
has answer: http://stackoverflow.com/a/50867524
type: Question
type: AnsweredQuestion
answer count: 2

python-docx
tags question: http://stackoverflow.com/q/50939078
tags question: http://stackoverflow.com/q/50963613
tags question: http://stackoverflow.com/q/50988236
tags question: http://stackoverflow.com/q/50982064
tags question: http://stackoverflow.com/q/50856336
type: Tag
tags question: http://stackoverflow.com/q/50973176
tag name: python-docx
tags question: http://stackoverflow.com/q/50878618
tags question: http://stackoverflow.com/q/50963852

http://stackoverflow.com/comment/88950396
has text: I think the question is not about leaving part of the plotted data out, but to plot the data as shown, but restrict the legend to not show duplicates.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50976957
type: Comment

http://stackoverflow.com/q/50903737
has title: How to fix List index out of range in python?
tagged with: for-loop
has comment: http://stackoverflow.com/comment/88808029
favorite count: 0
tagged with: qlistwidget
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88808403
has comment: http://stackoverflow.com/comment/88807971
tagged with: python
has body: I have a code that displays items (files) in a QlistWidget where the user clicks on the item and the system displays its content. The Problem is when the user clicks on the item the system crashes and displays the below error: File "c:\Users\test\Documents\Python_Projects\tests_scripts\qt_creator\Python_Projects-AnthonyKifawi-\myPDFviewer.py", line 159, in FileListSelected Item= oneDir + "\" + self.listWidgetPDFlist.selectedItems()[index].text() builtins.IndexError: list index out of range existing files in the list : C:\Users\test\Desktop\New Microsoft Word Document.docx ==> row 0 C:\Users\test\Desktop\test_arabic.docx ==> row 1 displayed Result : this is P==>C:\Users\test\Desktop\test_arabic.docx this is oneDir==>C:\Users\test this is the cuurent Item ==C:\Users\test\Desktop\test_arabic.docx this is ppp==>C:\Users\test\Desktop\test_arabic.docx current row = 1 this is P==>C:\Users\test\Desktop\test_arabic.docx this is oneDir==>C:\Users\test this is the cuurent Item ==C:\Users\test\Desktop\test_arabic.docx this is ppp==>C:\Users\test\Desktop\test_arabic.docx current row = 0 code: def FileListSelected(self): # Function to select the desired file from the list in the left pane ListIterator=range(self.listWidgetPDFlist.count()) for index in ListIterator: p = pathlib.Path(self.fullPath) print("this is P==&gt;{}".format(p)) oneDir = os.path.join(*p.parts[:-2]) print("this is oneDir==&gt;{}".format(oneDir)) Item= oneDir + "\\" + self.listWidgetPDFlist.selectedItems()[index].text() print("this is the cuurent Item =={}".format(Item)) ppp=os.path.join(os.path.expanduser("~"), Item) print("this is ppp==&gt;{}".format(ppp)) self.mouseHover() return ppp
answer count: 0
score: 0
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/88807310
type: Question

http://stackoverflow.com/comment/88848690
type: AnswerComment
type: Comment
has text: No, this is a bad idea. Here `['abc', 'def']` will be equivalent to `['abcd', 'ef']`, when in fact they are different.
score: 0
comment on: http://stackoverflow.com/a/50924690

http://stackoverflow.com/q/50992771
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: jupyter-notebook
tagged with: tensorflow
linked to: http://stackoverflow.com/q/42322698
has body: I would like to train multiple models on multiple GPUs at the simultaneously from within a jupyter notebook. I am working on a node with 4GPUs. I would like to assign one GPU to one model and train 4 different models at the same time. Right now, I select a GPU for one notebook by (e.g.): import os os.environ['CUDA_VISIBLE_DEVICES'] = '1' def model(...): .... model.fit(...) In four different notebooks. Though, then the results and the output of the fitting procedure is distributed in four different notebooks. Though, running them in one notebook sequentially, needs a lot of time. How do you assign GPU's to individual functions and run them in parallel?
type: Question
score: 5
has answer: http://stackoverflow.com/a/68280815
upvote count: 5
has answer: http://stackoverflow.com/a/51004182
answer count: 2
downvote count: 0
has title: Train multiple keras/tensorflow models on different GPUs simultaneously
tagged with: keras

http://stackoverflow.com/a/63729248
answers question: http://stackoverflow.com/q/50989403
has body: import plotly.express as px fig = px.pie(df, values='numeric_value', names='column_name', title='Your title') fig.show()
downvote count: 0
upvote count: 2
type: Answer
score: 2

http://stackoverflow.com/comment/88760490
has text: No it does not work, returns empty list as nodes won't be either (`tf.Operation` nor `tf.Tensor`)
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50879201
score: 1

http://stackoverflow.com/a/50966169
accepted answer of: http://stackoverflow.com/q/50965844
answers question: http://stackoverflow.com/q/50965844
has comment: http://stackoverflow.com/comment/88928847
has comment: http://stackoverflow.com/comment/88928869
upvote count: 3
type: AcceptedAnswer
has body: If your identified pattern is a heuristic which, nevertheless, I struggle to follow, you can instead try pd.Series.ffill and pd.Series.bfill to reach your desired result: df[0] = df[0].ffill() df[1] = df[1].bfill() Then drop duplicates: df = df.drop_duplicates() print(df) 0 1 0 shape square 1 shape circle 2 animal dog 4 animal cat 5 animal fish 6 color red 7 color blue
type: Answer
score: 3
downvote count: 0

http://stackoverflow.com/a/50982870
answers question: http://stackoverflow.com/q/50982372
type: Answer
has body: If you like to do it without eval / ast.literal_eval &gt;&gt;&gt; list(itertools.chain(*[map(int, w.strip('[]').split(',')) for w in l])) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
score: 0

http://stackoverflow.com/comment/88888619
has text: @eyllanesc I've added a link to an example. I'll try to reduce it still a bit.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50928059
score: 1

http://stackoverflow.com/comment/88807662
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50880179
has text: _“I was briefly demoted to Moderator of the Page”_ - did you generate a new access token afterwards?
score: 0

vertica
tag name: vertica
tags question: http://stackoverflow.com/q/50917141
type: Tag

http://stackoverflow.com/comment/88722570
comment on: http://stackoverflow.com/a/50859241
has text: obviously not. :) I was practicing that pandas example, did not work, and was wondering why it didn't work?
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/88739748
comment on: http://stackoverflow.com/a/50869011
has text: I don't think that would be desirable in general.
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/a/50924566
score: 4
has body: You can't have custom representation for the datetime dtype. But you have the following options: use strings - you might have any representation (as you wish), but all datetime methods and attributes get lost use datetime, but set the day part to 1 (as @Kopytok) has already shown. use period dtype, which still allows you to use some date arithmetic Demo: In [207]: df Out[207]: var1 date 0 A 2018-12-31 1 A 2017-09-07 2 B 2016-02-29 In [208]: df['new'] = df['date'].dt.to_period('M') In [209]: df Out[209]: var1 date new 0 A 2018-12-31 2018-12 1 A 2017-09-07 2017-09 2 B 2016-02-29 2016-02 In [210]: df.dtypes Out[210]: var1 object date datetime64[ns] new object dtype: object In [211]: df['new'] + 8 Out[211]: 0 2019-08 1 2018-05 2 2016-10 Name: new, dtype: object
type: Answer
answers question: http://stackoverflow.com/q/50923929
upvote count: 4
downvote count: 0

http://stackoverflow.com/comment/88930295
score: 0
has text: what defines an "ambiguous value" ?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50966822

http://stackoverflow.com/comment/88963736
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50983428
type: Comment
has text: for example: ['[{'a': u'中国', 'b': u'美国', 'c': u'日本', 'd': u'德国', 'e': u'法国'},]','[{'a': u'中国', 'b': u'美国', 'c': u'日本', 'd': u'德国', 'e': u'法国'},]',]

http://stackoverflow.com/comment/88985810
type: QuestionComment
has text: Can you show what the expected output would be in that case then? Or even a case with two (or more) smaller factorials?
comment on: http://stackoverflow.com/q/50995581
score: 0
type: Comment

http://stackoverflow.com/comment/88969002
type: Comment
comment on: http://stackoverflow.com/a/50965424
has text: @Jpp Oh I see. I now know what is meant by a function call, thank you!
score: 1
type: AnswerComment

http://stackoverflow.com/q/50955549
tagged with: python
tagged with: pycharm
upvote count: 3
type: Question
score: 3
tagged with: type-hinting
has title: How to use a function parameter as a type hint?
has body: I have a check_value function which expects the parameter value and value_type, compares type(value) with value_type and depending on the outcome returns the value or raises an Exception. Now I want to use type hints to annotate both parameters and the return type. def check_value(value: "value_type", value_type: type) -&gt; "value_type": if type(value) is value_type: return value else: raise Exception(f"Value '{value}' should be of type '{value_type}' instead of type '{type(value)}'.") if __name__ == '__main__': print(check_value(2, int)) # works, returns print(check_value(2, str)) # works, raises Exception The annotation of the parameter value_type works fine, but forward referencing value_type as a type hint (since the type of value/the returned value are of type value_type) causes an warning in Pycharm_2018.1.4 (see picture below). Is it a bug in Pycharm? Did I do something wrong? Is it not possible to use type hints this way? Thanks!
has answer: http://stackoverflow.com/a/50955957
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion

http://stackoverflow.com/a/50938352
downvote count: 0
has comment: http://stackoverflow.com/comment/88947189
type: Answer
answers question: http://stackoverflow.com/q/50938144
accepted answer of: http://stackoverflow.com/q/50938144
score: 4
has body: Since the interpolation is simple, you can do it by hand: import numpy as np a = np.array([1,5,11,9,13,21]) b = np.zeros(2*len(a)-1, dtype=np.uint32) b[0::2] = a b[1::2] = (a[:-1] + a[1:]) // 2 You can also use scipy.signal.resample this way: import numpy as np from scipy import signal a = np.array([1,5,11,9,13,21]) b = signal.resample(a, len(a) * 2) b_int = b.astype(int) The trick is to have exactly twice the number of elements, so that odd points match your initial points. Also I think that the Fourier interpolation done by scipy.signal.resample is better for your ECG signal than the linear interpolation you're asking for.
upvote count: 4
has comment: http://stackoverflow.com/comment/88948516
type: AcceptedAnswer

http://stackoverflow.com/q/50949764
answer count: 1
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/50949851
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50949851
type: Question
has comment: http://stackoverflow.com/comment/88897119
has title: Regex to match words in next line
score: 0
has comment: http://stackoverflow.com/comment/88897110
has body: I am working on a regex to process text, which pretty much considers text if it’s in the same line, but ignores text if it starts from the next line. I tried adding \s* but that didn’t seem to work. Can someone you please throw light on how can the regex be tuned for such condition PATTERN = r’Section One:(\s?)[\t\f ]*[\w+]’ Input: 1. Section One: Gyjbhj jchhhhj jjgvbgg 2. Section Two: lknlknvd lknlfnv lvkndflvlkvndflvkn vlkfdnlkfn 3. Section Three:pklnklnfvl lknlknvl flvkndflknvlf

http://stackoverflow.com/comment/88857645
comment on: http://stackoverflow.com/q/50929367
score: 0
type: Comment
type: QuestionComment
has text: @Kevin mn should be considered a match because it is a whole word, whereas e wouldn't because it isn't a whole word - if that makes sense?

http://stackoverflow.com/comment/88951613
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50976950
has text: Can you first try interpolation to bring both the time series at the same rate and then use autocorrelation to find the shift in starting time.
score: 0

http://stackoverflow.com/comment/88908421
comment on: http://stackoverflow.com/q/50954875
score: 0
type: Comment
has text: @ScottSkiles, `django-tables2`, IIUC takes a django queryset object as its argument. I can't get the right data using a queryset, so I'm using a Pandas DF.
type: QuestionComment

http://stackoverflow.com/q/50973663
favorite count: 0
has comment: http://stackoverflow.com/comment/88943767
tagged with: pandas
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/88943823
has answer: http://stackoverflow.com/a/50973761
answer count: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88943667
has comment: http://stackoverflow.com/comment/88943663
has answer: http://stackoverflow.com/a/50973715
downvote count: 1
type: Question
has body: I want to create a dictionary with a predetermined list, however, I can't seem to figure it out how to avoid overwriting instead of appending, and I'm not sure if I can avoid importing any other modules. The scope is that I have a data frame of 1 column of character names with ID numbers attached to the names from reading an excel file in, sega_df: Character 0 Amy (335) 1 Tails (359) 2 Shadow (357) 3 Shadow (357) 4 Blaze (337) Then I have a list of all the characters, characters, without their ID numbers: ['Sonic', 'Knuckles', 'Tails', 'Amy', 'Cream', 'Shadow', 'Rouge', 'Silver', 'Blaze'] I want to create a dictionary so I can replace sega_df.Character's by slicing each row entry with the len() of the characters in characters, producing desired_sega_df: Character 0 Amy 1 Tails 2 Shadow 3 Shadow 4 Blaze The dictionary I want to create will have keys of the characters names without their ID numbers, and values of the len() of their names. The dictionary is slice: {'Sonic': 5, 'Knuckles': 8, 'Tails': 5, 'Amy': 3, 'Cream': 5, 'Shadow': 6, 'Rouge': 5, 'Silver': 6, 'Blaze': 5} Even when I use .update() it still repeatedly overwrites with only Blaze as the key and 5 as the value. &gt;&gt;&gt; for character in characters: ... slice = {character: len(character)} ... slice.update({character:len(character)}) ... &gt;&gt;&gt; slice {'Blaze': 5} My question is: How can I modify my loop to add key-value pairs of all the characters to slice rather than continuously overwriting them?
score: 3
has answer: http://stackoverflow.com/a/50973789
accepted answer: http://stackoverflow.com/a/50973761
upvote count: 4
tagged with: for-loop
possible better answer: http://stackoverflow.com/a/50973789
has comment: http://stackoverflow.com/comment/88944933
has answer: http://stackoverflow.com/a/68761732
has title: Appending to dictionary with loop
has comment: http://stackoverflow.com/comment/88943626

http://stackoverflow.com/a/51009364
has body: Say file1.py contains: tup = (1,2,3,4,5) Then in file2.py use: from file1 import tup print(tup) (This assumes that file1.py and file2.py are in the same folder)
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51009252
accepted answer of: http://stackoverflow.com/q/51009252
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/q/50888897
favorite count: 0
tagged with: kivy-language
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/50889128
type: AnsweredQuestion
has title: how to center canvas? kivy
type: Question
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/50889128
has body: How to place the white square to the center? I tried a lot of variants, but nothing worked. It work for Label and Buttons, but not for canvas. Or maybe I'm doing everything in wrong way. maybe you suggest the best solution for this task. I need window with background, label in left corner, label in right corner and a square in center from kivy.app import App from kivy.uix.widget import Widget from kivy.uix.floatlayout import FloatLayout from kivy.config import Config from kivy.animation import Animation from kivy.vector import Vector from kivy.clock import Clock from kivy.properties import NumericProperty, ReferenceListProperty,\ ObjectProperty Config.set('graphics', 'resizable', 'true') Config.set('graphics', 'width', '900') Config.set('graphics', 'height', '450') Config.write() class Helicopter(Widget): pass class Background(Widget): pass class Root(FloatLayout): #def on_touch_down(self, touch): # Animation(center=touch.pos).start(self) pass class FriendsApp(App): def build(self): return Root() if __name__ == '__main__': FriendsApp().run() .kv file #: kivy 1.10.0 &lt;Root&gt; AnchorLayout: canvas.before: Color: rgba: 1, 1, 1, 1 # white Rectangle: source: 'background.jpg' pos: self.pos size: self.size size: self.parent.size anchor_x: 'center' anchor_y: 'center' AnchorLayout: anchor_y:'top' anchor_x:'left' padding: 20 Label: text: 'Lives: x2' size: self.texture_size size_hint: None, None AnchorLayout: anchor_x: 'right' anchor_y: 'top' padding: 20 Label: text: 'Score: 0000000' size: self.texture_size size_hint: None,None AnchorLayout: anchor_x: 'center' anchor_y: 'center' canvas: Rectangle: size: 100, 100 pos: self.pos
tagged with: kivy
score: 1

http://stackoverflow.com/comment/88830363
type: QuestionComment
comment on: http://stackoverflow.com/q/50915127
score: 3
has text: Possible duplicate of [Remove specific characters from a string in Python](https://stackoverflow.com/questions/3939361/remove-specific-characters-from-a-string-in-python)
type: Comment

http://stackoverflow.com/comment/88958482
type: Comment
has text: `else` is unnecessary.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50981572

kivy-language
type: Tag
tags question: http://stackoverflow.com/q/50968543
tags question: http://stackoverflow.com/q/50990697
tag name: kivy-language
tags question: http://stackoverflow.com/q/50888897
tags question: http://stackoverflow.com/q/50878126

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

http://stackoverflow.com/q/50889582
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/88780476
has body: I have a quick question: I have used both the method arrayname.astype('bool') and the parameter dtype = 'bool' when creating an array to try convert int type to bool type. Here is how I did it: booleanarray = np.array(range(10), dtype = 'bool') print booleanarray The output is: [False True True True True True True True True True] Now, using arrayname.astype('bool'): my_array = np.array(range(10)) my_array.astype('bool') print my_array The output becomes: [0 1 2 3 4 5 6 7 8 9] Why isn't the second output like the first? Why isn't .astype() converting the elements in my_array to bool? Thanks!
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88780361
linked to: http://stackoverflow.com/q/23143850
has comment: http://stackoverflow.com/comment/88780528
has comment: http://stackoverflow.com/comment/88780430
duplicate of: http://stackoverflow.com/q/23143850
has title: arrayname.astype('bool') vs dtype = 'bool'
type: Question
tagged with: numpy
tagged with: arrays

http://stackoverflow.com/comment/88976372
comment on: http://stackoverflow.com/q/50988340
score: 0
type: Comment
type: QuestionComment
has text: When you say reduce the spreadsheets, do you mean that you simply go into Excel and delete the columns that you don't want? Or is there a way to specify to openpyxl to only care about certain columns?

http://stackoverflow.com/comment/88787794
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50893596
has text: OTOH, if `HUBCop` only contains a single line, and that line has a single number, then `int(HUBCop.read())` is correct.

http://stackoverflow.com/comment/88801093
comment on: http://stackoverflow.com/a/50900065
type: Comment
has text: While this may theoretically answer the question, it would be preferable to include the essential parts of the answer here, and provide the link for reference.
type: AnswerComment
score: 0

http://stackoverflow.com/a/50996162
score: 0
has comment: http://stackoverflow.com/comment/88986850
type: Answer
has comment: http://stackoverflow.com/comment/88986822
has body: The any built-in function can help. val = 'Y' if any(df['city'].endswith(e) for e in ending) else 'N'
answers question: http://stackoverflow.com/q/50995942

http://stackoverflow.com/comment/88824469
score: 0
type: AnswerComment
type: Comment
has text: Hi Dillon, Thanks for the code snippet. This works fine. I have further complications. My lookup table has multiple records which could all match with Master. So the merged table has too many extra rows. I need to find a way to get my lookup to go down to 1-to-1 relation with master.
comment on: http://stackoverflow.com/a/50877130

http://stackoverflow.com/a/50935459
accepted answer of: http://stackoverflow.com/q/50934841
type: Answer
answers question: http://stackoverflow.com/q/50934841
score: 0
type: AcceptedAnswer
has body: When you are using only the most important features then there is less chance of an error happening (or less chance of the model incorrectly learn a pattern where it shouldn't). Without using feature importances There is a high chance that your model is captruing patterns where it shouldn't and hence giving importance to lesser important feature where it shouldn't. Also, Random Forest is an ensemble of decision trees, some might capture the correct feature importances, some might not. The most importance ones have such a high error rate because in some trees, they may be absolutely ignored altogther or given least importance. While some might capture it correctly Hence, you have both ends of the spectrum resulting in such a high error rate. Using feature importances You eliminate the least important features successively resulting in the fact that in successive trees, that feature will not be considered at all ( Hence lesser chance of any error happening in feature importance) Doing this successively improves the chances of more imporatant features to be selected again and again for splitting, hence the error margin is comparatively less

http://stackoverflow.com/a/50877354
has body: you need to define your getPlayerList() function take this as example: from selenium import webdriver driver=webdriver.Firefox() driver.get("https://html5.haxball.com/headless") driver.execute_script(""" // window.room = window.HBInit({ roomName: 'botts', maxPlayers: 16 }); // define the getPlayerList() functio; window.getPlayerList = function() { // here you make all the functional that you need return 'All players list'; } """) driver.execute_script(""" // now that we define our function, we can call it console.log(window.getPlayerList(); """)
answers question: http://stackoverflow.com/q/50877160
downvote count: 0
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/comment/88968417
comment on: http://stackoverflow.com/a/50965424
type: Comment
has text: In my opinion, you should never use `play.applymap(lambda x: newdict[x])`. This adds an additional and unnecessary Python-level function call. In addition, it will fail with `KeyError` if any value is not in your dictionary keys.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88983110
score: 1
has text: does it work? does it fail? what do you get?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50994279

http://stackoverflow.com/a/50942230
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/50939145
upvote count: 1
type: Answer
has body: To match any character except a newline or a dot you could use a negated character class [^.\r\n]+ and repeat that one or more times and use anchors to assert the start ^ and the end $ of the line. ^[^.\r\n]+\.flower$ Or you could specify in a character class which characters you would allow to match followed by a dot \. and flower. ^[a-z0-9]+\.flower$

http://stackoverflow.com/comment/88914742
type: Comment
type: QuestionComment
has text: The term you're looking for is anti-aliasing. Check out http://effbot.org/zone/tkinter-aggdraw.htm
comment on: http://stackoverflow.com/q/50958722
score: 0

python-2.7
tags question: http://stackoverflow.com/q/51007680
tags question: http://stackoverflow.com/q/50911868
tags question: http://stackoverflow.com/q/50937822
tags question: http://stackoverflow.com/q/50863679
tags question: http://stackoverflow.com/q/50863108
tags question: http://stackoverflow.com/q/51010481
tags question: http://stackoverflow.com/q/50888069
tags question: http://stackoverflow.com/q/50888617
tags question: http://stackoverflow.com/q/50930190
tags question: http://stackoverflow.com/q/50866870
tags question: http://stackoverflow.com/q/50927751
tags question: http://stackoverflow.com/q/50950426
tags question: http://stackoverflow.com/q/50955924
tags question: http://stackoverflow.com/q/50900249
tags question: http://stackoverflow.com/q/50884274
tags question: http://stackoverflow.com/q/50940673
tags question: http://stackoverflow.com/q/50954464
tags question: http://stackoverflow.com/q/50875363
tags question: http://stackoverflow.com/q/50942399
tags question: http://stackoverflow.com/q/50936077
tags question: http://stackoverflow.com/q/50918832
tags question: http://stackoverflow.com/q/50860112
tags question: http://stackoverflow.com/q/51001009
tags question: http://stackoverflow.com/q/50889570
tags question: http://stackoverflow.com/q/50982284
tags question: http://stackoverflow.com/q/50941165
tags question: http://stackoverflow.com/q/50930945
tags question: http://stackoverflow.com/q/50978994
tags question: http://stackoverflow.com/q/50864930
tags question: http://stackoverflow.com/q/50925937
tags question: http://stackoverflow.com/q/50861080
tags question: http://stackoverflow.com/q/50938850
tags question: http://stackoverflow.com/q/50921536
tags question: http://stackoverflow.com/q/50995271
tags question: http://stackoverflow.com/q/50929823
tags question: http://stackoverflow.com/q/50948082
tags question: http://stackoverflow.com/q/50861398
tags question: http://stackoverflow.com/q/50920373
tags question: http://stackoverflow.com/q/50943208
tags question: http://stackoverflow.com/q/51005805
tags question: http://stackoverflow.com/q/50918476
tags question: http://stackoverflow.com/q/50913071
tags question: http://stackoverflow.com/q/50885583
tags question: http://stackoverflow.com/q/50934300
tags question: http://stackoverflow.com/q/50977476
tags question: http://stackoverflow.com/q/50864810
tags question: http://stackoverflow.com/q/50899704
tags question: http://stackoverflow.com/q/50962303
tags question: http://stackoverflow.com/q/50937878
tags question: http://stackoverflow.com/q/50917535
tags question: http://stackoverflow.com/q/50941424
tags question: http://stackoverflow.com/q/50870912
tags question: http://stackoverflow.com/q/50976129
tags question: http://stackoverflow.com/q/50893482
tags question: http://stackoverflow.com/q/50965533
tags question: http://stackoverflow.com/q/50892550
tags question: http://stackoverflow.com/q/50974070
tags question: http://stackoverflow.com/q/50968896
tags question: http://stackoverflow.com/q/51011297
tags question: http://stackoverflow.com/q/50976915
tags question: http://stackoverflow.com/q/50909271
tags question: http://stackoverflow.com/q/50893788
tags question: http://stackoverflow.com/q/51008903
tags question: http://stackoverflow.com/q/50889565
tags question: http://stackoverflow.com/q/51008695
tags question: http://stackoverflow.com/q/50994279
tags question: http://stackoverflow.com/q/50934465
tags question: http://stackoverflow.com/q/50877065
tags question: http://stackoverflow.com/q/50933025
tags question: http://stackoverflow.com/q/50998990
tags question: http://stackoverflow.com/q/50935312
tags question: http://stackoverflow.com/q/50998710
tags question: http://stackoverflow.com/q/50865560
tags question: http://stackoverflow.com/q/50912888
tags question: http://stackoverflow.com/q/50901787
tags question: http://stackoverflow.com/q/50887539
tags question: http://stackoverflow.com/q/50961759
tags question: http://stackoverflow.com/q/51007775
tags question: http://stackoverflow.com/q/50961307
tags question: http://stackoverflow.com/q/50899891

http://stackoverflow.com/q/51004906
has answer: http://stackoverflow.com/a/51123013
has body: I'm trying to draw a line between two draggable points that are on a matplotlib canvas, embedded in a pyqt5 application. I'm using Draggable line with draggable points as a reference. However I'm trying to create multiple lines, with a pair of DraggablePoint objects being created on a button-click. Several problems are occuring for me: The line only appears when the points are being dragged (solved, see update below) The line is offset by a margin, which I assume is the difference between the canvas and the actual matplotlib plot. However the scaling isn't right either. The line for the 2nd point-pair is not showing at all Below is my adapted code: DraggablePoint import matplotlib.pyplot as plt import matplotlib.patches as patches from matplotlib.lines import Line2D import matplotlib class DraggablePoint: lock = None def __init__(self, parent, dominant, x=10, y=10, size=1): """Creates a draggable Point on a matplotlib canvas""" matplotlib.matplotlib_fname() # The FigureCanvas self.parent = parent # The Point self.point = patches.Ellipse((x, y), size, size, fc='r', alpha=0.5, edgecolor='r') #Coordinates of the point self.x = x self.y = y self.dy = 645 self.dx = 263 # Adds the point to the Plot parent.fig.axes[0].add_patch(self.point) # Used in the on_press() function self.press = None self.background = None # initiate the mpl_connects self.connect() # The Other DraggablePoint, with whom the line shall connect with. self.partner = None # The Line2D self.line = None # TODO self.dominant = dominant for pair in self.parent.point_pairs: if self in pair: if pair[1]: line_x = [pair[0].x+self.dx, pair[1].x+self.dx] line_y = [pair[0].y+self.dy, pair[1].y+self.dy] self.line = Line2D(line_x, line_y, color='r', alpha=0.5) parent.fig.axes[0].add_line(self.line) def connect(self): 'connect to all the events we need' # print("LOG.INFO: DraggablePoint.connect") self.cidpress = self.point.figure.canvas.mpl_connect('button_press_event', self.on_press) self.cidrelease = self.point.figu…
type: AnsweredQuestion
favorite count: 0
type: Question
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/51123013
answer count: 1
linked to: http://stackoverflow.com/q/28001655
tagged with: matplotlib
tagged with: pyqt5
has title: Line between two draggable points on a matplotlib pyqt5 canvas
downvote count: 0
score: 1

http://stackoverflow.com/comment/88725947
has text: I did try a few options like that and just tried this one. Still getting the same error.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50861398

http://stackoverflow.com/a/51030837
type: Answer
has body: Found raeson of fail, the print passed by cron don't encode/decode the same as the console (!??). ... print (u"Alerte, tous à poil !") UnicodeEncodeDecode Error ! Strange, looks like cron doesn't encode / decode the same than the user.... (!?) Solved with no latin characters in print, or print passed by try/except...
score: 0
answers question: http://stackoverflow.com/q/51008386

http://stackoverflow.com/q/50919824
answer count: 2
has answer: http://stackoverflow.com/a/50926899
has comment: http://stackoverflow.com/comment/88841048
possible better answer: http://stackoverflow.com/a/50936556
has comment: http://stackoverflow.com/comment/88853600
has answer: http://stackoverflow.com/a/50936556
tagged with: python
linked to: http://stackoverflow.com/q/35508866
tagged with: c++
type: AnsweredQuestion
has body: My tensorflow model for this example is simple and has been successfully loaded. My question is, to run inference, what do I pass the tf::Session? How do I create the feedDict mentioned here and what are my "outputOps"? Here's the model in python: model = tf.keras.Sequential([ tf.keras.layers.Convolution2D(filters, (5, 5), input_shape=(BoardDepth, BoardLength, BoardLength), data_format='channels_first', name='Input'), tf.keras.layers.Activation('relu', name='Relu'), tf.keras.layers.MaxPooling2D(pool_size=(2,2), name='Pool'), tf.keras.layers.Flatten(name="Flatten"), tf.keras.layers.Dense(BoardSize, activation='softmax', name='Output'), ]) optimizer = tf.train.AdamOptimizer(learning_rate=0.0018) model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy']) Here's the method used to train the model which uses a generator to feed images in: earlyExit = keras.callbacks.EarlyStopping(monitor='val_acc', min_delta=0, patience=0) # Train the model history = model.fit_generator(generator=gen.generator(), steps_per_epoch=gen.stepsPerEpoch(), validation_data=valGen.generator(), validation_steps=valGen.stepsPerEpoch(), epochs=numEpochs, verbose=2, workers=1, callbacks=[earlyExit]) And here's the method used to save the model: K.set_learning_phase(0) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) saver = tf.train.Saver(tf.trainable_variables()) saver.save(sess, './models/test/latestModel') In case you didn't follow the link above inference is supposed to be done with something like this: // and run the inference to your liking auto feedDict = ... auto outputOps = ... std::vector&lt;tensorflow::Tensor&gt; outputTensors; status = session-&gt;Run(feedDict, outputOps, {}, &amp;outputTensors); I've tried following the example here but cannot seem to figure out what I need to pass as outputOps. Do I need to only pass the name of the output node, or do I need to pass every single operation in the model? The different configurations I'v…
tagged with: tensorflow
has title: Running inference with a loaded tensorflow model in C++
type: Question
has comment: http://stackoverflow.com/comment/88840575
has comment: http://stackoverflow.com/comment/88848535
accepted answer: http://stackoverflow.com/a/50926899
has comment: http://stackoverflow.com/comment/88870794
score: 0

directed-acyclic-graphs
type: Tag
tag name: directed-acyclic-graphs
tags question: http://stackoverflow.com/q/50885343

http://stackoverflow.com/comment/88891255
type: QuestionComment
has text: Did you try `pandas.DataFrame.to_sql`: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_sql.html?
score: 0
comment on: http://stackoverflow.com/q/50946993
type: Comment

http://stackoverflow.com/q/50883000
has title: NLTK -> Using Stanford Dependency Parser ->
type: AnsweredQuestion
favorite count: 0
has body: There seems to be a lot of contradicting documentation for NLTK (where is the definitive source for NLTK/StanfordNLP documentation?). My question: what is the preferred method to call the StanfordParser from nltk? This is my code, but something is incorrect in the java call. from nltk.parse.stanford import StanfordDependencyParser import os parser_home = '/Users/myname/Documents/nlp/stanford-parser-full-2018-02-27/' # os.environ['CLASSPATH'] = parser_home parser = StanfordDependencyParser( model_path = parser_home + 'stanford-parser.jar', path_to_models_jar = parser_home + 'stanford-parser-3.9.1-models.jar', verbose = True ) result = parser.raw_parse('Here is an example sentence.') Here's my error. Any help appreciated. I haven't found an exact match to mine. I'm setting the classpath, but I'm not sure that's required. [Found stanford-parser\.jar: /Users/myname/Documents/nlp/stanford-parser-full-2018-02-27/stanford-parser.jar] [Found stanford-parser-(\d+)(\.(\d+))+-models\.jar: /Users/myname/Documents/nlp/stanford-parser-full-2018-02-27/stanford-parser-3.9.1-models.jar] /Users/myname/anaconda3/envs/nlp/lib/python3.6/site-packages/ipykernel_launcher.py:12: DeprecationWarning: The StanfordDependencyParser will be deprecated Please use nltk.parse.corenlp.StanforCoreNLPDependencyParser instead. if sys.path[0] == '': SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". SLF4J: Defaulting to no-operation (NOP) logger implementation SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details. Exception in thread "main" java.lang.RuntimeException: /Users/myname/Documents/nlp/stanford-parser-full-2018-02-27/stanford-parser.jar: expecting BEGIN block; got PK��aL META-INF/��PKPK��aLMETA-INF/MANIFEST.MFE�� at edu.stanford.nlp.parser.lexparser.LexicalizedParser.confirmBeginBlock(LexicalizedParser.java:536) at edu.stanford.nlp.parser.lexparser.LexicalizedParser.getParserFromTextFile(LexicalizedParser.java:546) at edu.stanford.nlp.parser.lexparser.…
type: Question
has answer: http://stackoverflow.com/a/50913980
tagged with: python
answer count: 1
score: 4
tagged with: java
upvote count: 4
accepted answer: http://stackoverflow.com/a/50913980
tagged with: stanford-nlp
tagged with: nltk
downvote count: 0

http://stackoverflow.com/comment/88999467
has text: Thank you!, i tried running the script. Encountered error in this row :if row not in seen: TypeError: unhashable type: 'writeable void-scalar' which i did not understand. What i did, is place the block of scripts after I load the data. Before that, I exclude the new created table in the question.
type: Comment
comment on: http://stackoverflow.com/a/51002758
score: 0
type: AnswerComment

http://stackoverflow.com/q/50964310
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/50965055
type: Question
answer count: 2
has body: I have 70 GB of files, mostly TXT, CSV and logs sourcing from publicly disclosed information either for research, training neural networks etc. I would like to serialize to json every line in that files and push to elastic search to make use of it. Lines might contain special characters that json encoder should escape like Russian letters, Korean etc. I cannot just take a 10 GB file, encode it as a one object and push it to elastic because of Apache Lucene file size limitation. Most of the entries contains: 9:username:someemail@gstuff:eafff17afbef485a894][;'.f6d39c56b79: 254:Starcius:someemail@gstuff:09160da290bcd1f83fssf0bd260e13d4f: 2:username:someemail@gstuff:104b77708bb7c19b9f913449c923a898:8 2:username:someemail@gstuff:efc38fca88d8e58089adccce3e05f93 254:username:someemail@gstuff:880896502dd68b546258\][;.'54cca34 2:username:someemail@gstuff:647b61ba8f0965e762c579e5b3da9eca:hUr 2:username:someemail@gstuff::3e9478fcecb4e90266art87g8fiuba90c6ed5473c:\^c 2:username:someemail@gstuff:9df5783228asdasddas796e18cb12e44da:,M| I want to take each line of the file (delimited by new line) and produce something like (escaping the illegal json characters): {"data":"9:username:someemail@gstuff:eafff17afbef485a894][;\'.f6d39c56b79:"}, {"data":"9:username:someemail@gstuff:eafff17afbef485a894][;\'.f6d39c56b79:"}, {"data":"9:username:someemail@gstuff:eafff17afbef485a894][;\'.f6d39c56b79:"} What would it be the best approach for this problem?
score: 0
accepted answer: http://stackoverflow.com/a/50965055
tagged with: elasticsearch
possible better answer: http://stackoverflow.com/a/50964610
tagged with: python
has answer: http://stackoverflow.com/a/50964610
has title: Serialize data into json using Python
type: AnsweredQuestion

http://stackoverflow.com/comment/88868964
has text: Yes it is possible, but you would have to implement your own decision tree to do the manual changing of nodes that you want. :)
comment on: http://stackoverflow.com/a/50914545
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/50880811
tagged with: beautifulsoup
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50881049
accepted answer: http://stackoverflow.com/a/50891738
upvote count: 1
tagged with: python
has title: Can't get rid of navigability issues caused by BeautifulSoup
type: AnsweredQuestion
score: 1
tagged with: web-scraping
type: Question
answer count: 2
has body: I've written a script in python in combination with BeautifulSoup to parse a certain address from a webpage. However, when i run my below script I get an issue AttributeError: 'NavigableString' object has no attribute 'text' when it hits the line address = [item.find_next_sibling().get_text(strip=True). I can get rid of this issue if I try the commented out lines. However, I would like to stick to the way that is currently applied. What can I do so ? This is my try: import requests from bs4 import BeautifulSoup URL = "https://beta.companieshouse.gov.uk/officers/lX9snXUPL09h7ljtMYLdZU9LmOo/appointments" def fetch_names(session,link): session.headers = {"User-Agent":"Mozilla/5.0"} res = session.get(link) soup = BeautifulSoup(res.text,"lxml") for items in soup.select("#content-container dt"): #the error appears in the following line address = [item.find_next_sibling().get_text(strip=True) for item in items if "correspondence address" in item.text.lower()][0] print(address) if __name__ == '__main__': with requests.Session() as session: fetch_names(session,URL) I can get rid of the error by doing something like below but i wanna stick to the way I tried in my script: items = soup.select("#content-container dt") address = [item.find_next_sibling().get_text(strip=True) for item in items if "correspondence address" in item.text.lower()][0] print(address) EDIT: It's not an answer but this is how I tried to play around (still unsure how to apply .find_previous_sibling() though: import requests from bs4 import BeautifulSoup URL = "https://beta.companieshouse.gov.uk/officers/lX9snXUPL09h7ljtMYLdZU9LmOo/appointments" def fetch_names(session,link): session.headers = {"User-Agent":"Mozilla/5.0"} res = session.get(link) soup = BeautifulSoup(res.text,"lxml") for items in soup.select("#content-container dt"): address = [item for item in items.strings if "correspondence address" in item.lower()] print(address) if __name__ == '__main__': with requests.Session() as session: fetch_names(…
downvote count: 0
has answer: http://stackoverflow.com/a/50891738
possible better answer: http://stackoverflow.com/a/50881049
favorite count: 0

http://stackoverflow.com/q/50915995
tagged with: kivy
has body: I am messing with Cython, diving deeper into kivy and I have been trying my hand at making my own Kivy Property. I have the following files difining a DocProperty: my.pyx: from kivy.properties cimport Property, PropertyStorage from kivy._event cimport EventDispatcher cdef inline void observable_object_dispatch(object self, str name): cdef Property prop = self.prop prop.dispatch(self.obj, name) class ObservableObject(object): # Internal class to observe changes inside a native python object. def __init__(self, *largs): self.prop = largs[0] self.obj = largs[1] super(ObservableObject, self).__init__() def __setattr__(self, name, value): object.__setattr__(self, name, value) observable_object_dispatch(self, name) cdef class DocProperty(Property): def __init__(self, defaultvalue=None, rebind=False, **kw): self.baseclass = kw.get('baseclass', object) super(DocProperty, self).__init__(defaultvalue, **kw) self.rebind = rebind cpdef link(self, EventDispatcher obj, str name): Property.link(self, obj, name) cdef PropertyStorage ps = obj.__storage[self._name] ps.value = ObservableObject(self, obj, ps.value) cdef check(self, EventDispatcher obj, value): if Property.check(self, obj, value): return True if not isinstance(value, object): raise ValueError('{}.{} accept only object based on {}'.format( obj.__class__.__name__, self.name, self.baseclass.__name__)) cpdef dispatch(self, EventDispatcher obj, str name): '''Dispatch the value change to all observers. .. versionchanged:: 1.1.0 The method is now accessible from Python. This can be used to force the dispatch of the property, even if the value didn't change:: button = Button() # get the Property class instance prop = button.property('text') # dispatch this property on the button instance prop.dispatch(button) ''' cdef PropertyStorage ps = obj.__storage[self._name] ps.observers.dispatch(obj, ps.value, (name,), None, 0) my.pxd: from kivy.properties cimport Property, PropertyStorage from kivy._event cimport EventDispatcher cdef cl…
score: 1
has answer: http://stackoverflow.com/a/50917664
tagged with: cython
upvote count: 1
type: Question
tagged with: overriding
downvote count: 0
has title: Is it possible to overload cpdef declaration on Cython .pxd?
answer count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/48864631
linked to: http://stackoverflow.com/q/10202938
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/88888489
type: AnswerComment
type: Comment
score: 2
comment on: http://stackoverflow.com/a/50945510
has text: I knew there was something simple, thanks heaps Jan, worked a charm!

http://stackoverflow.com/comment/88835286
type: QuestionComment
comment on: http://stackoverflow.com/q/50917450
score: 0
has text: @xerxes01 Did you read my updated comment? Let me explain more: this approach works if all the images in category 1 have a target vector of say `[2, 9.8, 19, 78]`, or by analyzing the content of image you can generate its target vector. Is it the case?
type: Comment

http://stackoverflow.com/a/50857333
downvote count: 0
has comment: http://stackoverflow.com/comment/88742230
type: Answer
has comment: http://stackoverflow.com/comment/88719850
upvote count: 1
answers question: http://stackoverflow.com/q/50856449
has body: You could apply the following algorithm: For each patch (x, y, width, height) in the WSI, compute its coordinates relative to the mask position: (x2, y2, width2, height2). There are some calculations to do here with min and max but nothing impossible. For each patch, compute the ratio cv2.countNonZero(mask[y2:y2+height2, x2:x2 + width2]) / (self.crop_size * self.crop_size). If this ratio is above 2/3, then you can set your patch as isFit = True. To get the position of the patch in the mask, let's assume that the mask is a rectangle with coordinates (x_m, y_m, width_m, height_m) in the WSI. Then a patch (x, y, width, height) will have the following coordinates in the mask: x2 = max(x - x_m, 0) This value can be higher than width_m in which case you ignore the patch as it is completely outside the mask. y2 = max(y - y_m, 0) This value can be higher than height_m in which case you ignore the patch as it is completely outside the mask. width2 = min(self.crop_size, width_m - x2) height2 = min(self.crop_size, height_m - y2)
score: 1
accepted answer of: http://stackoverflow.com/q/50856449
has comment: http://stackoverflow.com/comment/88719804
type: AcceptedAnswer

http://stackoverflow.com/comment/88738261
type: QuestionComment
comment on: http://stackoverflow.com/q/50868046
has text: Yes it should: make sure you can access *flask* site.
type: Comment
score: 1

http://stackoverflow.com/comment/88750109
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50874350
has text: Don't use pictures or links. Include all relevant code in your question *as text*. See [mcve].
score: 0

http://stackoverflow.com/a/50901766
answers question: http://stackoverflow.com/q/50901653
score: 1
upvote count: 1
downvote count: 0
has body: input() values will be stored as str. It all comes down to what the user inputs. The piece of code you provided is very bad, because the user has to guess what to input and when. But the logic works as follows: If you type in a single value, then int(input()) will convert that value to integer. For example, if you input 2, then input() will hold the string "2" and int("2") will yield integer 2. If you have multiple values, then you cannot convert to int right away, because what the hell does int("2 10") mean? That is why you have to use .split(), to separate these multiple values in many singular values. For example, if you run x = input() and type in 2 10, then x will hold the string "2 10". Now, "2 10".split() yields the list of strings ["2", "10"]. The piece of code map(int,input().split()) comes in to convert this list of strings to a list of integers. It maps each value to a new value using the function int to transform it. Now that this is established, it becomes easier to understand how this works in a for loop using range. The range type, as per docs, may have one parameter stop or three arguments (start, stop [, step]) in its constructor. These arguments are all integers. Thus, the values from input() have to fit this structure. If you type in 2 10 in input, and try to do range("2 10"), you'll receive an error. Because you are passing one argument of type str. That is why you have to convert to integer first. But you cannot convert "2 10" to integer right away, as we just discussed. That is why you have to split first, and then convert each value to int, and just then pass these as arguments to range(). So, to summarize, given x = input() and you type in 2 10, here is what does not work: &gt;&gt;&gt; int(x) &gt;&gt;&gt; range(x) what does work: &gt;&gt;&gt; a,b=map(int,input().split()) &gt;&gt;&gt; range(a, b)
type: Answer

http://stackoverflow.com/comment/88790393
score: 0
has text: The input is in the form of a string and I am writing it into a csv file column wise. In this case, the column name is `IPV4_SRC_ADDR`
comment on: http://stackoverflow.com/q/50895144
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50907604
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50907200
has body: Just write as JSON ? import json document_list = [['This', 'is', 'the', 'title', '\n\n\n\n', 'Rest', 'of', 'the', 'first', 'document'], ['Second', 'Document', '\t', 'title', '\n\n\n\n']] with open('doc_list.txt', 'w', encoding="utf-8") as file: file.write(json.dumps(document_list))

http://stackoverflow.com/q/50971075
linked to: http://stackoverflow.com/q/1015592
type: Question
tagged with: object
score: 3
tagged with: internal
has comment: http://stackoverflow.com/comment/88938935
has comment: http://stackoverflow.com/comment/88938928
has title: python - Can you replace an object completely by internal method?
tagged with: replace
has answer: http://stackoverflow.com/a/50971235
accepted answer: http://stackoverflow.com/a/50971235
has body: We are struggling with the following problem in python 3: we have defined a class, which inherits from list. We want to incorporate a method by which it can update itself to a new instance of this class. Some very simple code to illustrate what we mean: class test(list): def update(self): self = test(['a','b','c','d']) x = test([1,2,3]) x.update() print(x) This code returns the original list [1,2,3], which shows that the object x indeed hasn't been updated. Is there a way to let an object update itself completely? We need this to work for lists of different lengths.
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python
linked to: http://stackoverflow.com/q/1216356
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88938724
upvote count: 3
tagged with: methods

http://stackoverflow.com/q/50896869
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50896982
tagged with: input
tagged with: python
score: 4
has answer: http://stackoverflow.com/a/50896916
has title: python , run def() multiple times
has comment: http://stackoverflow.com/comment/88793608
has body: i wrote this code to get Ebay prices it asks for full ebay link then it writes its price import bs4 , requests print('please enter full Ebay link ..') link = str(input()) def ebayprice(url): res = requests.get(link) res.raise_for_status() txt = bs4.BeautifulSoup(res.text , 'html.parser') csselement = txt.select('#mm-saleDscPrc') return csselement[0].text.strip() price = ebayprice(link) print('price is : '+ price) i want to improve it and i tried my best and i couldnt i want it to take multiple links and run them one by one and it should write results each time it doesnt matter if links are from input() or from links = 'www1,www2,www3'
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/88793482
answer count: 2
downvote count: 0
favorite count: 0

http://stackoverflow.com/a/50994805
has comment: http://stackoverflow.com/comment/93422822
downvote count: 0
has body: In addition too: sys.path.insert(0, os.path.abspath("..Scripts/")) I added this afterward: sys.path.insert(0, os.path.abspath("..Scripts/Folder/")) Which allowed me to access files in Folder with autodoc.
upvote count: 8
type: Answer
score: 8
answers question: http://stackoverflow.com/q/50990626

http://stackoverflow.com/q/50903270
has comment: http://stackoverflow.com/comment/88806460
has comment: http://stackoverflow.com/comment/88806495
has title: error:list index out of range in a for loop
tagged with: python
has comment: http://stackoverflow.com/comment/88806370
type: Question
has answer: http://stackoverflow.com/a/50903373
has comment: http://stackoverflow.com/comment/88806535
has body: So I was making a program that counts and prints the number of runs scored, the bowls bowled, the bowler and the batsman which is on strike in a cricket match but when i finished my code: name = input('enter the name of the bowler\n=') # we ask for the input bat_strike = input('enter the name of the batter on strike\n=') bat_non_strike = input('enter the name of the batter on the non strike\n=') bowls = 6 # this is the max number of bowls in a over bowls_bowled = 0 runs_list = [] bowls_list = [] batter_list = [] batter_list.append(bat_strike) for j in range(0, bowls): bowl_type = int(input('enter the number corresponding to the option regarding the bowl bowled right now\n1)wide bowl\n2)simple bowl\n3)no ball\n4)dead bowl\n5)1D\n= ')) if bowl_type == 1: bowls_list.append('wd') runs_list.append(1) batter_list.append(bat_strike) bowls += 1 elif bowl_type == 2: run = int(input('enter the number of runs scored on that bowl 1 for 1 run 2 for 2 runs 3 for 3 runs 4 for 4 runs or 0 for a dot ball\n=')) if run == 1 or run == 3: batter_on_strike = input('enter wether the batter on strike is on non strike? y or n\n=') if batter_on_strike == 'y': c = bat_strike bat_non_strike = bat_strike bat_non_strike = c batter_list.append(bat_strike) runs_list.append(run) bowls_list.append(1) bowls_bowled += 1 elif bowl_type == 3: bowls_list.append('no ball') runs_list.append(1) bowls += 1 batter_list.append(bat_strike) elif bowl_type == 4: bowls_list.append('dead bowl') bowls += 1 batter_list.append(bat_strike) elif bowl_type == 5: bowls_list.append('1D') bowls += 1 runs_list.append(1) bowls_bowled += 1 batter_list.append(bat_strike) for i in range(0, bowls-1): print(f'bowler={name} batter on strike={batter_list[i]} bowl bowled={bowls_list[i]} runs scored={runs_list[i]}') it produces the following error print(f'bowler={name} batter on strike={batter_list[i]} bowl bowled={bowls_list[i]} runs scored={runs_list[i]}') IndexError: list index out of range I want to display the results using a for…
has comment: http://stackoverflow.com/comment/88806321
score: 0
answer count: 1
tagged with: python-3.x
type: UnansweredQuestion

http://stackoverflow.com/q/51011204
tagged with: python
has answer: http://stackoverflow.com/a/51011357
downvote count: 2
has answer: http://stackoverflow.com/a/51011456
has comment: http://stackoverflow.com/comment/89015409
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89015048
possible better answer: http://stackoverflow.com/a/51011456
score: -2
has title: Function call error in Python
has comment: http://stackoverflow.com/comment/89015198
accepted answer: http://stackoverflow.com/a/51011357
has body: I have a 1D array X with both +/- elements. I'm isolating their signs as follows: idxN, idxP = X&lt;0, X&gt;=0 Now I want to create an array whose value depends on the sign of X. I was trying to compute this but it gives the captioned syntax error. y(idxN) = [math.log(1+np.exp(x)) for x in X(idxN)] y(idxP) = X(idxP)+[math.log(np.exp(-x)+1) for x in X(idxP)]; Is the LHS assignment the culprit? Thanks. [Edit] The full code is as follows: y = np.zeros(X.shape) idxN, idxP = X&lt;0, X&gt;=0 y(idxN) = [math.log(1+np.exp(x)) for x in X(idxN)] y(idxP) = X(idxP)+[math.log(np.exp(-x)+1) for x in X(idxP)]; return y The traceback is: y(idxN) = [math.log(1+np.exp(x)) for x in X(idxN)] File "&lt;ipython-input-63-9a4488f04660&gt;", line 1 y(idxN) = [math.log(1+np.exp(x)) for x in X(idxN)] ^ SyntaxError: can't assign to function call
tagged with: syntax-error
answer count: 2
upvote count: 0
has comment: http://stackoverflow.com/comment/89015111
favorite count: 0

http://stackoverflow.com/comment/88750692
score: 0
type: Comment
type: QuestionComment
has text: looks like your code works fine. which version of pandas are you using?
comment on: http://stackoverflow.com/q/50873572

http://stackoverflow.com/comment/88740300
type: AnswerComment
has text: Thanks! removing 'str' from dsc and asc worked. Since I have converted the string into 'int' twice, I guess no need to change result = int(des) - int(asc) to num = int(des) - int(asc). Thank you so Much @Luke Woodward.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50865405

http://stackoverflow.com/a/50930479
has comment: http://stackoverflow.com/comment/88860309
has comment: http://stackoverflow.com/comment/88860496
answers question: http://stackoverflow.com/q/50930393
upvote count: 5
has comment: http://stackoverflow.com/comment/88859870
has body: A couple of points to note: You can use a list or dictionary to store a variable number of variables. Your Boolean series function as NumPy arrays; you can therefore combine a collection of series and use np.ndarray.all (or pd.DataFrame.all) to calculate their intersection. You can use a list of Boolean series with NumPy or Pandas: conditions = [df['A'] &gt; 3, df['B'] &gt; 6, df['C'] &gt; 5] # all equivalent select = pd.concat(conditions, axis=1).all(axis=1) select = np.logical_and.reduce(conditions) select = np.array(conditions).all(axis=0) print(select) array([False, False, False, True, True, False], dtype=bool) Equivalently, if you wish to name your Boolean filters, you can use a dictionary: conditions = {1: df['A'] &gt; 3, 2: df['B'] &gt; 6, 3: df['C'] &gt; 5} select = np.array(list(conditions.values())).all(axis=0) Performance benchmarking Performance will be very data-dependent, you should also try reduce as per @Kopytok's solution and check performance with your data. df = pd.concat([df]*1000) conditions = [df['A'] &gt; 3, df['B'] &gt; 6, df['C'] &gt; 5] conditions = conditions*100 %timeit reduce(lambda x, y: x &amp; y, conditions) # 104 ms per loop %timeit np.logical_and.reduce(conditions) # 104 ms per loop %timeit np.array(conditions).all(axis=0) # 99.4 ms per loop %timeit pd.concat(conditions, axis=1).all(axis=1) # 34.6 ms per loop
type: Answer
downvote count: 0
score: 5
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50930393

http://stackoverflow.com/comment/88766649
comment on: http://stackoverflow.com/q/50882090
has text: It looks like a bug. I answered a question similar to this one a while ago, see here: https://stackoverflow.com/questions/38470550/why-is-a-sum-of-strings-converted-to-floats/38470963#38470963. Fundamentally, the way that Pandas deals with datatypes is a bit messy.
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/50882950
accepted answer: http://stackoverflow.com/a/50883094
type: Question
tagged with: python
tagged with: python-3.x
score: 0
answer count: 2
has title: byte literal array to string
has answer: http://stackoverflow.com/a/50883030
has body: I am new to Python, I am calling an external service and printing the data which is basically byte literal array. results = q.sync('([] string 2#.z.d; `a`b)') print(results) [(b'2018.06.15', b'a') (b'2018.06.15', b'b')] To Display it without the b, I am looping through the elements and decoding the elements but it messes up the whole structure. for x in results: for y in x: print(y.decode()) 2018.06.15 a 2018.06.15 b Is there a way to covert the full byte literal array to string array (either of the following) or do I need to write a concatenate function to stitch it back? ('2018.06.15', 'a') ('2018.06.15', 'b') (2018.06.15,a) (2018.06.15,b) something like the following (though I want to avoid this approach ) for x in results: s="" for y in x: s+="," +y.decode() print(s) ,2018.06.15,a ,2018.06.15,b
possible better answer: http://stackoverflow.com/a/50883030
has answer: http://stackoverflow.com/a/50883094
type: AnsweredQuestion

http://stackoverflow.com/q/50897445
tagged with: http://stackoverflow.com/tag/html
downvote count: 1
has body: I have a HTML formatted text string from an earlier text processing step. It goes like this, and you see that any &lt;SPACE&gt; character has been replaced by a &amp;nbsp; sequence: ...this&amp;nbsp;is&amp;nbsp;some&amp;nbsp;text&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;and&amp;nbsp;some&amp;nbsp;further&amp;nbsp;&amp;nbsp;&amp;nbsp;text... Now, I want to replace some of the &amp;nbsp; sequences within the text with a &lt;SPACE&gt; character. The rules would be: replace any single &amp;nbsp; sequence with a single &lt;SPACE&gt; character replace the first &amp;nbsp; sequence within a series of &amp;nbsp; sequences with a single &lt;SPACE&gt; character The resulting string should then look like this: ...this is some text &amp;nbsp;&amp;nbsp;&amp;nbsp;and some further &amp;nbsp;&amp;nbsp;text... Any ideas for a programmatical approach using Python?
favorite count: 0
tagged with: python
tagged with: text
type: AnsweredQuestion
has title: replace first of &nbsp; sequence with space character
type: Question
answer count: 1
has answer: http://stackoverflow.com/a/50897526
accepted answer: http://stackoverflow.com/a/50897526
score: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/88794710

http://stackoverflow.com/comment/88965987
type: QuestionComment
has text: Are you trying to make pip “pin” the version of a package? Not sure what solution you are looking for. Once the package is installed, it will not install it again unless there is an upgrade, and if there is one, you can ignore the upgrade. I think there is something here we are missing, like what is triggering pip?
comment on: http://stackoverflow.com/q/50982701
score: 0
type: Comment

http://stackoverflow.com/comment/88794749
comment on: http://stackoverflow.com/q/50897358
score: 0
type: Comment
type: QuestionComment
has text: strange, whats the error

http://stackoverflow.com/comment/88719247
type: AnswerComment
has text: Exactly! I'm traditionally a C/C++ developer, so I'm just getting into web dev over here haha
comment on: http://stackoverflow.com/a/50857648
type: Comment
score: 0

http://stackoverflow.com/comment/123750303
has text: @rheras you probably have the wrong file. Check which python version you have and ensure the numbers after cp match it. And also you may need the 64-bit version instead. Once you have the correctly matched file you won't get this error.
comment on: http://stackoverflow.com/a/61483254
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50874163
has comment: http://stackoverflow.com/comment/88750589
has comment: http://stackoverflow.com/comment/88750281
tagged with: python
tagged with: excel
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50875162
has comment: http://stackoverflow.com/comment/88750423
score: 1
upvote count: 1
type: Question
has title: How to use python to append data to specific cell to existing excel table?
has comment: http://stackoverflow.com/comment/88751556
has answer: http://stackoverflow.com/a/50875162
has body: I am a new starter for Python and currently doing some data analysis. I distributed few surveys using the same format. I want to sum the data from same cell (e.g. A1) from different tables(Say I have 100 surveys) but do not know how to achieve that. I learned that excel sum function could sum the data from different sheets but it does not works when they are in different excel files. I tried to use Python to sum that and export to a new excel with exact the same format. But I came across the problem of append data to specific cell to the existing file. I used openpyxl for that but they cant read xls file and I cant change my file to xlsx. Do you have any ideas to solve this or how to quick aggregate data from different table and output them to specific cell? from openpyxl import load_workbook; book = load_workbook('C:\Template.xls') sheet = load_workbook.active sheet['A1'] = sum(Annual_data book.save('C:\Template.xls') It is like you have 100 tables with same format as below, and I want to sum all B2 from 100 tables and output it to another table with same format.
answer count: 1
downvote count: 0
tagged with: vba
favorite count: 0

http://stackoverflow.com/a/50902303
upvote count: 1
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/50902251
has body: import random x = int(input("guess a number between 0 and 10: \n")) y = random.randint(0,10) n = "try again" while x != y: x = int(input('try again')) else: print('congratulations!') Or: import random x = int(input("guess a number between 0 and 10: \n")) y = random.randint(0,10) n = "try again" var = True while var: if x != y: x = int(input('try again: ')) else: print('congratulations!') var = False
type: Answer

http://stackoverflow.com/q/50951837
downvote count: 0
has body: I just started learning pandas and I have a dataframe that looks like Date Average Volume 2013-02-07 400 4100 2013-02-08 389 3400 2013-02-23 380 3100 If the user says they want the information from the 1st column(I'm referring to the Average here, I am excluding date as its sort of a constant), I want it to return ['2013-02-07', 400] ['2013-02-08', 389] ['2013-02-23', 380] If they asked for the info from the 2nd column it would return the date and volume info in the same format. data_list(file_object,column_number) inp = int(input('Which column?' )) if inp = 1: df['Average'].iloc[0:] if inp = 2: df['Volume'].iloc[0:] This returns the column the user wants, but how can I return it with the date in the format requested above?
favorite count: 0
has comment: http://stackoverflow.com/comment/88901702
has answer: http://stackoverflow.com/a/50953694
tagged with: pandas
has title: How can I read 2 columns in dataframe in pandas and return a list of lists of the data?
tagged with: python
score: 2
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50953695
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88901343
has comment: http://stackoverflow.com/comment/88901735
type: Question
answer count: 2

http://stackoverflow.com/comment/88714588
comment on: http://stackoverflow.com/q/50855076
score: 0
type: Comment
type: QuestionComment
has text: Thank you, this is what i am planning to do by determining total frames divide them and setting positions but do you mean that i can not send the start-end points to my function or is it possible to process them in this way ?

http://stackoverflow.com/q/50918637
upvote count: 0
linked to: http://stackoverflow.com/q/4806911
tagged with: string
favorite count: 0
has comment: http://stackoverflow.com/comment/110500428
duplicate of: http://stackoverflow.com/q/4806911
has body: So, I have been working in some problems that require that the code organize a string in alphabetical order, so my first thoughts were to try using char comparisons. If charA &lt; charB and all that, but couldn't make it. But I guess I don't really know how the char comparison Works. Need a simple explanation on how they work. Thank you!
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50918658
has comment: http://stackoverflow.com/comment/88837254
has title: Python Char Comparisons
has comment: http://stackoverflow.com/comment/88837261
downvote count: 1
type: Question
score: -1
possible better answer: http://stackoverflow.com/a/50918685
answer count: 2
tagged with: char
has answer: http://stackoverflow.com/a/50918658
has answer: http://stackoverflow.com/a/50918685

http://stackoverflow.com/comment/88750812
comment on: http://stackoverflow.com/a/50874079
type: Comment
score: 1
has text: You fail to understand the OP and you fail to understand the comments too!
type: AnswerComment

http://stackoverflow.com/a/50932574
has body: If your categories are exclusive you probably should take a look at Softmax Regression: Softmax regression (or multinomial logistic regression) is a generalization of logistic regression to the case where we want to handle multiple classes. In logistic regression we assumed that the labels were binary: y(i)∈{0,1}. We used such a classifier to distinguish between two kinds of hand-written digits. Softmax regression allows us to handle y(i)∈{1,…,K} where K is the number of classes.
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/50932489
downvote count: 0
type: Answer

http://stackoverflow.com/a/50915693
accepted answer of: http://stackoverflow.com/q/50915665
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/50915665
has body: Use .attrs['value'] Ex: from bs4 import BeautifulSoup s = """&lt;form id="__AjaxAntiForgeryForm" action="#" method="post"&gt; &lt;input name="__RequestVerificationToken" type="hidden" value="LOUesP09TLS3suKJk4dF5hIxeo-LmDWLxX8xqwIHYnj-JqR29qDcGA_mtHXvyZIej83qG3FfBBs2nuzk1EY6onTuszY1"&gt; &lt;/form&gt;""" soup = BeautifulSoup(s, "html.parser") form = soup.find("form", {"id": "__AjaxAntiForgeryForm"}) print( form.input.attrs['value'] ) Output: LOUesP09TLS3suKJk4dF5hIxeo-LmDWLxX8xqwIHYnj-JqR29qDcGA_mtHXvyZIej83qG3FfBBs2nuzk1EY6onTuszY1
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91146834
type: AcceptedAnswer

http://stackoverflow.com/comment/88742549
comment on: http://stackoverflow.com/a/50862026
type: Comment
has text: Yes it’s not the most efficient way.
score: 0
type: AnswerComment

http://stackoverflow.com/q/50917168
has comment: http://stackoverflow.com/comment/88834577
answer count: 0
has comment: http://stackoverflow.com/comment/88834597
has title: Unicode Encode Error with greek letters when writing to a file
type: Question
has comment: http://stackoverflow.com/comment/88834707
has comment: http://stackoverflow.com/comment/88834568
score: 0
has comment: http://stackoverflow.com/comment/88834380
has comment: http://stackoverflow.com/comment/88834664
has body: I am developing a customer application with Tkinter for GUI and inputs are all in Greek. I've made the program to write the inputs directly to a txt file, but when I fill the gaps with info about a customer in Greek and I click the button to save them, python gives me UnicodeEncodeError...only with Greek letters. When I fill the gaps with latin characters all are fine, but I need Greek letters. How can I solve this? with open(saved + '.txt' , 'w') as file_open: file_open.write(saved_3 +' '+'PNC:'+saved_5+'\n') file_open.write(saved_1 +'\n') file_open.write(saved_2 +'\n') file_open.write(saved_3 +'\n') file_open.write(saved_4 +'\n') file_open.write(saved_6) messagebox.showinfo('', 'ΕΠΙΤΥΧΗΣ ΑΠΟΘΗΚΕΥΣΗ ΣΤΟΙΧΕΙΩΝ')
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/89002823
score: 2
comment on: http://stackoverflow.com/a/51004387
type: AnswerComment
has text: i made this but the error is the same
type: Comment

http://stackoverflow.com/q/50915906
accepted answer: http://stackoverflow.com/a/50916045
duplicate of: http://stackoverflow.com/q/31715287
has comment: http://stackoverflow.com/comment/111521572
type: Question
has title: Pandas dataframe `apply` to `dtype` generates unexpected results
tagged with: dataframe
score: 4
upvote count: 4
answer count: 2
tagged with: pandas
downvote count: 0
has comment: http://stackoverflow.com/comment/111694817
has answer: http://stackoverflow.com/a/50918189
favorite count: 0
has comment: http://stackoverflow.com/comment/111685725
linked to: http://stackoverflow.com/q/34917404
has answer: http://stackoverflow.com/a/50916045
linked to: http://stackoverflow.com/q/31715287
tagged with: python
possible better answer: http://stackoverflow.com/a/50918189
type: AnsweredQuestion
has body: Example Toy dataframe: &gt;&gt;&gt; df = pd.DataFrame({'a': ['the', 'this'], 'b': [5, 2.3], 'c': [8, 11], 'd': ['the', 7]}) yields: &gt;&gt;&gt; df a b c d 0 the 5.0 8 the 1 this 2.3 11 7 and: &gt;&gt;&gt; df.dtypes a object b float64 c int64 d object dtype: object Problem Statement But what I really want to do is perform df.apply so that I can perform some actions on values in a column if that column/series is a string type. So I thought I could simply do something like: &gt;&gt;&gt; df.apply(lambda x: if x.dtype == 'object' and &lt;the other check I care about&gt;) But it didn't work as I'd expected, everything was an object. To verify, try: &gt;&gt;&gt; df.apply(lambda x: x.dtype == 'object') a True b True c True d True dtype: bool Trying to understand what was going on, I tried the following: &gt;&gt;&gt; def tmp_fn(val, typ): ... if val.dtype == typ: ... print(type(val)) ... print(val.dtype) and then &gt;&gt;&gt; df.apply(lambda x: tmp_fn(x, 'object')) &lt;class 'pandas.core.series.Series'&gt; object &lt;class 'pandas.core.series.Series'&gt; object &lt;class 'pandas.core.series.Series'&gt; object &lt;class 'pandas.core.series.Series'&gt; object a None b None c None d None dtype: object Attempts at Understanding Now I knew what was happening: the pandas series was being interpreted as just that, a series. Seemed easy to solve. But, in fact, it wasn't working as a series normally works in other cases. For instance, if I try: &gt;&gt;&gt; df.a.dtype dtype('O') &gt;&gt;&gt; df.b.dtype dtype('float64') Those both work as I expected and give me the type of object inside the series, instead of the simple fact that it is a series. But try as I might, I couldn't figure out a way to replicate that same sort of behavior within pandas.DataFrame.apply. What's going on here? How can I get the series to act as it normally would? In other words, how can I get a pandas.DataFrame.apply to work exactly as a pandas.Series would? I never knew/realized they weren't acting identicall…

http://stackoverflow.com/comment/88842800
has text: Are you trying to find the intersection of two lists? Please don't do it like this.
type: Comment
comment on: http://stackoverflow.com/q/50921718
score: 0
type: QuestionComment

http://stackoverflow.com/comment/88730714
type: AnswerComment
score: 0
type: Comment
has text: @MehulBhatia How do you want your position to change? Create a new question by providing a [mcve] and I could help you.
comment on: http://stackoverflow.com/a/50862394

http://stackoverflow.com/a/50873580
accepted answer of: http://stackoverflow.com/q/50873319
type: AcceptedAnswer
upvote count: 3
has comment: http://stackoverflow.com/comment/88748831
has comment: http://stackoverflow.com/comment/88748989
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/88748711
has body: You could use some heuristic to sort the contours. The following example uses the minimum x coordinate of each contour to sort them: import cv2 import numpy as np img = cv2.imread('BB7eu.png') img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) _, contours, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) contours.sort(key=lambda c: np.min(c[:,:,0])) for i in range(len(contours)): cur = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) cv2.drawContours(cur, contours, i, (0,0,255), -1) cv2.putText(cur, "i=%d" % i, (140,90), cv2.FONT_HERSHEY_PLAIN, 1, (0,255,255), 1) cv2.imshow("img", cur) cv2.waitKey() You'll see that the contours are highlighted "in order": B,e,r.
answers question: http://stackoverflow.com/q/50873319
score: 3

http://stackoverflow.com/comment/88733630
comment on: http://stackoverflow.com/q/50865463
has text: If it meets your needs `np.repeat` is efficient. Otherwise try `np.tile`. `as_strided` can be more efficient, but it doesn't actually make copies. `np.repeat(test[None], 10,0)`
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/comment/88850648
type: Comment
has text: please don't use `22/7`, it's a really bad approximation for `pi`, at least with writing `3.142` explicitly he knows his error range. plus he already did `import math`, he could actually use `math.pi`
score: 0
comment on: http://stackoverflow.com/a/50925739
type: AnswerComment

http://stackoverflow.com/q/50858129
has comment: http://stackoverflow.com/comment/88719719
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/39011511
upvote count: 1
accepted answer: http://stackoverflow.com/a/50858608
type: Question
score: 1
has comment: http://stackoverflow.com/comment/88719697
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/50858501
favorite count: 0
has body: reproducible code for data: import pandas as pd dict = {"a": "[1,2,3,4]", "b": "[1,2,3,4]"} dict = pd.DataFrame(list(dict.items())) dict 0 1 0 a [1,2,3,4] 1 b [1,2,3,4] I wanted to split/delimit "column 1" and create individual rows for each split values. expected output: 0 1 0 a 1 1 a 2 2 a 3 3 a 4 4 b 1 5 b 2 6 b 3 7 b 4 Should I be removing the brackets first and then split the values? I really don't get any idea of doing this. Any reference that would help me solve this please?
has answer: http://stackoverflow.com/a/50858608
linked to: http://stackoverflow.com/q/17116814
tagged with: reshape
tagged with: python
possible better answer: http://stackoverflow.com/a/50858501
has title: delimit/split row values and form individual rows
tagged with: delimiter

http://stackoverflow.com/a/50883228
type: Answer
has comment: http://stackoverflow.com/comment/88769167
has comment: http://stackoverflow.com/comment/88800011
has comment: http://stackoverflow.com/comment/88800328
has comment: http://stackoverflow.com/comment/88800097
has comment: http://stackoverflow.com/comment/88800447
has comment: http://stackoverflow.com/comment/88769364
has comment: http://stackoverflow.com/comment/88800382
has comment: http://stackoverflow.com/comment/88800466
accepted answer of: http://stackoverflow.com/q/50882897
has comment: http://stackoverflow.com/comment/88772733
score: 0
answers question: http://stackoverflow.com/q/50882897
upvote count: 1
has comment: http://stackoverflow.com/comment/88783452
type: AcceptedAnswer
downvote count: 1
has comment: http://stackoverflow.com/comment/88800131
has body: This looks like a nearly perfect question for https://codereview.stackexchange.com, but I'll put my edits anyway. To note at start: avoid classes until you can try writing less junk/support/boilerplate code and more fun code recylce whatever python has to offer before making something new write at least a tiny test or an assert skip the rules above while learning Here is my edit of your code, hope you find some useful ideas/clues: # not needed #import math class Point: #FIXME: delete this and do some reading on class attributes # x = 0.0 # y = 0.0 def __init__(self, x, y): self.x = x self.y = y #FIXME: use __str__ method for this # def to_string(self): # return "{X: " + str(self.x) + ", Y: " + str(self.y) + "}" def distance(self, p): return ((self.x - p.x) ** 2 + (self.y - p.y) ** 2) ** .5 class Quadrilateral: # FIXME: same as in class Point # p1 = 0 # p2 = 0 # p3 = 0 # p4 = 0 # FIXED: you do not want anything undefined for constructor # def __init__(self, p1=Point(), p2=Point(), p3=Point(), p4=Point()): def __init__(self, p1, p2, p3, p4): # saving some typing self.points = [p1, p2, p3, p4] # self.p2 = p2 # self.p3 = p3 # self.p4 = p4 # print("Quadrilateral Constructor") # FIXME: please make some life easier # def to_string(self): # return "{P1: " + self.p1.ToString() + "}, " + "{P2: " + self.p2.ToString() + "}, " + \ # "{P3: " + self.p3.ToString() + "}," + "{P4: " + self.p4.ToString() + "}" def side(self, vertex_n): # TODO: elaborate some protection against wrong *vertex_n* a, b = self.points[vertex_n], self.points[vertex_n-1] return a.distance(b) @property def perimeter(self): return sum([self.side(i) for i in range(4)]) # any duplicated code is a sign of danger: somehtign is going wrong! #side1 = self.side_length(self.p1, self.p2) #side2 = self.side_length(self.p2, self.p3) #side3 = self.side_length(self.p3, self.p4) #side4 = self.side_length(self.p4, self.p1) #return side1 + side2 + side3 + side4 pts = [Point(x, y) for x, y in [(0,0), (1,0), (1,1), (0,1)]] asser…
has comment: http://stackoverflow.com/comment/88769186
has comment: http://stackoverflow.com/comment/88800170
has comment: http://stackoverflow.com/comment/88770223
has comment: http://stackoverflow.com/comment/88800343

http://stackoverflow.com/comment/88802489
has text: What does `for path in __path__` do?
type: Comment
comment on: http://stackoverflow.com/q/50901224
type: QuestionComment
score: 1

http://stackoverflow.com/q/50868970
tagged with: dictionary
upvote count: 11
has comment: http://stackoverflow.com/comment/88744661
has answer: http://stackoverflow.com/a/50869011
type: Question
type: AnsweredQuestion
has title: Python dictionary breaking the laws of python
accepted answer: http://stackoverflow.com/a/50869011
linked to: http://stackoverflow.com/q/44185741
has comment: http://stackoverflow.com/comment/111315219
downvote count: 4
duplicate of: http://stackoverflow.com/q/44185741
answer count: 1
score: 7
favorite count: 0
has body: When I do: &gt;&gt;&gt; d={True:'yes',1:'no',1.0:'maybe'} &gt;&gt;&gt; d I receive an output of: &gt;&gt;&gt; {True:'maybe'} It's not only that some of my keys are deleted but also the value it was holding changed. Why is True given priority over another bool keys?
has comment: http://stackoverflow.com/comment/88740029
tagged with: python

http://stackoverflow.com/q/50882063
type: Question
accepted answer: http://stackoverflow.com/a/50883100
has answer: http://stackoverflow.com/a/50882117
possible better answer: http://stackoverflow.com/a/50882117
answer count: 2
tagged with: brute-force
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/50883100
has comment: http://stackoverflow.com/comment/88766447
has body: I am trying to create a brute forcer. In my current version, I am just using selenium and finding web elements this way. This seems slow, maybe because it loads the whole website. (just a locally hosted panel). Anyone know a better way to do this, maybe without making an automated browser? For anyone wondering, i'm trying to find 2 elements, and there is no api etc, so I assume I can't do this by the requests lib in python.
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/88766492
type: AnsweredQuestion
has title: selenium alternative for python? Fastest way to access web elements
score: 1

http://stackoverflow.com/q/50920373
has answer: http://stackoverflow.com/a/50920445
favorite count: 0
upvote count: 2
tagged with: python
has title: How can I define a paramter in a function.
type: AnsweredQuestion
has body: I'm trying to make the function dice randomly roll from 1-6. But when I try to add the different numbers from the function, it says that one and two are undefined. I'm not sure to how solve this, and I'm pretty new at coding. import random def dice(name): name = random.randint(1,6) print name dice('one') dice('two') dicesum = float(one) + float(two) message = raw_input('guess the number. ') if dicesum == message: print "You guess right! You win!" if dicesum != message: print "You guess wrong! You lose!"
score: 1
downvote count: 1
has answer: http://stackoverflow.com/a/50920416
type: Question
has answer: http://stackoverflow.com/a/50920404
tagged with: python-2.7
answer count: 3
possible better answer: http://stackoverflow.com/a/50920445
accepted answer: http://stackoverflow.com/a/50920416

http://stackoverflow.com/comment/88716525
comment on: http://stackoverflow.com/q/50856325
score: 0
type: Comment
type: QuestionComment
has text: So something like `subprocess.Popen( ['my_cover.py', '-s', str(site_name), '-t', str(turbine_name), '-c', str(country_name)` ? I am not totally sure how `content%args.__dict__` works i used it from some example

http://stackoverflow.com/comment/88982489
type: Comment
type: QuestionComment
has text: More importantly (because that last question probably won't turn out to help…), please edit the information about platform, etc., into your question, rather than just putting it in a comment. And also, just to make sure: when you do the "select environment" thing, I assume VSCode properly labels it as something like "Python 3.6 (64-bit) Python Software Foundation", not just the label it uses when it's confused about the interpreter version, right?
score: 2
comment on: http://stackoverflow.com/q/50993566

http://stackoverflow.com/comment/89661705
comment on: http://stackoverflow.com/a/51011993
score: 0
type: AnswerComment
type: Comment
has text: AppEngine documentation: 10 minutes writing the code, 3 hours setting configurations... For the backend-auth example, you need to install both "requests" and "google-auth". Like every external lib (yes, google-auth is external), you should pip-install them to `lib/` (some people use `libs/`). Best way is to have a `requirements.txt` file with each lib in a new line ("requests", "google-auth") and then call `mkdir lib`, `pip install -t lib/ -r requirements.txt`.

google-oauth
type: Tag
tags question: http://stackoverflow.com/q/50948314
tags question: http://stackoverflow.com/q/50959061
tags question: http://stackoverflow.com/q/50865584
tags question: http://stackoverflow.com/q/50978109
tag name: google-oauth
tags question: http://stackoverflow.com/q/50913206
tags question: http://stackoverflow.com/q/50987584

http://stackoverflow.com/a/50954737
downvote count: 0
upvote count: 2
type: Answer
score: 2
has body: One way to do it, with df.apply(): def choose_orig(row): if row['Column_1'] == 'Position': return row['Original_1'] elif row['Column_2'] == 'Position': return row['Original_2'] elif row['Column_3'] == 'Position': return row['Original_3'] return '' df['Original_Values'] = df.apply(choose_orig, axis=1) The axis=1 argument to df.apply() causes the choose_orig() function to be called once for each row of the dataframe. Note that this uses a default value of the empty string, '', when none of the columns match the word 'Position'.
answers question: http://stackoverflow.com/q/50954560

http://stackoverflow.com/q/50879147
has body: I am grouping by two columns in a Pandas DataFrame, after which I count the size of each group. This grouped DataFrame will then be filtered and the data plotted in a bar chart. The issue i am having is that if a group has a zero count, it is not shown in the DataFrame and therefore does not appear on the plot. So the plot has missing categories on the x-axis when i would rather them include a category even if there is no bar to display (i.e represent the category as zero, thereby imo making the plot more representative of the data as a whole). # Import the required packages. import numpy as np import pandas as pd import matplotlib.pyplot as plt # Set the appearance of plots. plt.style.use('ggplot') # Create sample DataFrame. data = {'ID':[1, 2, 3, 4, 5, 6, 7], 'Name':['Tom', 'Jack', 'Anne', 'Steve', 'Ricky', 'Jane', 'Beth'], 'Age':[28,34,29,42,15,10,26], 'Voted':[0, 1, 0, 1, 1, 0, 0]} df = pd.DataFrame(data) # Bin into age groups and create an Age Group column in the DataFrame. bins = list(range(0, 60, 10)) df['Age Group'] = pd.cut(df['Age'], bins, right=False) # Group data by Age Group and Voted columns. Then perform count using the ID column. Make Age Group the new index. groups = df.groupby(['Age Group', 'Voted']) new_df = groups.agg({'ID': 'count'}).rename(columns={'ID':'Count'}) new_df.reset_index(inplace=True) new_df.set_index('Age Group', inplace=True) new_df The code above will output this: Voted ID Age Group [10, 20) 0 1 [10, 20) 1 1 [20, 30) 0 3 [30, 40) 1 1 [40, 50) 1 1 What I'd like is for something like the result below, from which i can filter out just the voted=1 age groups and plot in a chart: Voted ID Age Group [0, 10) 0 0 [0, 10) 1 0 [10, 20) 0 1 [10, 20) 1 1 [20, 30) 0 3 [20, 30) 1 0 [30, 40) 0 0 [30, 40) 1 1 [40, 50) 0 0 [40, 50) 1 1 I have searched the similar questions/results (most relative below), but i can't seem to get either to work. [Pandas groupby for zero values [Pandas Groupby How to Show Zero Counts in DataFrame I've also noticed tha…
tagged with: count
has answer: http://stackoverflow.com/a/50879306
tagged with: python
linked to: http://stackoverflow.com/q/47372181
accepted answer: http://stackoverflow.com/a/50879306
has title: Count following groupby on two columns in Pandas doesn't include groups with a zero count
type: AnsweredQuestion
downvote count: 0
score: 1
linked to: http://stackoverflow.com/q/37003100
type: Question
tagged with: dataframe
tagged with: pandas-groupby
tagged with: pandas
upvote count: 1
answer count: 1
favorite count: 0

http://stackoverflow.com/a/50969708
accepted answer of: http://stackoverflow.com/q/50968717
has comment: http://stackoverflow.com/comment/88935831
answers question: http://stackoverflow.com/q/50968717
score: 3
has comment: http://stackoverflow.com/comment/88935921
has comment: http://stackoverflow.com/comment/88937663
has comment: http://stackoverflow.com/comment/88937206
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88937587
upvote count: 3
has comment: http://stackoverflow.com/comment/88935820
type: Answer
has comment: http://stackoverflow.com/comment/88937120
has body: You should start by identifying the two things you're grouping by here. Ending letters and starting letters. Drop all the words into two dicts, keyed by each, and you'll end up with much faster lookups. list.index is a killer for efficiency, with each lookup costing O(n) from collections import defaultdict startswith, endswith = defaultdict(list), defaultdict(list) wordlist = ['apple','elephant','tower','rank'] for word in wordlist: startswith[word[0]].append(word) endswith[word[-1]].append(word) Then it should be a fairly simple graph traversal problem.
has comment: http://stackoverflow.com/comment/88936384
downvote count: 0

http://stackoverflow.com/q/50891451
score: 1
tagged with: error-handling
type: Question
has title: Hii, How do I run a command everytime I get an: "The process "XXX.exe" not found" error?
upvote count: 1
downvote count: 0
has body: Basically this is my code, which is supposed to block a software of choice. : import os import time import easygui import subprocess def main(): seconds = int(easygui.integerbox()) file = get_file() close_file(file, seconds) def get_file(): file_name = easygui.filesavebox() return file_name def close_file(file, seconds): if os.path.exists(file): while (seconds != 0): exe_name = file.split("\\") try: subprocess.Popen('taskkill /f /im {}'.format(exe_name[-1])) except: print('Program not open') time.sleep(1) print(seconds) seconds = seconds - 1 print('You can now use the program.') if __name__ == '__main__': main() Every time I run it and not the software is not open I get this repeatedly "Error: The process "blablabla.exe" not found. So basically how can I run a command in case I get such an error?
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
answer count: 0

http://stackoverflow.com/comment/88841152
type: QuestionComment
has text: No time to test this, but maybe try using `.pivot_table()` to get your data into a shape with a series (column) per group, then use `.fillna(method = 'ffill')` to propagate the values forward, the use `shift()`.
comment on: http://stackoverflow.com/q/50920760
score: 1
type: Comment

http://stackoverflow.com/q/50877963
has comment: http://stackoverflow.com/comment/88760334
has title: python - best way to compare objects property by specific other property
has comment: http://stackoverflow.com/comment/88758123
score: 0
tagged with: python
answer count: 0
type: UnansweredQuestion
tagged with: django
type: Question
tagged with: testing
has comment: http://stackoverflow.com/comment/88758058
has body: I'm using python 3.5.3 I have the following State class: class State(BaseModel): title = models.CharField(max_length=100, blank=True, null=True) name = models.CharField(max_length=100, blank=True, null=True) machine = models.ForeignKey(machine, related_name='states') data = JSONField(blank=True, null=True) I'm trying to get all states that point to specific two machines and verify that the 'data' property is the same where the 'name' is the same. This is how I done it: new_machine_states = State.objects.filter(machine_id=new_created_ma_id) for new_state in new_machine_states: existing_machine_state = State.objects.filter(machine_id=existing_ma.id, name=new_state.name) self.assertEqual(new_state.data, existing_machine_state[0].data) But I guess there's a better cleaner way to do that. Any idea?
tagged with: comparison

http://stackoverflow.com/a/50977226
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/50977130
upvote count: 1
has body: You are looking at intermediate print results. You are modifying a single dictionary, and sharing references to it. You can see the intermediary steps, but that doesn't mean the result is different. Store a reference to the object returned from next() and they'll all be the same: g = generator({'a': None}) first = next(g) second = next(g) third = next(g) print(first, second, third) # -&gt; {'a': 2} {'a': 2} {'a': 2} first, second and third are all references to the same object: &gt;&gt;&gt; first is second and second is third True You'd see the same thing if you did this in a regular for loop: &gt;&gt;&gt; results = [] &gt;&gt;&gt; d = {'a': None} &gt;&gt;&gt; for i in range(3): ... d['a'] = i ... print(d) ... results.append(d) ... {'a': 0} {'a': 1} {'a': 2} &gt;&gt;&gt; print(results) [{'a': 2}, {'a': 2}, {'a': 2}] &gt;&gt;&gt; all(d is elem for elem in results) # all references in results are the same object True The loop prints the dictionary object as it changes each step. The results list contains 3 references to the same object, and each shows the same state once printed at the end.

http://stackoverflow.com/comment/97832460
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/55566485
has text: This would be better suited as a comment, which you will be able to make when you reach 50 reputation. Your contribution in attempting to answer the question is appreciated but please reserve the answer section for concrete solutions.

http://stackoverflow.com/q/51010480
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89020683
has comment: http://stackoverflow.com/comment/89013746
tagged with: python
type: AnsweredQuestion
has body: I have a string: [{"leagueId":"37085320-2d31-11e8-802e-c81f66dacb22","leagueName":"Akali's Highwaymen","tier":"BRONZE","queueType":"RANKED_FLEX_SR","rank":"III","playerOrTeamId":"87747329","playerOrTeamName":"REYKKU","leaguePoints":0,"wins":53,"losses":59,"veteran":true,"inactive":false,"freshBlood":false,"hotStreak":false},{"leagueId":"c64de250-0065-11e8-b792-c81f66dd2a8f","leagueName":"Fiora's Horde","tier":"BRONZE","queueType":"RANKED_SOLO_5x5","rank":"IV","playerOrTeamId":"87747329","playerOrTeamName":"REYKKU","leaguePoints":28,"wins":29,"losses":25,"veteran":false,"inactive":false,"freshBlood":false,"hotStreak":false}] How do I turn this string into ONE array with dictionary and arrays inside it? I have tried ast.literal_eval() but that only seems to work when it is ONLY a dictionary
type: Question
has answer: http://stackoverflow.com/a/51010497
has title: Converting string into array containing dictionary
accepted answer: http://stackoverflow.com/a/51010497

http://stackoverflow.com/comment/88772830
comment on: http://stackoverflow.com/q/50885254
has text: It will be good if you can post a sample for `x` for other users to work on.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89002693
has text: If you get a memory error, that isn't a minimal example.
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51002825
type: Comment

http://stackoverflow.com/comment/88908793
type: QuestionComment
comment on: http://stackoverflow.com/q/50955355
score: 0
has text: Have you tried the [sortedcollections](https://pypi.org/project/sortedcollections/) or [sortedcontainers](http://www.grantjenks.com/docs/sortedcontainers/) module? It is installed by default in the Anaconda distribution of Python and is easy to get otherwise. It does not have a tree--it has data structures that use less memory than a tree, since the child pointers are removed, and do most of the operations of a tree in a good time. This may or may not meet your needs.
type: Comment

http://stackoverflow.com/comment/88918197
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50930464
score: 0
has text: I think you want to spawn multiple copies of the same sprite similarly to this question: https://stackoverflow.com/questions/10389487/spawning-multiple-of-the-same-sprite and in this intro guide: http://programarcadegames.com/index.php?chapter=introduction_to_sprites

http://stackoverflow.com/q/50862705
favorite count: 0
linked to: http://stackoverflow.com/q/12704305
tagged with: sql-server
linked to: http://stackoverflow.com/q/10865483
upvote count: 1
has comment: http://stackoverflow.com/comment/88728161
linked to: http://stackoverflow.com/q/43504474
has answer: http://stackoverflow.com/a/71487600
type: UnansweredQuestion
has body: this seems like a basic function, but I'm new to Python so maybe I'm not googling this correctly. In Microsoft SQL Server, when you have a statement like SELECT top 100 * FROM dbo.Patient_eligibility you get a result like Patient_ID | Patient_Name | Patient_Eligibility 67456 | Smith, John | Eligible ... etc. Etc. I am running a connection to SQL through Python as such, and would like the output to look exactly the same as in SQL. Specifically - with column names and all the data rows specified in the SQL query. It doesn't have to appear in the console or the log, I just need a way to access it to see what's in it. Here is my current code attempts: import pyodbc conn = pyodbc.connect(connstr) cursor = conn.cursor() sql = "SELECT top 100 * FROM [dbo].[PATIENT_ELIGIBILITY]" cursor.execute(sql) data = cursor.fetchall() #Query1 for row in data : print (row[1]) #Query2 print (data) #Query3 data My understanding is that somehow the results of PATIENT_ELIGIBILITY are stored in the variable data. Query 1, 2, and 3 represent methods of accessing that data that I've googled for - again seems like basic stuff. The results of #Query1 give me the list of the first column, without a column name in the console. In the variable explorer, 'data' appears as type List. When I open it up, it just says 'Row object of pyodbc module' 100 times, one for each row. Not what I'm looking for. Again, I'm looking for the same kind of view output I would get if I ran it in Microsoft SQL Server. Running #Query2 gets me a little closer to this end. The results appear like a .csv file - unreadable, but it's all there, in the console. Running #Query3, just the 'data' variable, gets me the closest result but with no column names. How can I bring in the column names? More directly, how do i get 'data' to appear as a clean table with column names somewhere? Since this appears a basic SQL function, could you direct me to a SQL-friendly library to use instead? Also note that neither of the Queries required…
tagged with: python
tagged with: pyodbc
score: 1
has comment: http://stackoverflow.com/comment/88727931
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/50863550
downvote count: 0
has title: In Python, display output of SQL query as a table, just like it does in SQL

http://stackoverflow.com/comment/88773195
type: Comment
type: QuestionComment
has text: @sc241 please show us what the data in your file looks like. Sounds like you are reading in strings without converting to numerical type.
comment on: http://stackoverflow.com/q/50885583
score: 0

http://stackoverflow.com/q/50960451
has comment: http://stackoverflow.com/comment/88918009
tagged with: python
score: 2
type: AnsweredQuestion
upvote count: 2
type: Question
tagged with: recursion
has body: I have this kind of list: [['I'],['want','love','like'],['cat',dog]] and I want to create a function that can return all combinations of words in the lists like this: [['I'],['want'],['cat']] [['I'],['love'],['cat']] [['I'],['like'],['cat']] [['I'],['want'],['dog']] [['I'],['love'],['dog']] [['I'],['like'],['dog']] PS: The function must work with any n words
has answer: http://stackoverflow.com/a/50960520
linked to: http://stackoverflow.com/q/533905
tagged with: for-loop
accepted answer: http://stackoverflow.com/a/50960520
duplicate of: http://stackoverflow.com/q/533905
downvote count: 0
answer count: 1
favorite count: 0
has title: How to create function that returns all combinations of this list in Python?
linked to: http://stackoverflow.com/q/464864

http://stackoverflow.com/q/50892465
score: -3
has answer: http://stackoverflow.com/a/50892494
type: Question
answer count: 2
has body: I have column A in DF data frame. Current;y, it looks like this: A 1 [32000, 56000, 12000] 2 [32000, 12000] 3 [] 4 [25] . . Some cells are empty list. I want to extract values as integer or float for each row and sum the total value. I attempted doing this and got the message below: [[float(i) for i in k] for k in DF['A'] ] ValueError: could not convert string to float: What I want: A 1 100000 2 44000 3 0 and so on. I am posting some results based on the suggestions: import ast DF.A.apply(ast.literal_eval) (ValueError: malformed node or string: []) DF.A.head().to_dict() returns: {0: [], 1: ['32000', '56000', '12000'], 2: [], 3: [], 4: ['2000', '1500', '1000', '10', '1000']} Note: I created dataframe from customer narratives. I tried to clean punctuations and irrelevant characters. A narrative goes like below for each row. " XYZ foo bar foo XYZ { $130 } XYX bar foo { $260 }" or "XYZ bar foo" (no dollars mentioned in this one). All of these are rows I created a new column to represent the dollar value mentioned. I reduced the narrative to number-only as explained above. Also, if I can extract the sum of total dollar value mentioned for each row's narrative without going through cleaning the narrative (to avoid potential problems), that would work too. I tried to do some regex on the raw narrative but failed to extract the amounts indicated in between {$ }--this is how dollar value represented in each row narrative.
upvote count: 0
tagged with: string
has title: Extracting strings of a list in pandas column as integer or float
tagged with: pandas
tagged with: python
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88785782
downvote count: 3
has answer: http://stackoverflow.com/a/50892501

http://stackoverflow.com/q/50909084
has title: Extract all tables from web page in python
tagged with: pandas
answer count: 1
has answer: http://stackoverflow.com/a/50909144
favorite count: 0
tagged with: python
type: AnsweredQuestion
score: 1
downvote count: 3
accepted answer: http://stackoverflow.com/a/50909144
tagged with: web-scraping
type: Question
upvote count: 4
has body: I want to get all the tables from web page in python, but my code is showing only one of table not all. Please help. Thanks in advance. import pandas as pd import requests from bs4 import BeautifulSoup from tabulate import tabulate res = requests.get("http://www.findchips.com/search/PCB") soup = BeautifulSoup(res.content,'lxml') table = soup.find_all('table')[0] df = pd.read_html(str(table)) print( tabulate(df[0], headers='keys', tablefmt='psql') )
has comment: http://stackoverflow.com/comment/88818948

http://stackoverflow.com/q/50908676
favorite count: 0
tagged with: python
has title: Python: How to create multi line cells in excel when exporting a pandas dataframe
upvote count: 11
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/15370432
has answer: http://stackoverflow.com/a/50908925
tagged with: excel
type: Question
possible better answer: http://stackoverflow.com/a/71909517
has body: I have the following pandas Dataframe df = pd.DataFrame([ 'First Line', 'Second line', 'First line', 'second line', 'third line', 'first line' ]) I am trying to export it into an Excel file. However I would like that between each list-element a line break is entered, similar to ALT-ENTER in Excel. So at the end, the excel would look like this: Thank you
accepted answer: http://stackoverflow.com/a/50908925
score: 11
has answer: http://stackoverflow.com/a/71909517
answer count: 3
has answer: http://stackoverflow.com/a/74447948
tagged with: pandas
downvote count: 0

http://stackoverflow.com/comment/88745333
score: 0
type: Comment
has text: edited to add `nargs`, now will accept `-p` without value
comment on: http://stackoverflow.com/a/50871450
type: AnswerComment

http://stackoverflow.com/comment/88904109
type: Comment
comment on: http://stackoverflow.com/a/50953207
score: 0
type: AnswerComment
has text: :) no worries thats fine with me as well

http://stackoverflow.com/comment/88786053
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50891417
type: Comment
has text: Because regardless of whether you use `-n20 -r1`, or `-n1 -r20`, or just had 1 option which just provided an option to define the number of times the function is run, say `-l20`, they are all just doing random sampling, and capturing sufficient number of samples to have high signal/noise ratio?

http://stackoverflow.com/q/50867030
score: 1
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/50867155
has comment: http://stackoverflow.com/comment/88736375
has comment: http://stackoverflow.com/comment/88736295
downvote count: 0
has comment: http://stackoverflow.com/comment/88736315
has title: Downsample sublists based on length of smallest sublist
favorite count: 0
has answer: http://stackoverflow.com/a/50867139
has answer: http://stackoverflow.com/a/50867091
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50867101
has body: I have a list of lists like the following, and the number and length of sublists can be variable: test = [[1, 5, 4, 3, 5, 2], [4, 2], [5, 2, 4, 3, 5], [5, 3, 1]] I want to downsample all sublists to the length of the shortest sublist - this case 2. That means I want to randomly select 2 elements from all sublists as an output. For a much larger list of around 100 sublists, each greater than 100000 items, what would the most efficient way be?
answer count: 4

http://stackoverflow.com/q/50888389
has comment: http://stackoverflow.com/comment/88790538
has title: error reading protobuf spec. validator error: The. mlmodel supplied is of version 3, intended for a newer version of xcode
has comment: http://stackoverflow.com/comment/88782307
has comment: http://stackoverflow.com/comment/88793798
type: UnansweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/88830428
tagged with: python
has comment: http://stackoverflow.com/comment/88812238
has body: I'm running this out-of-the-box turi python code: import turicreate as tc # Load the data data = tc.SFrame('annotations.sframe') # Make a train-test split train_data, test_data = data.random_split(0.8) # Create a model model = tc.object_detector.create(train_data, model="darknet-yolo", max_iterations=1, verbose=True) # Save predictions to an SArray predictions = model.predict(test_data) # Evaluate the model and save the results into a dictionary metrics = model.evaluate(test_data) # Save the model for later use in Turi Create model.save('mymodel.model') # Export for use in Core ML model.export_coreml('MyCustomObjectDetector.mlmodel') But on the last line I'm getting the error: model.export_coreml('MyCustomObjectDetector.mlmodel') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/Users/amir/anaconda/envs/CowsVision/lib/python2.7/site-packages/turicreate/toolkits/object_detector/object_detector.py", line 1477, in export_coreml mlmodel = coremltools.models.MLModel(model) File "/Users/amir/anaconda/envs/CowsVision/lib/python2.7/site-packages/coremltools/models/model.py", line 209, in __init__ self.__proxy__ = _get_proxy_from_spec(filename) File "/Users/amir/anaconda/envs/CowsVision/lib/python2.7/site-packages/coremltools/models/model.py", line 103, in _get_proxy_from_spec return _MLModelProxy(filename) RuntimeError: Error compiling model: "Error reading protobuf spec. validator error: The .mlmodel supplied is of version 3, intended for a newer version of Xcode. This version of Xcode supports model version 2 or earlier.". &gt;&gt;&gt; In the console. Does that mean that my local installed xcode version needs upgrade? Where is the .mlmodel version being determined? What's "this version of Xcode"?
tagged with: turi
type: Question
tagged with: coreml
has answer: http://stackoverflow.com/a/50939352
has comment: http://stackoverflow.com/comment/88820822
answer count: 1
has comment: http://stackoverflow.com/comment/88827638
has comment: http://stackoverflow.com/comment/88826112
tagged with: xcode

http://stackoverflow.com/a/50981933
type: Answer
accepted answer of: http://stackoverflow.com/q/50981060
answers question: http://stackoverflow.com/q/50981060
upvote count: 5
has body: Discord.py currently couldn't automatically register the commands from subclasses of Client that are decorated by @commands.command(). You can still however, manually add them in __init__ or anywhere that's going to be ran: class Bot(commands.AutoShardedBot): def __init__(self): super().__init__(command_prefix="~") self.add_command(commands.Command("test", self.test)) # or uglier: self.command()(self.test) async def test(self, ctx): await ctx.send("some random text") You can still use the decorator if you wanted to (I'd prefer this way since it's more simplistic): class Bot(commands.AutoShardedBot): def __init__(self): super().__init__(command_prefix="~") self.add_command(self.test) @commands.command() async def test(self, ctx): await ctx.send("some random text") If you're going to have lots of initial commands and lazy to call add_command for each of them, you can do the following: import inspect class Bot(commands.AutoShardedBot): def __init__(self): super().__init__(command_prefix="~") members = inspect.getmembers(self) for name, member in members: if isinstance(member, commands.Command): if member.parent is None: self.add_command(member) @commands.command() async def test(self, ctx): await ctx.send("some random text") @commands.command() async def test2(self, ctx): await ctx.send("some random text2") @commands.command() async def test3(self, ctx): await ctx.send("some random text3")
has comment: http://stackoverflow.com/comment/106210415
score: 5
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/88758143
comment on: http://stackoverflow.com/a/50877755
type: AnswerComment
has text: @antfuentes87 I have to disagree with that. Don't ever be afraid of importing standard library modules, especially `itertools`, `collections` and `functools`. It will save you a lot of repetition. `itertools` is even a zero-cost import since it's used by python on startup. What about tobias_k's answer then? `enumerate` is a built in function.
type: Comment
score: 0

http://stackoverflow.com/a/50982296
has comment: http://stackoverflow.com/comment/89039429
upvote count: 2
has comment: http://stackoverflow.com/comment/88988606
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50981960
has body: Use x-ticks: d = ({ 'A' : ['08:00:00','08:10:00'], 'B' : [1,2], }) df = pd.DataFrame(data=d) fig = plt.figure() x = df['A'] y = df['B'] x_numbers = list(pd.to_timedelta(df['A'], errors="coerce").dt.total_seconds ()) plt.scatter(x_numbers, y) plt.xticks(x_numbers, x) plt.show() This will plot the timestamps as the tick marks on the x-axis. Note that I converted the 'B' column in your dataframe to numbers instead of strings. If they really need to be strings or are imported as strings from a file, just convert them to numbers, e.g. via float() or int().
accepted answer of: http://stackoverflow.com/q/50981960
type: Answer
score: 2

http://stackoverflow.com/a/50960564
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50960537
type: Answer
accepted answer of: http://stackoverflow.com/q/50960537
upvote count: 4
has comment: http://stackoverflow.com/comment/88917947
downvote count: 0
has comment: http://stackoverflow.com/comment/88917977
has body: I do not think we need iterrows here. csv[~(csv['currentAge'].isnull())&amp;(csv['currentAge2'].isnull())]
score: 4

http://stackoverflow.com/comment/88834822
score: 1
comment on: http://stackoverflow.com/q/50917370
has text: What is that `run` function? Did you do `from subprocess import *`, or are you using one of the third-party shell wrapper libraries, or…?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50997565
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50988236
accepted answer of: http://stackoverflow.com/q/50988236
type: Answer
has body: There currently exists no way to do this in the library. HOWEVER, I found out that by aligning text in an existing document, then opening it with python-docx, you can simply edit the text and it will retain its formatting. from docx import document document = Document('template.docx') # This just grabs the first paragraph, code assumes you've already applied formatting. document.paragraphs[0].text = "Example Text" document.save('output.docx')
score: 0

relative-path
type: Tag
tag name: relative-path
tags question: http://stackoverflow.com/q/50881667

http://stackoverflow.com/q/50958722
type: Question
tagged with: python
has title: Tkinter polygon edge resolution
tagged with: tkinter
has comment: http://stackoverflow.com/comment/88914742
upvote count: 1
has body: I am attempting to draw some polygons using tkinter. That is relatively easy. The problem is that the edges of the polygon are fairly pixelized/low resolution. See the example in the picture: Is there a way to make the edges "smoother" (but not in the sense of using the "smoothing" option which ends up creating a circle). Hopefully I didn't miss something obvious. Thanks!
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88914901
tagged with: polygon
answer count: 0
downvote count: 0
score: 1
favorite count: 0

http://stackoverflow.com/a/51006472
upvote count: 2
has comment: http://stackoverflow.com/comment/89006318
has body: Use add(): df_1.add(df_2) Index Jan15 Feb15 0 0 13 9 With different column names: pd.DataFrame(df_1.values + df_2.values, columns = df_1.columns.str.replace("\d", "")).reset_index()
answers question: http://stackoverflow.com/q/51006409
has comment: http://stackoverflow.com/comment/89006245
accepted answer of: http://stackoverflow.com/q/51006409
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89006319
type: Answer
has comment: http://stackoverflow.com/comment/89006248
score: 2
has comment: http://stackoverflow.com/comment/89006238

string
tags question: http://stackoverflow.com/q/51004248
tags question: http://stackoverflow.com/q/50979496
tags question: http://stackoverflow.com/q/50916377
tags question: http://stackoverflow.com/q/50941409
tags question: http://stackoverflow.com/q/50892962
tags question: http://stackoverflow.com/q/50901077
tags question: http://stackoverflow.com/q/50877776
tags question: http://stackoverflow.com/q/50918637
tags question: http://stackoverflow.com/q/50942291
tags question: http://stackoverflow.com/q/50900491
tags question: http://stackoverflow.com/q/50900813
tags question: http://stackoverflow.com/q/50970923
tags question: http://stackoverflow.com/q/50894532
tags question: http://stackoverflow.com/q/50904474
tags question: http://stackoverflow.com/q/50946014
tags question: http://stackoverflow.com/q/50925382
tags question: http://stackoverflow.com/q/50866477
tags question: http://stackoverflow.com/q/50924265
tags question: http://stackoverflow.com/q/50914776
tags question: http://stackoverflow.com/q/50996642
tags question: http://stackoverflow.com/q/50940956
tags question: http://stackoverflow.com/q/50857000
tags question: http://stackoverflow.com/q/50896837
tags question: http://stackoverflow.com/q/51000035
tags question: http://stackoverflow.com/q/51003389
tags question: http://stackoverflow.com/q/50874061
tags question: http://stackoverflow.com/q/50868209
tags question: http://stackoverflow.com/q/50882377
tags question: http://stackoverflow.com/q/50879291
tags question: http://stackoverflow.com/q/50907696
tags question: http://stackoverflow.com/q/50933912
tags question: http://stackoverflow.com/q/50998417
tags question: http://stackoverflow.com/q/50992066
tags question: http://stackoverflow.com/q/50876926
tags question: http://stackoverflow.com/q/50971208
tags question: http://stackoverflow.com/q/50882246
tag name: string
tags question: http://stackoverflow.com/q/50955687
tags question: http://stackoverflow.com/q/50940421
tags question: http://stackoverflow.com/q/50975022
tags question: http://stackoverflow.com/q/50878193
tags question: http://stackoverflow.com/q/50891485
tags question: http://stackoverflow.com/q/50876776
tags question: http://stackoverflow.com/q/50856366
type: Tag
tags question: http://stackoverflow.com/q/50995942
tags question: http://stackoverflow.com/q/50942814
tags question: http://stackoverflow.com/q/50861237
tags question: http://stackoverflow.com/q/50901552
tags question: http://stackoverflow.com/q/50962731
tags question: http://stackoverflow.com/q/51002266
tags question: http://stackoverflow.com/q/51003118
tags question: http://stackoverflow.com/q/51002355
tags question: http://stackoverflow.com/q/50986420
tags question: http://stackoverflow.com/q/50856781
tags question: http://stackoverflow.com/q/50991123
tags question: http://stackoverflow.com/q/50901326
tags question: http://stackoverflow.com/q/51010380
tags question: http://stackoverflow.com/q/50898184
tags question: http://stackoverflow.com/q/50875037
tags question: http://stackoverflow.com/q/50915424
tags question: http://stackoverflow.com/q/50982397
tags question: http://stackoverflow.com/q/50985232
tags question: http://stackoverflow.com/q/50933895
tags question: http://stackoverflow.com/q/50953981
tags question: http://stackoverflow.com/q/50932804
tags question: http://stackoverflow.com/q/50883259
tags question: http://stackoverflow.com/q/50957015
tags question: http://stackoverflow.com/q/50914658
tags question: http://stackoverflow.com/q/50874871
tags question: http://stackoverflow.com/q/50877171
tags question: http://stackoverflow.com/q/50879786
tags question: http://stackoverflow.com/q/50870524
tags question: http://stackoverflow.com/q/50990854
tags question: http://stackoverflow.com/q/50948490
tags question: http://stackoverflow.com/q/50892465
tags question: http://stackoverflow.com/q/50951893
tags question: http://stackoverflow.com/q/50999282

http://stackoverflow.com/a/50937667
has comment: http://stackoverflow.com/comment/88873766
score: 0
has body: Just use readline() to read a line, and make a while loop def line_after(): with open("/file_path/filename", "r", encoding="utf-8") as f: while true: if "this one" in f.readline(): a, b = f.readline().split() return int(a), int(b) return None
type: Answer
answers question: http://stackoverflow.com/q/50937567
has comment: http://stackoverflow.com/comment/88873854

http://stackoverflow.com/comment/88853499
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50926580
has text: There's a nice example of validation [here](https://stackoverflow.com/a/4140988/4014959). Apart from the problems previously mentioned, your `validate_entry` is problematic: unless the user pastes 'APPLE' into the widget nothing will pass validation.
score: 0

http://stackoverflow.com/a/50932266
type: Answer
has body: Here are a few tweaks to get your program working as intended: import csv import os FirstName = input("Enter your first name: ") Surname = input("Enter your surname: ") Age = input("Enter your age: ") YearGroup = input("Enter your year group: ") userName = input("Create a unique username: ") passWord = input("Create a password: ") fieldnames = ['Username', 'Surname', 'First Name', 'Age', 'YearGroup', 'passWord'] filename = 'StudentUserName.csv' # The file is now opened in append mode instead of write mode. with open(filename, 'a', newline='\n') as csvUser: # reG is now a dictionary, as required by writerow. reG = {'Username': userName, 'Surname': Surname, 'First Name': FirstName, 'Age': Age, 'YearGroup': YearGroup, 'passWord': passWord} writer = csv.DictWriter(csvUser, fieldnames=fieldnames) # if it's an empty file, write the header if os.stat(filename).st_size == 0: writer.writeheader() writer.writerow(reG) # writer.writerow("\r") # writer.writerow({userName, Surname, FirstName, # Age, YearGroup, passWord}) csvUser.close() print ("Registration completed") The file is now opened in append mode instead of write mode. reG is now a dictionary, as required by writerow. The header is only added if the file is empty.
answers question: http://stackoverflow.com/q/50932096
score: 0

http://stackoverflow.com/a/76136553
has body: I had this happen when I moved from TeX Live 2022 to TeX Live 2023, with very similar rc settings for my Matplotlib figures. The error said missing font metrics file: cmss10. It is thrown by the dviread.py module in the snippet ... if tfm is None: raise FileNotFoundError("missing font metrics file: %s" % fontname) ... The following two steps worked to fix it for me: According to this doc page, I performed the following two troubleshooting actions: Try deleting your .matplotlib/tex.cache directory. If you don’t know where to find .matplotlib, see matplotlib configuration and cache directory locations. Make sure LaTeX, dvipng and ghostscript are each working and on your PATH. This then threw other errors, but since I hadn't restarted PyCharm since my installation of TeX Live 2023 (and deletion of TeX Live 2022), I gave that a shot too. Worked like a charm.
score: 0
answers question: http://stackoverflow.com/q/50875637
type: Answer

http://stackoverflow.com/comment/88991816
score: 0
has text: Uncomment both `append`s. Replace the second `break` with `return mylist`.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50998880

http://stackoverflow.com/q/50874626
score: 0
answer count: 2
has body: I want to use tesseract-ocr on AWS EC2 machine using python. I have install tesseract-ocr, pytesseract and set TESSDATA_PREFIX=/usr/local/share/tessdata... but still geting below error while calling image_to_string method of pytesseract. pytesseract.pytesseract.TesseractNotFoundError: tesseract not installed or it's not in your path
type: UnansweredQuestion
tagged with: amazon-ec2
has answer: http://stackoverflow.com/a/50874671
tagged with: amazon-web-services
type: Question
has title: AWS EC2 machine giving "pytesseract.pytesseract.TesseractNotFoundError: tesseract not installed or it's not in your path"
tagged with: python
tagged with: ocr
tagged with: python-tesseract
has answer: http://stackoverflow.com/a/58171526

http://stackoverflow.com/q/50992080
tagged with: dataset
linked to: http://stackoverflow.com/q/25241096
answer count: 1
downvote count: 0
has title: Data import error in Python
favorite count: 0
has comment: http://stackoverflow.com/comment/88981841
accepted answer: http://stackoverflow.com/a/50997194
upvote count: 1
tagged with: python
tagged with: matlab
type: AnsweredQuestion
score: 1
tagged with: import
type: Question
has comment: http://stackoverflow.com/comment/88979015
has comment: http://stackoverflow.com/comment/88981744
has body: I'm trying to import the MNIST dataset in Python as follows: import h5py f = h5py.File("mnist.h5") x_test = f["x_test"] x_train = f["x_train"] y_test = f["y_test"] y_train = f["y_train"] the type of say, y_train says h5py._hl.dataset.Dataset I want to convert them to float for mathematical convenience. I try this: D = x_train.astype(float) y_train = y_train.astype(float)+np.ones((60000,1)); but I get this traceback: Traceback (most recent call last): File "&lt;ipython-input-14-f3677d523d45&gt;", line 1, in &lt;module&gt; y_train = y_train.astype(float)+np.ones((60000,1)); TypeError: unsupported operand type(s) for +: 'AstypeContext' and 'float' Where am I missing out? Thanks.
has answer: http://stackoverflow.com/a/50997194
has comment: http://stackoverflow.com/comment/88982097

http://stackoverflow.com/comment/88896564
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50949437
has text: Possible duplicate of [Cannot populate numpy datetime64 arrays](https://stackoverflow.com/questions/27469031/cannot-populate-numpy-datetime64-arrays)
score: 0

http://stackoverflow.com/q/50981478
tagged with: python
has answer: http://stackoverflow.com/a/50981719
tagged with: deployment
favorite count: 0
type: UnansweredQuestion
tagged with: production-environment
has title: How does real world machine learning production systems run?
tagged with: machine-learning
upvote count: 1
downvote count: 1
type: Question
tagged with: data-science
score: 0
answer count: 1
has body: Dear Machine Learning/AI Community, I am just a budding and aspiring Machine Learner who has worked on open online data sets and some POC's built locally for my project. I have built some models and converted into pickle objects in order to avoid re-training. And this question always puzzles me. How does a real production system work for ML algorithms? Say, I have trained my ML algorithm with some millions of data and I want to move it to production system or host it on a server. In real world, do they convert into pickle objects? If so, it would be huge pickled file, isn't. The ones I trained locally and converted for 50000 rows data itself took 300 Mb space on disk for that pickled object. I don't think so this is right approach. So how does it work in order to avoid my ML algorithm to re-train and start predicting on incoming data? And how do we actually make ML algorithm as a continuous online learner. For example, I built a image classifier, and start predicting the incoming images. But I want to again train algorithm by adding the incoming online images to my previously trained data sets. May be not for every data, but daily once I want to combine all received data for that day and re-train with newly 100 images which my previously trained classifier predicted with actual value. And this approach shouldn't effect my previously trained algorithm to stop predicting incoming data as this re-training may take time based on computational resources and data. I have Googled and read many articles, but couldn't find or understand to my above question. And this is puzzling me every day. Do manual intervention is needed for production systems as well? or any automated approach is there for it? Any leads or answers to above questions would be highly helpful and appreciated. Please let me know if my questions doesn't make sense or not understandable. This is not a project centric I am looking for. Just a generic case of real world production ML systems example. Thank you …

http://stackoverflow.com/a/63783307
has body: The regex approach can be brittle. I suggest you find a library that can parse the JSON text that is missing quotes. For example, in Kotlin 1.4, the standard way to parse a JSON string is using Json.decodeFromString. However, you can use Json { isLenient = true }.decodeFromString to relax the requirements for quotes. Here is a complete example in JUnit. import kotlinx.serialization.Serializable import kotlinx.serialization.decodeFromString import kotlinx.serialization.json.Json import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test @Serializable data class Widget(val x: Int, val y: String) class JsonTest { @Test fun `Parsing Json`() { val w: Widget = Json.decodeFromString("""{"x":123, "y":"abc"}""") Assertions.assertEquals(123, w.x) Assertions.assertEquals("abc", w.y) } @Test fun `Parsing Json missing quotes`() { // Json.decodeFromString("{x:123, y:abc}") failed to decode due to missing quotes val w: Widget = Json { isLenient = true }.decodeFromString("{x:123, y:abc}") Assertions.assertEquals(123, w.x) Assertions.assertEquals("abc", w.y) } }
answers question: http://stackoverflow.com/q/50947760
type: Answer
has comment: http://stackoverflow.com/comment/118051848
score: 0

http://stackoverflow.com/comment/88916628
type: Comment
comment on: http://stackoverflow.com/a/50959780
has text: Curious, how does the `while` end? I rarely use `itertools`.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88863369
type: AnswerComment
has text: I tried: `df.loc[:, df.columns != 'ID'].applymap(lambda x: datetime.strptime('1582/10/15', "%Y/%m/%d") + timedelta(days=x) if pd.notnull(x) else x)`and it seems to work. However, it won't show the ID.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50931771

http://stackoverflow.com/comment/88771064
type: Comment
comment on: http://stackoverflow.com/a/50884547
type: AnswerComment
has text: Thanks so much! That worked and it only took me 10 seconds to fix!
score: 0

http://stackoverflow.com/comment/88789620
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50870470
score: 0
has text: I remove `~` chars in between field qualifiers (double quotes) and then remove all `"` that have no `"` or `~` to the end of the field (not sure it is what you need, hence still hesitating to post as an answer).

http://stackoverflow.com/comment/88818430
comment on: http://stackoverflow.com/a/50909091
type: AnswerComment
score: 0
type: Comment
has text: I did it and now I get a new error saying `'dict' object not callable` on line `prod.photo1 = form.cleaned_data('photo1')`

http://stackoverflow.com/comment/88797331
comment on: http://stackoverflow.com/a/50898764
type: Comment
has text: `File "F:\django\fostania\fostania\urls.py", line 28, in <module> path('login/', auth_views.LoginView(authentication_form=EmailAuthForm), name='login'), File "C:\Users\LiTo\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\urls\conf.py", line 73, in _path raise TypeError('view must be a callable or a list/tuple in the case of include().') TypeError: view must be a callable or a list/tuple in the case of include().`
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90388740
type: AnswerComment
score: 0
type: Comment
has text: unfortunately not
comment on: http://stackoverflow.com/a/51501852

http://stackoverflow.com/a/50882865
answers question: http://stackoverflow.com/q/50868607
downvote count: 0
score: 1
has body: You cannot use parameters for table/column names, regardless of what their contents are. The safest way to insert a user-specified table name is to check that it is in a list of known valid names: valid_tables = ["ThisTable", "ThatTable"] if str not in valid_tables: raise Exception("invalid table name") If you do not have such a known list, correctly quote the table name as an identifer; this only requires doubling any quote character inside: def sql_quote_identifier(x): return '"' + x.replace('"', '""') + '"' c.execute("INSERT INTO {} VALUES ...".format(sql_quote_identifier(str)), ...)
type: Answer
upvote count: 1

http://stackoverflow.com/comment/88780048
comment on: http://stackoverflow.com/a/50886765
score: 0
type: AnswerComment
type: Comment
has text: sorry. i found the reason for this line `closing =cv2.adaptiveThreshold(closing , 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 15, 2)`

http://stackoverflow.com/q/50905642
has answer: http://stackoverflow.com/a/50905865
accepted answer: http://stackoverflow.com/a/50905743
tagged with: python
has comment: http://stackoverflow.com/comment/88814680
has title: How to solve this error startswith?
tagged with: http://stackoverflow.com/tag/xml
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88886214
score: 0
has body: Why I am getting this error? Traceback(most recent call last): File "/home/prachh/odoo-new/11/odoo/odoo/http.py", line 650, in _handle_exception return super(JsonRequest, self)._handle_exception(exception) File "/home/prachh/odoo-new/11/odoo/odoo/http.py", line 310, in _handle_exception raise pycompat.reraise(type(exception), exception, sys.exc_info()[2]) File "/home/prachh/odoo-new/11/odoo/odoo/tools/pycompat.py", line 87, in reraise raise value File "/home/prachh/odoo-new/11/odoo/odoo/http.py", line 692, in dispatch result = self._call_function(**self.params) File "/home/prachh/odoo-new/11/odoo/odoo/http.py", line 342, in _call_function return checked_call(self.db, *args, **kwargs) File "/home/prachh/odoo-new/11/odoo/odoo/service/model.py", line 97, in wrapper return f(dbname, *args, **kwargs) File "/home/prachh/odoo-new/11/odoo/odoo/http.py", line 335, in checked_call result = self.endpoint(*a, **kw) File "/home/prachh/odoo-new/11/odoo/odoo/http.py", line 936, in call return self.method(*args, **kw) File "/home/prachh/odoo-new/11/odoo/odoo/http.py", line 515, in response_wrap response = f(*args, **kw) File "/home/prachh/odoo-new/11/odoo/addons/web/controllers/main.py", line 934, in call_button action = self._call_kw(model, method, args, {}) File "/home/prachh/odoo-new/11/odoo/addons/web/controllers/main.py", line 922, in _call_kw return call_kw(request.env[model], method, args, kwargs) File "/home/prachh/odoo-new/11/odoo/odoo/api.py", line 689, in call_kw return call_kw_multi(method, model, args, kwargs) File "/home/prachh/odoo-new/11/odoo/odoo/api.py", line 680, in call_kw_multi result = method(recs, *args, **kwargs) File "/home/prachh/odoo-new/11/enterprise/account_bank_statement_import_csv/wizard/account_bank_statement_import_csv.py", line 19, in import_file return super(AccountBankStatementImport, self).import_file() File "/home/prachh/odoo-new/11/apps/account_bank_statement_import_bankgiro/models/inherited_account_bank_statement_import.py", line 18, in impor…
type: Question
tagged with: odoo
has comment: http://stackoverflow.com/comment/88844963
has answer: http://stackoverflow.com/a/50905743
has comment: http://stackoverflow.com/comment/88885611
has comment: http://stackoverflow.com/comment/88816539
answer count: 2
has comment: http://stackoverflow.com/comment/88818797
possible better answer: http://stackoverflow.com/a/50905865
has comment: http://stackoverflow.com/comment/88937955

http://stackoverflow.com/q/50989759
answer count: 0
type: UnansweredQuestion
has body: I am developing an app that displays advertisements. It will display in fullscreen and divide the screen into 2 parts. One part will display an image (or a slide of images). The other part will display a loop of videos, it automatically plays a list of videos in the folder and repeats them. No pause or start button is required but the sound of the video. I have tried with opencv and PIL but it just helps me to play a single video once and play without the video's sound. The code below is what I have used in my project: ret, frame = self.vid.get_frame() if ret: self.photo = PIL.ImageTk.PhotoImage(image=PIL.Image.fromarray(frame), master=self) self.videoCanvas.create_image(self.x, self.y, image=self.photo, anchor=CENTER) self.after(self.delay, self.update) As I understand, it basically captures all the images in the video and displays them again in order on the canvas. I am looking for a solution to such problem.
downvote count: 1
tagged with: opencv
has title: Python: Create a loop of videos (clips) by using tkinter
tagged with: python-imaging-library
type: Question
score: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/88974446
has comment: http://stackoverflow.com/comment/88988906
favorite count: 0
tagged with: python
tagged with: tkinter

http://stackoverflow.com/comment/88807427
score: 0
has text: It's not previously saved value. It's the value of your onetoone field. That drop-down column is there if you want to change the relation to some other instance.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50903837

http://stackoverflow.com/comment/102563678
type: Comment
has text: This says nothing about the setup of the orientdb and gremlin-server. I'll upvote if you supply this information since i'd like to use it in http://wiki.bitplan.com/index.php/Gremlin_python#Connecting_to_Gremlin_enabled_graph_databases.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/55063546

http://stackoverflow.com/a/50907870
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 1
accepted answer of: http://stackoverflow.com/q/50907796
has body: List comprehension for instance.. out = [str(L1[i]) + " " + str(L1[i+1]) for i in range(0, len(L1)//2, 2)] # Out[15]: ['PHE 45', 'HIS 46', 'HIS 46']
upvote count: 1
answers question: http://stackoverflow.com/q/50907796

http://stackoverflow.com/comment/88956371
score: 0
has text: I've cut it down. The old df was replicated. As in I have 12 columns and the names are situated in the 5th column. Now I have 7 columns. The names are still in the 5th column
comment on: http://stackoverflow.com/q/50979757
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50929968
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/50930461
has comment: http://stackoverflow.com/comment/88859043
tagged with: python
has comment: http://stackoverflow.com/comment/88858982
has body: I am writing a code the represent the Ulam Spiral Diagonal Numbers and this is the code I typed myself t = 1 i = 2 H = [1] while i &lt; 25691 : for n in range(4): t += i H.append(t) i += 2 print(H) The number "25691" in the code is the side lenght of the spiral.If it was 7 then the spiral would contain 49 numbers etc. Here H will give you the all numbers in diagonal. But I wonder is there a much faster way to do this. For example if I increase the side lenght large amount it really takes forever to calculate the next H. Code Example: t = 1 i = 2 H = [1] for j in range(25000,26000): while i &lt; j : for n in range(4): t += i H.append(t) i += 2 For example my computer cannot calculate it so, is there a faster way to do this ?
accepted answer: http://stackoverflow.com/a/50930461
type: AnsweredQuestion
has title: Ulam Spiral (for diagonal numbers) writing program python
type: Question

http://stackoverflow.com/comment/88729189
type: QuestionComment
type: Comment
has text: Add some logging and check timestamp in Stackdriver Logging to see where you use the time: https://cloud.google.com/appengine/docs/standard/python/logs/
score: 0
comment on: http://stackoverflow.com/q/50858658

http://stackoverflow.com/a/50999304
type: Answer
has body: Try sending this: postdata=b'''{"IsLocationTrue":"True","LocType":"country"}'''
score: 0
answers question: http://stackoverflow.com/q/50998701
has comment: http://stackoverflow.com/comment/88995964

http://stackoverflow.com/q/50893341
tagged with: selenium
type: AnsweredQuestion
has title: How can I get table with dynamic data from a url using Selenium and xpath, or other alternative?
score: 1
type: Question
has body: I am trying to retrieve the main "Network Status" table data from this site: http://dev.cryptolions.io/mainnet/ I have tried many combinations of selenium functions populated with Chrome's copy selector and copy Xpath, but am not having any luck. The site opens with selenium, but I keep getting errors similar to this. What am I missing here? Getting the table in any number of data structures would be ok. But a dictionary, JSON, or something I can load into a pandas df would be ideal. NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="bpTableSystem"]"} (Session info: chrome=67.0.3396.87) (Driver info: chromedriver=2.40.565498 (ea082db3280dd6843ebfb08a625e3eb905c4f5ab),platform=Windows NT 10.0.17134 x86_64) My Code: driver = webdriver.Chrome(r'C:\chromedriver_win32\chromedriver.exe') browser = webdriver.Chrome() browser.get('http://dev.cryptolions.io/mainnet/') time.sleep(30) content = driver.find_element_by_xpath('//*[@id="bpTableSystem"]') print content.text
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/50894583
upvote count: 1
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/50894583
tagged with: selenium-webdriver
tagged with: xpath

http://stackoverflow.com/q/50930945
tagged with: python-2.7
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/50937974
has comment: http://stackoverflow.com/comment/88873964
has comment: http://stackoverflow.com/comment/88873948
tagged with: python
type: AnsweredQuestion
tagged with: pyside
has body: I am wanting to make a custom button class that allows for clicking and drag and drop. I also want the ability to control the aesthetics of it (button color, mouse over color, clicked color, drag over color, etc.). Note: these examples are shorter, generic versions of what I need to do. I know it doesn't contain all necessary things to work and some names of variables and functions are just examples. My real example will need as many as 15 instances of this class instead of the 4 shown. In the example of clicking the button, as soon as I override the mousePressEvent and the mouseReleaseEvent the my_button.clicked.connect(my_func) statement no longer works. And being that I want to use this custom class for all kinds of button functions I can't just put the button functions in the overridden method, which is what my current solution is and I hate it (see below). I tried using the super(DropZone_Category, self)mouseReleaseEvent(event) statement after my style sheet changes (as suggested in other questions) but this did absolutely nothing for me. All I really wanted to do with these overrides was control the style sheet so if there is a better way to do this, please advise. from PySide import QtGui, QtCore class DropZone_Category(QtGui.QPushButton): def __init__(self, parent=None, *args, **kwargs): super(DropZone_Category, self).__init__(parent, *args, **kwargs) # Instance Attrs self.parent = parent # Style Variables self.dropZone_font = QtGui.QFont() self.dropZone_font.setPointSize(16) self.dropZone_font.setFamily("Calibri") self.default_button_stylesheet = "background-color: rgb(100,100,100);" \ "color: lightgrey;" \ "border-radius: 3px;" self.drag_button_stylesheet = "background-color: rgb(166,215,176);" \ "color: rgb(0,97,19);" \ "border-radius: 3px;" self.hover_button_stylesheet = "background-color: rgb(150,150,150);" \ "color: lightgrey;" \ "border-radius: 3px;" self.clicked_button_stylesheet = "background-color: rgb(80,80,80);" \ "color: lightgrey;" \ "border-ra…
has comment: http://stackoverflow.com/comment/88873739
type: Question
has answer: http://stackoverflow.com/a/50937974
has title: Overriding QPushButton Class Event Method with PySide

http://stackoverflow.com/comment/88834565
type: QuestionComment
has text: nothing that was just my way of highlighting that that was the line I was concerned with but I guess it's just confusing. I'll take it out
score: 0
comment on: http://stackoverflow.com/q/50917074
type: Comment

http://stackoverflow.com/comment/88946622
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50974693
score: 1
has text: It looks like you are throwing away the phase. Don't do that. Use the phase, Luke.

http://stackoverflow.com/q/50866961
score: 7
type: Question
has comment: http://stackoverflow.com/comment/88736194
upvote count: 7
answer count: 1
downvote count: 0
tagged with: django-rest-framework
favorite count: 0
has title: How to return a single object with Django-Rest-Framework
type: UnansweredQuestion
tagged with: django
has answer: http://stackoverflow.com/a/50867968
tagged with: python
has body: I'm trying to return a single object with profile information but am stuck getting an array in return. How do I just return a single object. Current output: [{"id":1,"username":"someusername"}] Desired output: {"id":1,"username":"someusername"} serializers.py from rest_framework import serializers from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username') views.py # from django.shortcuts import render from django.contrib.auth.models import User from profiles.serializers import UserSerializer from rest_framework import viewsets # Create your views here. class CurrentUserViewSet(viewsets.ReadOnlyModelViewSet): """ Lists information related to the current user. """ serializer_class = UserSerializer def get_queryset(self): user = self.request.user.id return User.objects.filter(id=user)

http://stackoverflow.com/comment/88931294
type: QuestionComment
type: Comment
has text: Possible duplicate of [google api client python import taskqueue](https://stackoverflow.com/questions/38848896/google-api-client-python-import-taskqueue)
score: 1
comment on: http://stackoverflow.com/q/50967491

http://stackoverflow.com/comment/88724436
type: Comment
type: QuestionComment
has text: Possible duplicate of [Sort a list of strings by their lengths](https://stackoverflow.com/questions/21299988/sort-a-list-of-strings-by-their-lengths)
comment on: http://stackoverflow.com/q/50860933
score: 2

http://stackoverflow.com/a/51005427
score: 0
has comment: http://stackoverflow.com/comment/89018141
has comment: http://stackoverflow.com/comment/89007227
type: Answer
answers question: http://stackoverflow.com/q/51005244
has comment: http://stackoverflow.com/comment/89017820
has body: As mentioned in this answer, you have to first import the following from sas7bdat import SAS7BDAT and then cast your file as SAS7BDAT("airline.sas7bdat") Then you can convert it to a data frame. YEAR Y W R L K 0 1948.0 1.214 0.243 0.1454 1.415 0.612 1 1949.0 1.354 0.260 0.2181 1.384 0.559 2 1950.0 1.569 0.278 0.3157 1.388 0.573 3 1951.0 1.948 0.297 0.3940 1.550 0.564 4 1952.0 2.265 0.310 0.3559 1.802 0.574
has comment: http://stackoverflow.com/comment/89005508
has comment: http://stackoverflow.com/comment/89004838

http://stackoverflow.com/comment/88990458
has text: This is a python code which is executed in spyder
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50998203

http://stackoverflow.com/a/50868981
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50868873
type: Answer
has body: If you want a Userbase to contain multiple Usernames. Username should not be a subclass of Userbase. It is not an i-sa relationship. A Username is not a special type of Userbase. Try instead something like this. class Username(): def __init__ (self, username, userbase): self.username = username userbase.userbase[self.username] = self Here Username adds itself to the Userbase passed in its constructor. An even better approach is to add a method to Userbase that adds a Username. class Userbase(object): ... def add_user(self, user): self.userbase[user.username] = user Now after creating a Username it can be added to the Userbase. b = Userbase('my_base') u = Username('bob') b.add_user(u)
answers question: http://stackoverflow.com/q/50868873

encoding
tags question: http://stackoverflow.com/q/50955687
tags question: http://stackoverflow.com/q/51004261
tags question: http://stackoverflow.com/q/50942773
type: Tag
tags question: http://stackoverflow.com/q/50947115
tag name: encoding
tags question: http://stackoverflow.com/q/50860670
tags question: http://stackoverflow.com/q/50925937
tags question: http://stackoverflow.com/q/51009154
tags question: http://stackoverflow.com/q/51004427

http://stackoverflow.com/a/50958701
has body: import copy import heapq #from dotmap import Map from itertools import count class Map(dict): def __getattr__(self, k): return self[k] def __setattr__(self, k, v): self[k] = v graph = { 'A': ['B', 'E'], 'B': ['C', 'D'], 'C': ['G'], 'D': ['C', 'F'], 'E': ['D'], 'F': [], 'G': ['F'] } class PriorityQueue: def __init__(self): self.elements = [] self._counter = count() def empty(self): return len(self.elements) == 0 def put(self, item, priority): heapq.heappush(self.elements, (priority, item,)) def get(self): return heapq.heappop(self.elements)[1] class AStar: def __init__(self, graph, start, goals=[]): self.graph = graph self.start = start self.frontier = PriorityQueue() self.frontier.put(start, 0) self.previous = {} self.previous[start] = None self.costs = {} self.costs[start] = 0 self.final_path = None self.goals = goals self.goal = None def search(self): graph = self.graph frontier = self.frontier goals = self.goals costs = self.costs while not frontier.empty(): state = frontier.get() if state in goals: cost = self.costs[state] self.goal = state self.final_path = self.trace_path() return Map({'path': self.final_path, 'cost': cost}) for next_state in graph[state]: new_cost = costs[state] + 1 if next_state not in costs or new_cost &lt; costs[next_state]: costs[next_state] = new_cost priority = new_cost frontier.put(next_state, priority) self.previous[next_state] = state # No path found return Map({'path': [], 'cost': float('inf')}) def trace_path(self): current = self.goal path = [] while current != self.start: path.append(current) current = self.previous[current] path.append(self.start) path.reverse() return path def YenKSP(graph, source, sink, k_paths): A = [AStar(graph, source, sink).search().path] B = [] for _ in range(1, k_paths): for i in range(len(A[-1]) - 1): graph_clone = copy.deepcopy(graph) spur_node = A[-1][i] root_path = A[-1][:i+1] for path in A: if len(path) &gt; i and root_path == path[:i+1]: if path[i+1] in graph_clone[path[i]]: graph_clone[path[i]].re…
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50958152
type: Answer
answers question: http://stackoverflow.com/q/50958152

http://stackoverflow.com/comment/88715981
type: Comment
type: QuestionComment
has text: to be honest, I can't help you right now. a further step would be to work from a small csv file that you can paste in your question. Now you would get answers :)
comment on: http://stackoverflow.com/q/50855654
score: 0

http://stackoverflow.com/comment/88978374
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50991334
score: 1
has text: I missed that, your ` "-1",` should be `-1` in `functions`.

http://stackoverflow.com/comment/88983467
has text: @Noah: I don't think so. Like, I'm kind of missing a point as to whether manually adding the current working directory to the path is absolutely required. I was under the assumption that init.py basically helps you discover modules within packages. But maybe not in this?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50977078

http://stackoverflow.com/comment/88863470
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50931571
has text: that makes sense, thx ! (I'm ready to wait a long time ^^ )
score: 0

http://stackoverflow.com/a/50976585
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50971871
answers question: http://stackoverflow.com/q/50971871
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88949408
type: Answer
has body: If NumPy is available you can use the interp function to generate your scaled values (docs): import numpy as np scaled_a = np.interp(a, (min(a), max(a)), c) The scaled_a variable is a NumPy array that can be passed to matplotlib's plot function in place of the original a variable. If NumPy is not available you'll have to do a bit of arithmetic to calculate the new values: def scaler(x, old_min, old_max, new_min, new_max): old_diff = old_max - old_min new_diff = new_max - new_min return ((x - old_min) * (new_diff / old_diff)) + new_min old_min = min(a) old_max = max(a) scaled_a = [scaler(x, old_min, old_max, c[0], c[1]) for x in a] The variable scaled_a is now a python list, but it can still be passed to the plot function.
score: 1

timeit
tag name: timeit
type: Tag
tags question: http://stackoverflow.com/q/50902910
tags question: http://stackoverflow.com/q/50891288

http://stackoverflow.com/q/50904668
has comment: http://stackoverflow.com/comment/88809164
upvote count: 0
has answer: http://stackoverflow.com/a/50904800
score: -3
has body: i have a log text like this. data = ''' ================================================================================ Annotation file: /b/cd-builder/sandboxes/sb_DEV_COMMON_BRANCH-_act-builder-4977/annofile-4977TB53661_cd-builder.xml Build ID: 27951 on Host bng-emake-5a.juniper.net, Cluster Manager: bng-ea-cm-02:8030 Start Time: Sun Jun 17 23:57:30 2018 Job ID: J00002adde8677420 , Exit Value 1 CWD: /b/cd-builder/sandboxes/sb_DEV_COMMON_BRANCH-_act-builder-4977/obj/bsd11/amd64/junos/usr.sbin/rpd/bgp/lib/proto Node: bng-ea-agent-14a-3 Start: 2018-06-18 00:20:55.488609 (1405.488609) End: 2018-06-18 00:20:56.653945 (1406.653945) Command: export BMAKELOCATION=/b/cd-builder/sandboxes/sb_DEV_COMMON_BRANCH-_act-builder-4977/src/build/mk/jnx.sym_check.mk:37; CURDIR=/b/cd-builder/sandboxes/sb_DEV_COMMON_BRANCH-_act-builder-4977/src/junos/usr.sbin/rpd/bgp/lib/proto OBJDUMP=/volume/hab/Linux/Ubuntu-12.04/x86_64/llvm/3.7/current/bin/amd64-unknown-freebsd11.0-objdump BSS_SYMS=bss_syms.clang.amd64,bsdx TLS_SYMS=tls_syms.clang.amd64,bsdx ACCEPT_CMD='mk --machine amd64,bsd11 -C junos/usr.sbin/rpd/bgp/lib/proto accept-syms' /volume/hab/Linux/Ubuntu-12.04/x86_64/bsd-tools/current/bin/sh /b/cd-builder/sandboxes/sb_DEV_COMMON_BRANCH-_act-builder-4977/src/build/scripts/sym_check.sh librpd-proto-bgp.a ------------------------------ Output ------------------------------ ERROR: /b/cd-builder/sandboxes/sb_DEV_COMMON_BRANCH-_act-builder-4977/src/junos/usr.sbin/rpd/bgp/lib/proto/tls_syms.clang.amd64,bsdx: changed global or static TLS variables 261a262 &gt; bgp_inetsrte_incolor_update._xinfo If correct, use: mk --machine amd64,bsd11 -C junos/usr.sbin/rpd/bgp/lib/proto accept-syms make[1]: *** [check-syms] Error 1 -------------------------------------------------------------------- Operations: ================================================================================ + echo -e '\e[31m Displaying Production.log.errs\e[0m' Displaying Production.log.errs + echo 'End Meta Error logs' End Me…
has title: Find the text between two string pattern
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88809087
has answer: http://stackoverflow.com/a/50905294
has comment: http://stackoverflow.com/comment/88809091
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/50904787
linked to: http://stackoverflow.com/q/12736074
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/50904712
has answer: http://stackoverflow.com/a/50904754
has answer: http://stackoverflow.com/a/50904712
accepted answer: http://stackoverflow.com/a/50904787
downvote count: 3
answer count: 5
has comment: http://stackoverflow.com/comment/88809612
has comment: http://stackoverflow.com/comment/88809195

http://stackoverflow.com/comment/88945047
has text: This is creating a range. The bins are `(0-0.2], (0.2-0.5]`, etc.
comment on: http://stackoverflow.com/a/50974408
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50867251
tagged with: python
has body: I am running Python tornado web application from terminal by typing the command python app.py when I close the terminal, the app stops. Is there anyway I can still run the app on a port such that closing terminal wouldn't affect it? Because I don't want to keep the terminal open.
tagged with: command-line
tagged with: python-3.x
has title: How to close the terminal when running a tornado application?
has answer: http://stackoverflow.com/a/50867497
upvote count: 1
answer count: 1
type: UnansweredQuestion
tagged with: tornado
downvote count: 0
score: 1
favorite count: 0
type: Question

http://stackoverflow.com/comment/88765688
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50881678
type: AnswerComment
has text: That did the charm. Thanks a mil, my problem is solved.

http://stackoverflow.com/comment/88772866
has text: The new dictionary will have what values for those matched keys?
type: QuestionComment
comment on: http://stackoverflow.com/q/50885545
score: 0
type: Comment

http://stackoverflow.com/a/50862026
type: Answer
has body: With comprehension list you could do: df['refValue'] = [ row['Value'] - float(df.loc[(df['No']==row['No']) &amp; (df['Group']==row['refGroup']),'Value'].values) if row['refGroup']!=row['Group'] else row['Value'] for index, row in df.iterrows() ]
has comment: http://stackoverflow.com/comment/88742307
upvote count: 1
has comment: http://stackoverflow.com/comment/88742549
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/50860328

http://stackoverflow.com/q/50924487
downvote count: 0
answer count: 1
tagged with: concurrent.futures
favorite count: 0
tagged with: python-3.x
has title: How to retrieve a task from a future in python?
upvote count: 1
tagged with: python
type: AnsweredQuestion
has body: Let say I have the following code to run multiple task in parallel. with concurrent.futures.ThreadPoolExecutor(max_workers=connections) as executor: loop = asyncio.get_event_loop() futures = [ loop.run_in_executor( executor, fun, arg ) for i in range(connections) ] for result in await asyncio.gather(*futures): # I want to access the futures task here pass Is it possible to read the the futures' task once it has been executed?
has answer: http://stackoverflow.com/a/50927656
score: 1
tagged with: async-await
accepted answer: http://stackoverflow.com/a/50927656
type: Question
has comment: http://stackoverflow.com/comment/88852532
tagged with: python-asyncio

http://stackoverflow.com/q/50930155
tagged with: python
has body: How can I find the correlation between the frequency of specific values in multiple text columns? These columns contain specific tags like: 'Indicator Discrepancy','Missing or Invalid', or 'Inaccurate'. I would like to figure out which values in the first sheet are correlated with changes in values in the second list.
has comment: http://stackoverflow.com/comment/88860329
tagged with: text-analysis
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88864824
type: Question
tagged with: http://stackoverflow.com/tag/r
has title: Correlation between two text columns Python (text Analytics)
score: 0

http://stackoverflow.com/comment/88792697
comment on: http://stackoverflow.com/q/50892346
has text: Possible duplicate of [How I can make apt-get install to my virtualenv?](https://stackoverflow.com/questions/11441546/how-i-can-make-apt-get-install-to-my-virtualenv)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50972733
type: Question
tagged with: minidom
tagged with: xml-parsing
answer count: 1
downvote count: 0
tagged with: elementtree
favorite count: 0
tagged with: http://stackoverflow.com/tag/xml
has answer: http://stackoverflow.com/a/50975188
type: UnansweredQuestion
tagged with: python
has body: I have a large number of XML file in which I want to make the following changes: Create a new element – let's call it new_element – under the root element Find another, specific element, which is more deeply nested – let's call it existing_element – and move it such that it becomes a child of new_element I want to do this in the least intrusive way possible, such that the diff between the old file and the new file only shows changes on rows that either belong to the newly created element (and hence have been added to the file) or that used to belong to the element that was moved (and hence have been removed from the file). I want to do this using Python 3. However, when I try just reading one of the XML files with xml.dom.minidom and writing what I just read to a new file and diff the two files, every single line gets marked as changed (probably because they contain different types newlines). Besides, when I look at the contents of the two files, I see that the encoding specification in the XML declaration, as well as the newline after the declaration, have disappeared, and attributes in tags all throughout the document have had their order shuffled within the tag. The story is very similar when using xml.etree.ElementTree, only that now the entire XML declaration disappears, all tag names are preceded by "ns0:" (for some reason), and some attribute names are followed by ":ns0". None of these "extra" modifications to the XML files are desirable, since I want to be able to diff the old file and the new file and be able to easily see what has changed and what has not. So, is there some simple way to create a new XML file based on another XML file that only introduces changes to lines that really are supposed to be changed and leave all other lines untouched, and that doesn't involve writing your own code to parse the XML data? Edit: Here is the structure of the file I want to process (since I don't know what will cause any suggested code to work or not to work with my…
score: 1
upvote count: 1
has title: Python: Working with XML files non-intrusively

http://stackoverflow.com/comment/88850337
score: 1
has text: *"nothing works for me"* - show us what you already tried then
type: QuestionComment
comment on: http://stackoverflow.com/q/50925488
type: Comment

http://stackoverflow.com/comment/88996188
has text: Could you add details about the way it fails? Does it throw an error? Is the answer just wrong?
score: 1
comment on: http://stackoverflow.com/q/51001182
type: Comment
type: QuestionComment

heap-memory
tag name: heap-memory
type: Tag
tags question: http://stackoverflow.com/q/50902111

lightgbm
tags question: http://stackoverflow.com/q/50889162
tag name: lightgbm
tags question: http://stackoverflow.com/q/50894390
tags question: http://stackoverflow.com/q/50982269
tags question: http://stackoverflow.com/q/50931168
type: Tag
tags question: http://stackoverflow.com/q/50956103
tags question: http://stackoverflow.com/q/50973373

http://stackoverflow.com/comment/88771081
has text: https://stackoverflow.com/q/1912434/62576
comment on: http://stackoverflow.com/q/50884375
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88956259
has text: I think the question is too localised right now.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50979757
score: 1

http://stackoverflow.com/comment/88773869
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50886079
score: 0
has text: No sorry the exact code had it as ques82.lower() it runs without issue. I will edit the question right now to correct that

http://stackoverflow.com/comment/89025370
comment on: http://stackoverflow.com/q/50898333
score: 0
type: Comment
type: QuestionComment
has text: @PM2Ring, you're right. I'll do this. Still, having the average colors should ease the process of representing the resulting image.

http://stackoverflow.com/comment/88818763
type: Comment
comment on: http://stackoverflow.com/a/50907445
type: AnswerComment
has text: If you want to convert that list to a vector, use `np.array`. `np.arange` is analogous to the Python builtin `range`, creating an array of linearly spaced values. It does not construct a new array from some values, like you want to do here.
score: 0

http://stackoverflow.com/comment/88742442
comment on: http://stackoverflow.com/q/50870393
has text: i was trying, but it kept just posting some text and then links, while removing all the other HTML
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/88806618
has text: Also, take a look at the [How to Ask](https://stackoverflow.com/help/how-to-ask) page.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50900226

http://stackoverflow.com/comment/88981142
type: Comment
comment on: http://stackoverflow.com/a/50993188
score: 1
type: AnswerComment
has text: Still working on `ms` vs `ns` issue. But you can use the `floor` method. `pd.to_datetime(df['Event Time'], unit='ns').dt.floor('s')`

http://stackoverflow.com/comment/88845635
type: Comment
has text: What do you expect to happen?
score: 0
comment on: http://stackoverflow.com/q/50923199
type: QuestionComment

average
tags question: http://stackoverflow.com/q/51004076
tags question: http://stackoverflow.com/q/50897121
tags question: http://stackoverflow.com/q/50957548
type: Tag
tag name: average

http://stackoverflow.com/a/50926571
accepted answer of: http://stackoverflow.com/q/50926012
answers question: http://stackoverflow.com/q/50926012
type: Answer
has comment: http://stackoverflow.com/comment/88861253
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/88891735
has comment: http://stackoverflow.com/comment/88891955
type: AcceptedAnswer
downvote count: 0
has body: Not sure if I'm understanding the Regex idea correctly, but if I'm correct, you want to match the following: (Zero or more words).orange.(Exactly one word) Now I do not know if the words in the hash are seperated by spaces, periods or are just words after each other, but here are the following cases: Hash words separated by spaces pattern = r"(?P&lt;hash&gt;(\w+|\s)*)\.(?P&lt;orange&gt;orange)\.(?P&lt;star&gt;\w+)" Hash words seperated by periods pattern = r"(?P&lt;hash&gt;(\w+|\.)*)\.(?P&lt;orange&gt;orange)\.(?P&lt;star&gt;\w+)" Hash words just after each other pattern = r"(?P&lt;hash&gt;(\w*))\.(?P&lt;orange&gt;orange)\.(?P&lt;star&gt;\w+)" If you don't want to have the (?P&lt;>) syntax, you can also just do the following pattern = r"(\w+|\s)*\.orange\.\w+" Which will match against your string and tell you if it is a match, but you then can't do match.group('hash') To get the hash words.

http://stackoverflow.com/a/50913564
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50913292
has body: It's possible but confusing. If you want to keep the sequence of x values and the calculations on x separate, you should do this explicitly by not involving x with an iterator. def next_value(x): """Custom iterator""" # Bunch of code defining a new x yield new_x x = None while True: x = next_value(x) x = some_calculation_on(x) # Break when you're done if finished and done: break If you want the loop to execute exactly i times, then use a for loop: for step in range(i): x = next_value(x) x = some_calculation_on(x) # No break

http://stackoverflow.com/q/50980810
tagged with: colormap
type: AnsweredQuestion
upvote count: 5
tagged with: numpy
answer count: 2
score: 5
has answer: http://stackoverflow.com/a/50980960
downvote count: 0
favorite count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/50980960
possible better answer: http://stackoverflow.com/a/50981619
has body: I am trying to create a really simple colourmap using RGB triples. That has a discrete number of colours. Here is the shape that I am trying to make it follow: I know it is probably not a true RGB spectrum, but i wanted it to be as easy to compute as possible. I want to be able to generate an array of N 8-bit RGB tuples that are evenly spaced along the line. For easy instances where all of the points in the image above fall on colours, it is easy to generate using numpy.linspace() using the following code: import numpy as np # number of discrete colours N = 9 # generate R array R = np.zeros(N).astype(np.uint8) R[:int(N/4)] = 255 R[int(N/4):int(2*N/4)+1] = np.linspace(255,0,num=(N/4)+1,endpoint=True) # generate G array G = 255*np.ones(N).astype(np.uint8) G[0:int(N/4)+1] = np.linspace(0,255,num=(N/4)+1,endpoint=True) G[int(3*N/4):] = np.linspace(255,0,num=(N/4)+1,endpoint=True) # generate B array B = np.zeros(N).astype(np.uint8) B[int(2*N/4):int(3*N/4)+1] = np.linspace(0,255,num=(N/4)+1,endpoint=True) B[int(3*N/4)+1:] = 255 # stack arrays RGB = np.dstack((R,G,B))[0] This code works fine for 5 colours: r 255 255 0 0 0 g 0 255 255 255 0 b 0 0 0 255 255 9 colours: r 255 255 255 127 0 0 0 0 0 g 0 127 255 255 255 255 255 127 0 b 0 0 0 0 0 127 255 255 255 13 colours: r 255 255 255 255 170 85 0 0 0 0 0 0 0 g 0 85 170 255 255 255 255 255 255 255 170 85 0 b 0 0 0 0 0 0 0 85 170 255 255 255 255 etc.. but I'm having trouble working out how to make it work for an arbitrary N number of colours because the linspace trick only works if it is going from one endpoint to another. Can someone please help me with working out how to do it? Any ideas for how to make my code above more efficient would be great as well, I am just learning how to use numpy after putting it off for ages..
has answer: http://stackoverflow.com/a/50981619
has title: How to create a discrete RGB colourmap with N colours using numpy
type: Question

http://stackoverflow.com/comment/88866916
type: Comment
has text: This code makes zero sense. Why do you place a `value=None` as a class variable, only to immediately replace it with a `property`? You can't set the attribute because you haven't defined a setter. Also, `if not value:` would throw a `NameError` since `value` is not defined, so this code wouldn't reach teh `AttributeError`.
type: QuestionComment
comment on: http://stackoverflow.com/q/50934180
score: 0

http://stackoverflow.com/comment/88778557
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50882980
has text: no there cannot be a non jack with same value in `add1`
score: 0

http://stackoverflow.com/a/50897613
upvote count: 2
has comment: http://stackoverflow.com/comment/88796486
answers question: http://stackoverflow.com/q/50897523
accepted answer of: http://stackoverflow.com/q/50897523
has comment: http://stackoverflow.com/comment/88796054
score: 2
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: No need to write all the code again, there are a lot of libraries already written which replicate all the requests. One such library is https://github.com/ping/instagram_private_api Solution using this library, from instagram_private_api import Client, ClientCompatPatch user_name = 'YOUR_USERNAME' password = 'YOUR_PASSWORD' username_to_scrape = 'USERNAME_TO_SCRAPE' all_posts = [] api = Client(user_name, password) posts = api.username_feed(username_to_scrape) #Gets the first 12 posts # Extract the value *next_max_id* from the above response, this is needed to load the next 12 posts next_max_id = posts["next_max_id"] all_posts = all_posts + posts # next_page_posts = api.username_feed(track_username, max_id = next_max_id) This is just a quick example to help you get started. Update: Saving &amp; Loading Cookies #Saving cookies cookies = api.cookie_jar.dump() with open("cookies.pkl", "wb") as save_cookies: save_cookies.write(cookies) #Loading cookies with open("cookies.pkl", "rb") as read_cookies: cookies = read_cookies.read() #Pass cookies to Client to resume session api = Client(user_name, password, cookie = cookies)

http://stackoverflow.com/comment/88911177
score: 2
comment on: http://stackoverflow.com/q/50956798
has text: I would only worry about this if you're working on something very performance sensitive. Be sure to choose good names. If you're doing this to imports, then you should probably have just imported the name on it's own from the other module `from math import sin, cos`.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/89247081
type: Comment
has text: Okay, got it. Thanks
type: AnswerComment
comment on: http://stackoverflow.com/a/51082267
score: 0

http://stackoverflow.com/q/50932132
has body: I want to use NLTK to recognize the difference between "red dress" and "dress shoes". The part of speech is the same for both, and none of the taggers I have tried have worked. I'm aware that POS tagger can only pick up on one token at a time, which poses some problems. I'm very new to NLTK, and I'm sure I'm just missing something very basic here.
type: Question
tagged with: nltk
upvote count: 1
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50932341
tagged with: python
accepted answer: http://stackoverflow.com/a/50932341
has title: Tagging noun adjunct or attributive noun using NLTK
type: AnsweredQuestion
downvote count: 0
score: 1

http://stackoverflow.com/comment/111685725
type: QuestionComment
comment on: http://stackoverflow.com/q/50915906
has text: Yes, you're right, @johnDanger, but I feel like using `result_type='expand'` in @harvpan's suggestion is better. `reduce` is supposed to function differently, and suggests something different. I do not exactly understand how `reduce` generates the proper result. Whereas it is quite clear why `result_type='expand'` would.
score: 0
type: Comment

http://stackoverflow.com/comment/88936692
score: 2
has text: What do you mean by "handle exceptions"? What exceptions? Exceptions in the application that is being tested?
comment on: http://stackoverflow.com/q/50969989
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88952019
score: 0
has text: `all(sub_arr[i] == Large_arr[j])` ?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50977944

http://stackoverflow.com/q/50945384
has comment: http://stackoverflow.com/comment/88921469
has comment: http://stackoverflow.com/comment/88939804
has comment: http://stackoverflow.com/comment/88893434
type: Question
upvote count: 1
favorite count: 0
has title: cv2.matchtemplate opencv inbuilt function takes undesired time for execution
tagged with: python
answer count: 0
downvote count: 0
has body: import cv2 import numpy as np import time img = cv2.imread('rotate.png', 0) template = cv2.imread('thresh_2.png', 0) w, h = template.shape[::-1] start = time.time(); res = cv2.matchTemplate( template, img, cv2.TM_CCORR) stop = time.time(); print "TIME ",stop-start; min_val, max_val, min_loc, max_loc = cv2.minMaxLoc( res ) top_left = max_loc bottom_right = ( top_left[0] + w, top_left[1] + h ) cv2.rectangle( template, top_left, bottom_right, 255, 2 ) Above code is working well but the time cv2.matchtemplate function takes is more than desired. Time taken by the single instruction cv2.matchtemplate is 0.23 secs. How can I solve this?
type: UnansweredQuestion
tagged with: opencv
score: 1

http://stackoverflow.com/comment/88881983
type: Comment
type: QuestionComment
has text: Possible duplicate of https://stackoverflow.com/questions/46820154/negative-decision-function-values
comment on: http://stackoverflow.com/q/50941223
score: 0

http://stackoverflow.com/q/50943178
favorite count: 0
upvote count: 2
tagged with: python
tagged with: regex
accepted answer: http://stackoverflow.com/a/50943489
type: AnsweredQuestion
score: 1
has title: How to find filenames inside directories in Python using regexp
has answer: http://stackoverflow.com/a/50947804
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88884262
possible better answer: http://stackoverflow.com/a/50947804
has comment: http://stackoverflow.com/comment/88884232
has answer: http://stackoverflow.com/a/50943489
answer count: 2
has comment: http://stackoverflow.com/comment/88884026
linked to: http://stackoverflow.com/q/2225564
has body: I need to scan a directory for ex: C:\Users\Jack\Work and search for a file name which has part text part numbers ex: Worklog_201810716_081.log. Could anyone please help me how can I use regexp in my code to search the file name specifically. I have implemented the following hard code with the file name: reg_lst = ["Error in log"] for i, line in enumerate(open("C:\\Users\\Jack\Work\\Worklog_201810716_081.log")): if any(compiled_reg.match(line) for compiled_reg in reg_lst): print("Found on line %s" % (i+1)) print("Log msg: ", line) This prints the message after Error in log in the Worklog_201810716_081.log file. I need to write a generic code where I need to also scan other log files in the directory for a text search.
has comment: http://stackoverflow.com/comment/88884150

http://stackoverflow.com/q/51011390
tagged with: python
tagged with: append
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51011495
downvote count: 0
type: Question
has title: Dynamic Merging of Pandas Dataframes
upvote count: 2
tagged with: pandas
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/51011495
has body: I am writing a program in python which asks the user to select 5 symbols. After the user selects five symbols the program will provide various outputs. The way the program currently works it creates five uniquely named pandas dataframes and then joins them into one frame as below. data1 = pdr.DataReader(symbol, 'iex', start, end) data2 = pdr.DataReader(symbol, 'iex', start, end) data3 = pdr.DataReader(symbol, 'iex', start, end) data4 = pdr.DataReader(symbol, 'iex', start, end) data5 = pdr.DataReader(symbol, 'iex', start, end) I want to improve the program so the user could select any number of stocks and the program would build one pandas dataframe. I am thinking it would be similar to an append query in a SQL database. For the purposes of this question I am keeping the symbol list static in size. import pandas import pandas_datareader as pdr from datetime import datetime start = datetime(2018, 5, 1) end = datetime(2018, 5, 31) symbol_list = ['IVV', 'EWH', 'INDY', 'EWG', 'ENZL'] for symbols in Symbol_List: symbol = symbols data = pdr.DataReader(symbol, 'iex', start, end) add something here to append the new data into a master dataframe. The append would need to rewrite the column names to include the symbols, add the columns for the new data, and ensure the data index lines up. I was thinking something like: data.rename(columns={'high': 'high' + symbol, 'low': 'low' + symbol}, inplace=True) pd.merge(masterdata, data, on='index')

http://stackoverflow.com/comment/88720678
comment on: http://stackoverflow.com/q/50858476
type: Comment
type: QuestionComment
has text: Div (/) and Mod (%) should be your friends. divmod() too.
score: 0

http://stackoverflow.com/comment/88861436
comment on: http://stackoverflow.com/a/50905367
score: 0
type: AnswerComment
has text: @Vignesh : Check out my updated answer under UPDATE section. Hope that will be helpful. Thanks !
type: Comment

http://stackoverflow.com/q/50895468
type: AnsweredQuestion
has title: Create hyperlink for accessing Multiple excel sheets by python
upvote count: 2
has body: I have multiple txt files which I am able to merge and write into different excel sheets by the below code: for file in list(file_lists): filename = os.path.join(path, file) df = pd.read_table(filename,sep="|",encoding = "ISO-8859-1") df.to_excel(writer, sheet_name=file[:-4], index=False,header=True) writer.save() I want to now create another sheet (Name = "Homepage") which will contain different sheet names as hyperlinks. I should be able to click on that hyperlink which will take me to the respective sheets. Is there any way I can do that? Any sample codes would be helpful, the similar codes available in SO are not helping me.
type: Question
has answer: http://stackoverflow.com/a/50895628
tagged with: pandas
score: 2
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/50895628
favorite count: 0
tagged with: python-3.x
tagged with: python

http://stackoverflow.com/a/50946888
answers question: http://stackoverflow.com/q/50946655
has comment: http://stackoverflow.com/comment/88927077
has comment: http://stackoverflow.com/comment/88892325
has body: using a simple iteration Demo: import pprint d = {} for i in data: if not i["id"] in d: d[i["id"]] = {'id': i["id"], 'thermo_module':{'datetime':[{'time_utc': i["time_utc"]}], 'Temperature':[i["Temperature"]]}, 'longitude':i["longitude"], 'latitude':i["latitude"], 'altitude':i["altitude"]} else: d[i["id"]]['thermo_module']["datetime"].append({'time_utc': i["time_utc"]}) d[i["id"]]['thermo_module']["Temperature"].append(i["Temperature"]) pprint.pprint(d.values()) Output: [{'altitude': 479, 'id': 'AAA', 'latitude': 46.223831, 'longitude': 7.278415, 'thermo_module': {'Temperature': [1.5, 3.4], 'datetime': [{'time_utc': 1514677434}, {'time_utc': 1514677667}]}}, {'altitude': 555, 'id': 'BBB', 'latitude': 46.21502, 'longitude': 7.269399, 'thermo_module': {'Temperature': [1.5, 2.5], 'datetime': [{'time_utc': 1514677561}, {'time_utc': 1514677196}]}}]
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/88894032
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88899826
has comment: http://stackoverflow.com/comment/88893818
accepted answer of: http://stackoverflow.com/q/50946655
downvote count: 0

http://stackoverflow.com/q/50867705
accepted answer: http://stackoverflow.com/a/50893699
tagged with: django
has title: django, python, postgres and web deployment
has comment: http://stackoverflow.com/comment/88737919
type: Question
tagged with: nginx
has answer: http://stackoverflow.com/a/50893699
possible better answer: http://stackoverflow.com/a/50870118
tagged with: ubuntu
has body: This error has been haunting me. I have actually developed fixes and I document it and I successfully run the server on the below IP address. I try to reproduce my success after reinstalling the Ubuntu OS... with the same errors the same fixes won't do it anymore... now I need outside help. I have combed the internet for solutions. I try to add django to the PYTHONPATH and it IS added but when I exit the python interpreter the appended django path disappears! Another item of detail that may help is that my website www.doman.com/admin is directed to the django admin login screen. I tried to log in using username and password but it fails which makes me think django is not working properly. $ sudo python3 manage.py runserver 192.165.4.3:80 I get the error: Traceback (most recent call last): File "manage.py", line 8, in &lt;module&gt; from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 14, in &lt;module&gt; ) from exc ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? Django is installed within my environment: $ django-admin --version 2.0.6 Python path attempt: $ PYTHONPATH=/home/kap/dev_env/lib/python3.6/site-packages/django python Python 3.6.5 (default, Apr 1 2018, 05:46:30) [GCC 7.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import django &gt;&gt;&gt; sys.path Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; NameError: name 'sys' is not defined &gt;&gt;&gt; import sys &gt;&gt;&gt; sys.path ['', '/home/kap/dev_env/lib/python3.6/site-packages/django', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/home/kap/dev_env/lib/python3.6/site-packages'] &gt;&gt;…
score: 0
has comment: http://stackoverflow.com/comment/88738428
tagged with: web-deployment
has comment: http://stackoverflow.com/comment/88743072
has answer: http://stackoverflow.com/a/50870118
has comment: http://stackoverflow.com/comment/88737987
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/50894907
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50868255

http://stackoverflow.com/a/60467110
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/106970715
has comment: http://stackoverflow.com/comment/106971035
answers question: http://stackoverflow.com/q/50856538
downvote count: 0
has body: using the following answer, all the ID and Sequence will be in the same line and i would like to obtain the header in a line and all the lines for the sequences in another line. with open('input.fasta') as f_input, open('output.fasta', 'w') as f_output: block = [] for line in f_input: if line.startswith('&gt;header'): if block: f_output.write(''.join(block) + '\n') block = [] f_output.write(line) else: block.append(line.strip()) if block: f_output.write(''.join(block) + '\n')
type: Answer

http://stackoverflow.com/comment/93355596
type: Comment
has text: @zindarod I have a problem in the code: dx = int(centroids[1][0] - centroids[0][0]) IndexError: list index out of range. How to solve?
comment on: http://stackoverflow.com/a/51043935
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88755117
score: 1
has text: @EvgenyPogrebnyak, updated the code to use command line arguments .
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50875627

http://stackoverflow.com/q/50930923
tagged with: apache-kafka
has answer: http://stackoverflow.com/a/54258794
has body: According to documentation it is possible to commit offset into kafka from (scala) spark streaming application. I would like to achieve the same functionality from pyspark. Or at least store the kafka partition, offset into external datastore (RDBMS, etc). However the pyspark api for kafka integration only provides RDD(offset, value)] instead of RDD[ConsumerRecord] (as in scala). Is there any way to obtain (topic, partition, offset) from the python RDD? And persist it else where?
upvote count: 2
tagged with: apache-spark
answer count: 1
has title: pyspark streaming commit offset to kafka
favorite count: 0
tagged with: spark-streaming
type: UnansweredQuestion
tagged with: python
score: 2
downvote count: 0
type: Question

http://stackoverflow.com/q/50933566
has comment: http://stackoverflow.com/comment/88865764
tagged with: python
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/40987185
has answer: http://stackoverflow.com/a/50933596
type: Question
linked to: http://stackoverflow.com/q/6074018
has body: I have a code like below a=25 b=20 #number=0 if a &lt; b == True: number = 1 elif a &gt;b == True: number = 2 print(number) When i execute this i get the following error NameError: name 'number' is not defined When i initialize the number = 0 like below a=25 b=20 number=0 if a &lt; b == True: number = 1 elif a &gt;b == True: number = 2 print(number) then i am not getting the output as 2, i am getting 0 instead, what am i missing here
has title: NameError: name 'number' is not defined
score: 0
duplicate of: http://stackoverflow.com/q/6074018
answer count: 1
accepted answer: http://stackoverflow.com/a/50933596

http://stackoverflow.com/comment/88949717
has text: Did you test the pulp installation? From EC2 Python IDE, can you try `>>> import pulp` and then `>>> pulp.pulpTestAll().` That way you can start to rule out possible causes.
type: QuestionComment
comment on: http://stackoverflow.com/q/50957523
score: 0
type: Comment

http://stackoverflow.com/a/50878865
downvote count: 0
has body: Since you are probably attempting to hardcode your filepath and not ask for user input (input()), you should probably replace xl = pd.ExcelFile(input("C:\Praca\dane.xlsx")) with xl = pd.ExcelFile(r"C:\Praca\dane.xlsx")
answers question: http://stackoverflow.com/q/50878792
upvote count: 3
type: Answer
score: 3

http://stackoverflow.com/comment/88858936
has text: Is the string to be converted to integer always in the same position? or you need to find it?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50929995

rest
tags question: http://stackoverflow.com/q/50972893
tags question: http://stackoverflow.com/q/50895202
tags question: http://stackoverflow.com/q/50897102
tags question: http://stackoverflow.com/q/50915931
tags question: http://stackoverflow.com/q/50959137
tags question: http://stackoverflow.com/q/51010940
tags question: http://stackoverflow.com/q/50977217
tags question: http://stackoverflow.com/q/50972719
tags question: http://stackoverflow.com/q/50929182
type: Tag
tag name: rest
tags question: http://stackoverflow.com/q/50936240

http://stackoverflow.com/q/50917228
has comment: http://stackoverflow.com/comment/88834503
has comment: http://stackoverflow.com/comment/88836219
type: UnansweredQuestion
tagged with: python
has title: Difference in result of the same run due to python
has comment: http://stackoverflow.com/comment/88835131
has comment: http://stackoverflow.com/comment/88834534
answer count: 0
has comment: http://stackoverflow.com/comment/88834590
type: Question
has body: I am not sure if this is the best place to ask this question but since I wrote me code in python, I decided to ask here. I am working with python on my linux machine and on spyder. On spyder there is version3.6. My ubuntu runs version 3.6.5. I ran my code on both but got different results despite copying the same code from spyder to my ubuntu. Working Code: from operator import itemgetter b = ['3/', '2/', '3/0', '/0', '5/0'] c = [[7, 3, 0, 0], [5, 0, 5, 0], [0, 3, 7, 0], [10, 0, 0, 0], [2, 0, 8, 0]] d = list(zip(b,[str(a).replace(' ','') for a in c])) f =[] for i in d: f.extend([i[0], (i[1]).strip("[]")]) g = [":".join(f[i:i+2]) for i in range(0, len(f), 2)] h = list(map(itemgetter(-1), g)) k = [] for x in g: if any(int(i) &gt;= 1 for i in h): y = x else: y = x[:-1].strip(',') k.append(y) print(k) Results are: ubuntu = ['3/:7,3,None', '2/:5,None,5', '3/0:None,3,7', '/0:10,None,0', '5/0:2,None,8'] spyder = ['3/:7,3,0', '2/:5,0,5', '3/0:0,3,7', '/0:10,0,0', '5/0:2,0,8'] The result from spyder is the correct one. Why am I getting None's instead of zero with ubuntu version? I am pretty sure there is an underlying reason and hopefully someone can help me understand this. If not, what do I do to make the ubuntu result same as the one from spyder? Thank you
score: 0

http://stackoverflow.com/a/50993003
has comment: http://stackoverflow.com/comment/89164507
has comment: http://stackoverflow.com/comment/89163045
has body: If you store the data as a dictionary you can look up the key based on the name in the csv file: data = { "A_Names" : ["Anton", "Berta", "Charlie"], "Ages" : ["32","18","23"], "Nicknames": ["Agent A", "Agent B", None], "Birthdays": ["03.03.1986", "02.02.2000", "01.01.1995"], "IDs": [100, 200, 300] } def Show_Values(): for row in rows: for n in range (0, len(data["A_Names"])): print data["A_Names"][n] for header in row: if header == "Agents" or header == "": # This field doesn't match any thing in the data. continue header = header.strip() header += "s" print " %s: %s" % (header, data[header][n]) Since the data is now in a dict we can look up the value based on the parameter which we got from the file. I probably should have called it "parameter" rather than "header". Show_Values() Output: Anton A_Names: Anton Ages: 32 Nicknames: Agent A Birthdays: 03.03.1986 Berta A_Names: Berta Ages: 18 Nicknames: Agent B Birthdays: 02.02.2000 Charlie A_Names: Charlie Ages: 23 Nicknames: None Birthdays: 01.01.1995 And then from the second row in the .csv: Anton Nicknames: Agent A A_Names: Anton IDs: 100 Berta Nicknames: Agent B A_Names: Berta IDs: 200 Charlie Nicknames: None A_Names: Charlie IDs: 300
accepted answer of: http://stackoverflow.com/q/50990679
has comment: http://stackoverflow.com/comment/89164645
has comment: http://stackoverflow.com/comment/89163167
score: 0
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/89164778
has comment: http://stackoverflow.com/comment/89163196
answers question: http://stackoverflow.com/q/50990679

http://stackoverflow.com/q/50996494
has comment: http://stackoverflow.com/comment/88987376
type: Question
has answer: http://stackoverflow.com/a/50996525
tagged with: if-statement
has title: Error with my boolean if statement (Django)
has answer: http://stackoverflow.com/a/50996512
tagged with: boolean
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/50996525
tagged with: python
has body: I am building a table like the following: List of car parts available: Name Price {% for product in products_list %} {{ product.name }} ${{ product.price }} {% if product.in_cart == False: %} Add to cart {% else %} {{ print('')}} {% endfor %} I would like to say if the product's value for in_cart is False (meaning it is not in cart), then add a link to the cart url. However I get this error: Could not parse the remainder: ':' from 'False:' Then, how can I change its value to true? This is my views: def index(request): products_list = Product.objects.all() template = loader.get_template('products/index.html') context = {'products_list': products_list} return HttpResponse(template.render(context, request)) def cart(request): cart_list = Product.objects.filter(in_cart = True) template_cart = loader.get_template('cart/cart.html') context = {'cart_list': cart_list} return HttpResponse(template_cart.render(context, request)) Thanks!
type: AnsweredQuestion
tagged with: django
accepted answer: http://stackoverflow.com/a/50996512

django-templates
tags question: http://stackoverflow.com/q/50891705
tags question: http://stackoverflow.com/q/50869399
tags question: http://stackoverflow.com/q/50989048
tags question: http://stackoverflow.com/q/50984980
tags question: http://stackoverflow.com/q/50962903
tag name: django-templates
tags question: http://stackoverflow.com/q/50900353
tags question: http://stackoverflow.com/q/50870950
type: Tag
tags question: http://stackoverflow.com/q/51000385
tags question: http://stackoverflow.com/q/50954875
tags question: http://stackoverflow.com/q/50982334
tags question: http://stackoverflow.com/q/50909083
tags question: http://stackoverflow.com/q/51009667

http://stackoverflow.com/q/50971914
accepted answer: http://stackoverflow.com/a/50972311
favorite count: 0
score: 13
tagged with: python
possible better answer: http://stackoverflow.com/a/64599009
answer count: 4
upvote count: 13
has answer: http://stackoverflow.com/a/78459227
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/64599009
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/64625436
tagged with: pandas
tagged with: shapely
has body: I have a function that outputs a grid of points as x and y numpy arrays for interpolation, but before I interpolate, I want to use Geopandas to perform an intersection with my research boundary (otherwise half of my interpolation points fall in the ocean). I'm generating points like this: import geopandas as gpd import numpy as np import matplotlib.pyplot as plt from shapely.geometry import Point x = np.linspace(0,100,100) y = np.linspace(0,100,100) x, y = np.meshgrid(x, y) x, y = x.flatten(), y.flatten() f, ax = plt.subplots() plt.scatter(x, y) plt.axis('equal') plt.show() Is there an efficient way to convert these numpy arrays to shapely.Point([x, y]) so they can be placed in a geopandas geodataframe? This is my current approach: interp_points = [] index = 0 y_list = yi.tolist() for x in xi.tolist(): interp_points.append(Point(x,y_list[index])) index += 1 But it seems like converting to lists and then iterating is likely not a good approach for performance, and I have approximately 160,000 points.
tagged with: geopandas
downvote count: 0
has title: What is the most efficient way to convert numpy arrays to Shapely Points?
has answer: http://stackoverflow.com/a/50972311

http://stackoverflow.com/a/50928807
has body: I suggest to filter the input lists for standard structure and valid IP before doing the split and join, as below: #testasplilist.py def validate_ip(s): a = s.split('.') if len(a) != 4: return False for x in a: if not x.isdigit(): return False i = int(x) if i &lt; 0 or i &gt; 255: return False return True #input data temp = [['1979', '74.6.160.107'], ['1979', '216.115.100.123'], ['1979', '216.115.100.124'], ['1979', '74.6.160.106'], ['1979', '192.168.1.33'], ['1979', '74.6.160.106'], ['1979', '216.115.100.124'], ['1979', '216.115.100.123'], ['1979', '74.6.160.107'], ['1979', '192.168.1.24'], ['1979', '127.0.0.1'], ['1979', '192.168.1.24'], ['1979', '127.0.0.1'], ['1979', '192.168.1.118'], ['1979', '8.8.8.8'], ['1979', '64.14.29.250'], ['1979', '64.14.29.252'], ['1979', '64.14.29.251'], ['1979', '64.14.29.50'], ['1979', '192.168.1.11'], ['1979', '8.8.8.8'], ['1979', '2404', '6800', '4007'], ['1979', '192.168.1.24'], ['1979', '127.0.0.1'], ['1979']] dates = ['Jun 15 16:26:21', 'Jun 15 16:26:21', 'Jun 15 16:26:21', 'Jun 15 16:26:21', 'Jun 15 16:26:21', 'Jun 15 16:26:21', 'Jun 15 16:26:21', 'Jun 15 16:26:21', 'Jun 15 16:26:21', 'Jun 15 16:26:23', 'Jun 15 16:26:23', 'Jun 15 16:26:30', 'Jun 15 16:26:30', 'Jun 15 16:26:32', 'Jun 15 16:26:32', 'Jun 15 16:26:32', 'Jun 15 16:26:32', 'Jun 15 16:26:32', 'Jun 15 16:26:32', 'Jun 15 16:26:33', 'Jun 15 16:26:33', 'Jun 15 16:26:33', 'Jun 15 16:26:37', 'Jun 15 16:26:38', 'Jun 15 16:26:38'] # filter temp for valid IP c= [] for x in temp: if (len(x) == 2) and validate_ip(x[1]): c.append(x) print(c) #filter dates for valid IP d=[] for x,y in zip(temp, dates): if (len(x) == 2) and validate_ip(x[1]): d.append(y) print(d) a = [x[0] for x in c] b = [x[1] for x in c] print(a) print(b) print(len(c)) print (len(d)) finalResult = [[x, y] for x, y in zip(d, b)] print(finalResult) Results: [['1979', '74.6.160.107'], ['1979', '216.115.100.123'], ['1979', '216.115.100.124'], ['1979', '74.6.160.106'], ['1979', '192.168.1.33'], ['1979', '74.6.160.106…
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50926951

http://stackoverflow.com/comment/88761298
type: QuestionComment
comment on: http://stackoverflow.com/q/50877347
score: 0
has text: It is better to use google official speech recognition/speech synthesis api instead. Or even dialogflow.
type: Comment

http://stackoverflow.com/comment/88965482
score: 0
comment on: http://stackoverflow.com/q/50983959
type: Comment
type: QuestionComment
has text: Grmph... code in question says `print(json.dumps(d, ensure_ascii=False))` while error says `print(json.dumps(d).encode("latin-1"))`. Ok it does not change much because the error is in the `dumps` call but please **keep source and error message coherent**

http://stackoverflow.com/comment/137279968
has text: That's because you are not passing the root message to MessageToJson.
comment on: http://stackoverflow.com/a/68652598
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/88804440
comment on: http://stackoverflow.com/a/50894708
type: AnswerComment
score: 0
type: Comment
has text: @Zim If the ranges are always (1-3, 4-5, 6) then my condensed table can be simplified since it doesn't need to store last_n0.

http://stackoverflow.com/comment/88880818
comment on: http://stackoverflow.com/a/50940755
type: Comment
has text: Add some description to your answer so that any user can understand
type: AnswerComment
score: 0

django-rest-auth
tag name: django-rest-auth
type: Tag
tags question: http://stackoverflow.com/q/50893756
tags question: http://stackoverflow.com/q/50862127

http://stackoverflow.com/q/50950575
tagged with: python
has comment: http://stackoverflow.com/comment/88898908
has comment: http://stackoverflow.com/comment/88899277
has answer: http://stackoverflow.com/a/50950839
downvote count: 1
has comment: http://stackoverflow.com/comment/88899025
tagged with: recursion
type: AnsweredQuestion
tagged with: list
tagged with: sum
score: -1
accepted answer: http://stackoverflow.com/a/50950839
type: Question
answer count: 3
upvote count: 0
has comment: http://stackoverflow.com/comment/88899111
has title: Python: sum of List (recursive function) with starting point p
has answer: http://stackoverflow.com/a/50952494
favorite count: 0
has comment: http://stackoverflow.com/comment/88899189
has body: I got stuck by finding out how to build a recursive function that sums the elements in a list form a specific starting point to the end of the list. for example when list a[1,2,3,4,5,6,7,8,9,10] and starting point is Index 5 I want to get the sum of 6+7+8+9+10. For me it is quite difficult to understand the whole concept of recursive functions. Maybe you can help me to get a step further understanding the concept. Many thanks in advance
possible better answer: http://stackoverflow.com/a/50950998
has comment: http://stackoverflow.com/comment/88899311
has answer: http://stackoverflow.com/a/50950998

http://stackoverflow.com/q/50927915
has comment: http://stackoverflow.com/comment/125349116
tagged with: python
score: 1
type: Question
upvote count: 2
duplicate of: http://stackoverflow.com/q/2736255
linked to: http://stackoverflow.com/q/51055750
has title: Defining abstract properties in Python
favorite count: 0
tagged with: class
downvote count: 1
has body: I want to define an abstract class in python 3.6 that enforces the presence of certain properties. From the docs it appears that you have to define abstract properties as getter/setter functions, even if you don't intend to use getter/setter functions with the properties. Following the recipe in the docs I created an abstract class with two properties : name and description. One read/write the other read only. import abc class AbstractTestClass(abc.ABC): def __init__(self): """ Constructor """ pass def __repr__(self): return 'AbstractTestClass' @property @abc.abstractmethod def name(self): return 'Not defined' @name.setter @abc.abstractmethod def name(self): pass @property @abc.abstractmethod def description(self): return 'Not defined' What I wanted was to be able to create a class based on the abstract class in a simple manner like this: class ConcreteClass1(AbstractTestClass): """ Simple class definition """ def __init__(self): # Set values to properties using simple assignment self.name = 'Concrete class 1' self.description = 'Concrete class 1 description' I just want to make sure that the name and description properties have always been defined. However if I create an instance of this class then it throws the error class1 = ConcreteClass1() TypeError: Can't instantiate abstract class ConcreteClass1 with abstract methods description, name As an exercise I created another class from the abstract one: class ConcreteClass2(AbstractTestClass): """ This class works but it's not what I want """ def __init__(self): # define private variable for name self._name = 'Concrete class 2' @property def name(self): return self._name @name.setter def name(self,value): self._name = value @property def description(self): return 'Concrete class 2 description' This works, it instantiates, but it's ugly and verbose, and it feels like the abstract class is not helping me. Is there a way to implement something more like ConcreteClass1 that's concise and streamlined? Or do I just put the…
linked to: http://stackoverflow.com/q/2736255
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/50866610
accepted answer of: http://stackoverflow.com/q/50866586
answers question: http://stackoverflow.com/q/50866586
type: Answer
has body: Just add another mean: df.groupby('A').C.mean().mean()
upvote count: 1
score: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/88728471
score: 0
type: Comment
type: QuestionComment
has text: The `ForeignObjectRel` doesn't have a `rel` property to access the model you should use the `field.remote_field.model`
comment on: http://stackoverflow.com/q/50862141

http://stackoverflow.com/comment/88997748
type: AnswerComment
score: 0
type: Comment
has text: @MelvinAbraham, yes, and the "ntpq" lines are in the middle of over 100+ lines in each file
comment on: http://stackoverflow.com/a/51000977

http://stackoverflow.com/a/50859785
has body: why you put NULL in book VALUES (NULL,?,?,?,?) ? try without NULL cur.execute("INSERT INTO book VALUES (?,?,?,?)" ,(title,author,year,isbn))
has comment: http://stackoverflow.com/comment/88723020
has comment: http://stackoverflow.com/comment/88722589
has comment: http://stackoverflow.com/comment/88723459
has comment: http://stackoverflow.com/comment/88724883
score: 0
has comment: http://stackoverflow.com/comment/88739216
has comment: http://stackoverflow.com/comment/88723933
answers question: http://stackoverflow.com/q/50859698
type: Answer
has comment: http://stackoverflow.com/comment/88739720

http://stackoverflow.com/comment/88976070
type: AnswerComment
has text: I think you will need to (re)nstall scrapy with pip3 to get it available under python3
type: Comment
comment on: http://stackoverflow.com/a/50989419
score: 0

http://stackoverflow.com/comment/89117780
has text: @HoseongJeon Ok, good, already answered, didn't know there was a limitation between asked questions when having low-rep
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50887311

http://stackoverflow.com/comment/88954849
type: Comment
type: QuestionComment
has text: Very interesting. Can you explain better what you want in the last step. Do you want to color balance or do you want to reduce the overall number of colors?
score: 0
comment on: http://stackoverflow.com/q/50972401

http://stackoverflow.com/comment/88780943
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50884533
has text: For both functions, the `singular values` (`s`) is the main thing they promise. The k largest `s` values match. SVD is not unique. https://en.wikipedia.org/wiki/Singular-value_decomposition#Calculating_the_SVD

http://stackoverflow.com/q/50939773
favorite count: 0
tagged with: class
has answer: http://stackoverflow.com/a/50939813
type: Question
has answer: http://stackoverflow.com/a/50944849
tagged with: python
tagged with: rules
has body: I'm currently using the FuncAnimation function of matplotlib and encountered an issue. My code follows a similar logic to the code below import matplotlib.animation as animation import matplotlib.pyplot as plt class Example: def __init__(self): self.fig = plt.figure() def update(self, num): print("This is getting called") def animate(self): ani = animation.FuncAnimation(self.fig, update, interval=100) def main(): obj = Example() obj.animate() if __name__ == "__main__": main() At the moment, my code doesn't print out "This is getting called". I tried passing in self.update instead of update into FuncAnimation, to no avail. I also tried writing global update before calling FuncAnimation, which also doesn't work. I'm wondering if anybody can help me.
upvote count: 2
answer count: 2
tagged with: parameters
accepted answer: http://stackoverflow.com/a/50944849
tagged with: matplotlib
has title: Python: passing a function as a parameter while in a class
type: AnsweredQuestion
score: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/50939813

http://stackoverflow.com/q/50915020
upvote count: 1
type: Question
answer count: 2
has body: I am a biology student trying to get into programming and have some issue with a basic index calculator I am trying to write for a research project. I need a program that will prompt the user to input data points one at a time, perform the proper calculation (-1*(x*ln(x))) on each data point, and enter that new calculated value into an array. Once the user inputs 'done', I would like the program to sum the array values and return that index value. This is what I have. I am very new so apologies for any blaring mistakes. Any points in the right direction are very appreciated. import math print('This program calculates a Shannon Diversity ' 'Index value for a set of data points entered by the user.' ' when prompted enter a species number value,then press enter. ' 'COntinue until all data points have been entered. ' 'Upon completion, enter the word done.') def Shannonindex(): index = [] entries = 1,000,000 endKey = 'done' for i in range(entries): index = [input("Enter a value: ")] if index != endKey: entry = p p = -1*(x*ln(x)) index.append(p) else Sindex = sum(index) return Sindex print('Your Shannon Diversity Value is: ", Sindex)
downvote count: 0
has title: Shannon Diversity Program: basic questions
has answer: http://stackoverflow.com/a/50915144
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50915433
tagged with: python
tagged with: calculation
tagged with: indexing
score: 1

http://stackoverflow.com/comment/88965039
type: Comment
has text: Worked. Thanks :)
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50984990

http://stackoverflow.com/q/50928942
tagged with: python
tagged with: matplotlib-basemap
favorite count: 0
has comment: http://stackoverflow.com/comment/88922777
downvote count: 0
has comment: http://stackoverflow.com/comment/88927188
has answer: http://stackoverflow.com/a/50965764
accepted answer: http://stackoverflow.com/a/50965764
has comment: http://stackoverflow.com/comment/88924493
type: AnsweredQuestion
score: 3
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/88922729
type: Question
has body: The code below is supposed to colour all the states of Vietnam: import pandas as pd import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap fig, ax = plt.subplots(figsize=(10,20)) # create the map map = Basemap(resolution='l', # c, l, i, h, f or None projection='merc', lat_0=15.95, lon_0=105.85, llcrnrlon=102., llcrnrlat= 8.31, urcrnrlon=109.69, urcrnrlat=23.61) # load the shapefile, use the name 'states' map.readshapefile(r'path\to\gadm36_VNM_1', name='states', drawbounds=True) # shapefile downloaded from http://www.gadm.org/ # collect the state names from the shapefile attributes so we can # look up the shape obect for a state by it's name state_names = [] for shape_dict in map.states_info: state_names.append(shape_dict['VARNAME_1']) ax = plt.gca() # get current axes instance # NOR, CEN, SOU and MEK are some subdivisions I have created for the states of Vietnam NOR = ['Lai Chau', 'Lao Cai', 'Ha Giang', 'Cao Bang', 'Dien Bien', 'Son La', 'Yen Bai', 'Tuyen Quang', 'Bac Kan', 'Lang Son', 'Thai Nguyen', 'Phu Tho', 'Vinh Phuc', 'Hoa Binh', 'Ha Noi', 'Bac Ninh', 'Hai Duong', 'Hung Yen', 'Ha Nam', 'Quang Ninh', 'Hai Phong', 'Thai Binh', 'Nam Dinh', 'Bac Giang', 'Ninh Binh'] CEN = ['Thanh Hoa', 'Nghe An', 'Ha Tinh', 'Quang Binh', 'Quang Tri', 'Thua Thien Hue', 'Da Nang'] SOU = ['Quang Nam', 'Kon Tum', 'Quang Ngai', 'Gia Lai', 'Binh Dinh', 'Dak Lak', 'Phu Yen', 'Khanh Hoa', 'Dak Nong', 'Lam Dong', 'Ninh Thuan'] MEK = ['Binh Phuoc', 'Dong Nai', 'Binh Thuan', 'Tay Ninh', 'Binh Duong', 'Dong Nai', 'Ba Ria - Vung Tau', 'Ho Chi Minh', 'Long An', 'An Giang', 'Dong Thap', 'Tien Giang', 'Kien Giang', 'Can Tho', 'Vinh Long', 'Ben Tre', 'Hau Giang', 'Tra Vinh', 'Soc Trang', 'Bac Lieu', 'Ca Mau'] # Define the colours to be used to colour the states from matplotlib import cm from numpy import linspace start = 0.5 stop = 1.0 number_of_lines= 4 cm_subsection = linspace(start, stop, number_of_lines) cm_subsection[0] = cm_subsection[0]*4 cm_subsection[1] = cm_subsection[1…
answer count: 1
upvote count: 3
tagged with: colors
tagged with: data-visualization
has title: Why is matplotlib basemap not plotting the colours of some areas in my map?

http://stackoverflow.com/a/50920142
has comment: http://stackoverflow.com/comment/88853874
score: 0
has comment: http://stackoverflow.com/comment/88840365
type: Answer
has body: Use Substr to separate out the first part of the name from the numbers at the end, and then sort by this new annotation first. from django.db.models.functions import Substr, Length qs = qs.annotate(letters=Substr('name', 1, 6), length=Length('name')) qs = qs.order_by('letters', 'length', 'name') return qs
answers question: http://stackoverflow.com/q/50892879

regex
tags question: http://stackoverflow.com/q/50923981
tags question: http://stackoverflow.com/q/50904500
tags question: http://stackoverflow.com/q/50954029
tags question: http://stackoverflow.com/q/50907435
tags question: http://stackoverflow.com/q/50971337
tags question: http://stackoverflow.com/q/50900038
tags question: http://stackoverflow.com/q/50971208
tags question: http://stackoverflow.com/q/50995512
tags question: http://stackoverflow.com/q/50914959
tags question: http://stackoverflow.com/q/50999017
tags question: http://stackoverflow.com/q/50943178
tags question: http://stackoverflow.com/q/50867620
tags question: http://stackoverflow.com/q/50949764
tags question: http://stackoverflow.com/q/50934807
tags question: http://stackoverflow.com/q/50878549
tags question: http://stackoverflow.com/q/50939145
tags question: http://stackoverflow.com/q/50947760
tag name: regex
tags question: http://stackoverflow.com/q/50904668
tags question: http://stackoverflow.com/q/50871254
tags question: http://stackoverflow.com/q/50938835
tags question: http://stackoverflow.com/q/50865953
tags question: http://stackoverflow.com/q/50994051
tags question: http://stackoverflow.com/q/50902252
tags question: http://stackoverflow.com/q/50986671
tags question: http://stackoverflow.com/q/50907064
tags question: http://stackoverflow.com/q/50864642
tags question: http://stackoverflow.com/q/50965287
tags question: http://stackoverflow.com/q/50971834
tags question: http://stackoverflow.com/q/50982397
tags question: http://stackoverflow.com/q/50887460
tags question: http://stackoverflow.com/q/50963346
tags question: http://stackoverflow.com/q/51005760
tags question: http://stackoverflow.com/q/50979572
tags question: http://stackoverflow.com/q/50983308
tags question: http://stackoverflow.com/q/50939856
tags question: http://stackoverflow.com/q/50857600
tags question: http://stackoverflow.com/q/50882796
tags question: http://stackoverflow.com/q/50916898
tags question: http://stackoverflow.com/q/50926012
tags question: http://stackoverflow.com/q/50950593
tags question: http://stackoverflow.com/q/50964844
tags question: http://stackoverflow.com/q/50992910
tags question: http://stackoverflow.com/q/50984777
tags question: http://stackoverflow.com/q/50981036
tags question: http://stackoverflow.com/q/50924879
tags question: http://stackoverflow.com/q/50966211
tags question: http://stackoverflow.com/q/50955069
tags question: http://stackoverflow.com/q/50879231
tags question: http://stackoverflow.com/q/50978660
tags question: http://stackoverflow.com/q/50875028
tags question: http://stackoverflow.com/q/50993773
tags question: http://stackoverflow.com/q/50920791
tags question: http://stackoverflow.com/q/50872574
tags question: http://stackoverflow.com/q/50926792
tags question: http://stackoverflow.com/q/50900813
tags question: http://stackoverflow.com/q/50907940
tags question: http://stackoverflow.com/q/51004201
tags question: http://stackoverflow.com/q/50982111
tags question: http://stackoverflow.com/q/50933454
tags question: http://stackoverflow.com/q/50878529
tags question: http://stackoverflow.com/q/50863706
tags question: http://stackoverflow.com/q/50871905
tags question: http://stackoverflow.com/q/50905066
tags question: http://stackoverflow.com/q/50855941
tags question: http://stackoverflow.com/q/51005874
tags question: http://stackoverflow.com/q/51001899
tags question: http://stackoverflow.com/q/50990333
tags question: http://stackoverflow.com/q/50930119
tags question: http://stackoverflow.com/q/51006347
tags question: http://stackoverflow.com/q/50888483
tags question: http://stackoverflow.com/q/50874061
tags question: http://stackoverflow.com/q/50915360
tags question: http://stackoverflow.com/q/50919509
tags question: http://stackoverflow.com/q/50889565
tags question: http://stackoverflow.com/q/50885202
tags question: http://stackoverflow.com/q/50878527
tags question: http://stackoverflow.com/q/50928430
tags question: http://stackoverflow.com/q/51000342
tags question: http://stackoverflow.com/q/50870470

http://stackoverflow.com/comment/88762922
score: 1
has text: @user48956: I've added a method in my answer that'll let you find out!
comment on: http://stackoverflow.com/q/50880121
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50954147
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88906132
has comment: http://stackoverflow.com/comment/88906395
has answer: http://stackoverflow.com/a/50954696
upvote count: 1
downvote count: 1
linked to: http://stackoverflow.com/q/39980323
type: Question
possible better answer: http://stackoverflow.com/a/50954696
tagged with: if-statement
has comment: http://stackoverflow.com/comment/88906138
has body: I know how to use a dictionary as a switcher in Python. I'm not sure how to use one for my specific case. I think I will just need to use if, elif, and else but hopefully I am proved wrong by the community :) I want to make a find/replace function for certain characters in strings. The string is at least one sentence but usually more and comprised of many words. Basically what I am doing is the following: if non-breaking hyphen in string: # string is a sentence with many words replace non-breaking hyphen with dash elif en dash in string: replace en dash with dash elif em dash in string: replace em dash with dash elif non-breaking space in string: replace non-breaking space with space .... and so forth The only thing I can think of is splitting the string apart into separate sub-strings and then looping through them then the dictionary switcher would work. But this would obviously add a lot of extra processing time and the purpose of using a dictionary switcher is to save time. I could not find anything on this specific topic searching everywhere. Is there a way to use a switcher in Python using if in and elif in?
has answer: http://stackoverflow.com/a/50954481
has comment: http://stackoverflow.com/comment/88906108
has comment: http://stackoverflow.com/comment/88907383
has title: Python 3+ Is It Possible to Replace if in and elif in Using a Switcher
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/88906200
has answer: http://stackoverflow.com/a/50954625
has comment: http://stackoverflow.com/comment/88906227
has comment: http://stackoverflow.com/comment/88906080
tagged with: switchers
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/50954481
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/88906475

marker
tag name: marker
tags question: http://stackoverflow.com/q/50956968
type: Tag

http://stackoverflow.com/a/50916061
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/50914959
has body: This problem can be solved much more easily using negative lookbehind assertions. COEFFICIENT_PATTERN = re.compile(r"(?&lt;!x\^)(?&lt;!x\^-)-?\d+") coefficients = [int(c) for c in COEFFICIENT_PATTERN.findall(polynomial)] This solution uses two negative lookbehinds for x^ and x^- (because look behinds must be fixed length). So it reads "get me all integers not preceded by x^. &gt;&gt;&gt; COEFFICIENT_PATTERN.findall('2x^3+4x^2+8x-16') ['2', '4', '8', '-16']
answers question: http://stackoverflow.com/q/50914959
has comment: http://stackoverflow.com/comment/88832589
upvote count: 1
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/q/50869654
has comment: http://stackoverflow.com/comment/88741536
linked to: http://stackoverflow.com/q/6760685
tagged with: python
has title: Creating class instance within a loop and updating it
has comment: http://stackoverflow.com/comment/88742097
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/50870173
tagged with: loops
type: Question
tagged with: oop
has answer: http://stackoverflow.com/a/50870173
has body: Let's say I have a dataset ('test.csv') like so: Name,Fruit,Price John,Apple,1.00 Steve,Apple,1.00 John,Mango,2.00 Adam,Apple,1.00 Steve,Banana,1.00 Although there are several easier ways to do this, I would like to organize this information as a class in python. So, ideally, an instance of a class would look like: {'name': 'John', 'Fruits': ['Apple','Mango'], 'Price':[1.00, 2.00]} My approach to loading the dataset into a class is to store each instance in a list. class org(object): def __init__(self,name,fruit,price): self.name = name self.fruit = [fruit] self.price = [price] classes = [] with open('test.csv') as f: for line in f: if not 'Name' in line: linesp=line.rstrip().split(',') name = linesp[0] fruit = linesp[1] price = linesp[2] inst = org(name,fruit,price) classes.append(inst) for c in classes: print (c.__dict__) In this case, how do I know if 'John' already exists as an instance? If so, how do I update 'John'? With a classmethod? @classmethod def update(cls, value): cls.fruit.append(fruit)
tagged with: class
has comment: http://stackoverflow.com/comment/88742482
upvote count: 1
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/88944703
type: Comment
type: QuestionComment
score: 2
has text: `await bot.send_message(member, "Hi {} how are you.".format(member.name))` should do it. You can see the docs for `User` (which is the parent class of `Member`) [here](http://discordpy.readthedocs.io/en/latest/api.html#discord.User).
comment on: http://stackoverflow.com/q/50974212

http://stackoverflow.com/q/50868676
tagged with: python
tagged with: build
answer count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/88754045
has comment: http://stackoverflow.com/comment/88771617
has comment: http://stackoverflow.com/comment/88751163
has title: Python: conditional build depending on environment
type: UnansweredQuestion
has body: Using distutils, how can I make a conditional build depending on the environment. I have two versions of a script, which I am going to use as an entry point. Depending on whether mpich is installed or not, I want to use one of them. It could be easily done with Makefiles in the C-family projects (see this feature), I expect similar tool for Python. By doing conditional builds, I am trying to avoid an error that arises when I am trying to launch a script that uses mpi functions in the system where mpi is not installed. Is it possible to check if mpich is installed during the build procedure - for instance in the setup configuration file - and pick the right version of the script as an entry point?
tagged with: distutils
downvote count: 0
score: 1
favorite count: 0
tagged with: software-distribution
type: Question
tagged with: mpi

http://stackoverflow.com/q/50911128
tagged with: tkinter
score: 0
has title: python notebook classes -- how to place data on the tab pages when classes were used
answer count: 0
has body: New python user here. I apologize for not being able to figure this out. I am doing a GUI application which has menu bars and notebook tabs, and wish to use classes. I found some code which does this and modified it. It appears to my untrained eye that the classes instantiate themselves rather than having a definition and separate instantiation and useage in main code. In the end I want to be able to place graphs and tables on eached tabbed space. But I cannot figure out how to do this. import tkinter as tk from tkinter import ttk import mdrparse_foidev_for_frn_only as maude #from tkinter import user class Root(tk.Tk): """Container for all frames within the application""" def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) #initialize menu self.config(menu=MenuBar(self)) self.geometry("1500x500") self.appFrame = Application(self) self.appFrame.pack(side='top', fill='both', expand='True') self.status = StatusBar(self) self.status.pack(side='bottom', fill='x') class MenuBar(tk.Menu): def __init__(self, parent): tk.Menu.__init__(self, parent) pumpmenu = tk.Menu(self, tearoff=False) self.add_cascade(label="Pump",underline=0, menu=pumpmenu) pumpmenu.add_command(label="Spectrum", command=self.callback) pumpmenu.add_separator() pumpmenu.add_command(label="Sappphire", underline=1, command=self.callback) yearmenu = tk.Menu(self, tearoff=False) self.add_cascade(label="Year", menu=yearmenu) yearmenu.add_command(label="2018...", command=self.callback) yearmenu.add_separator() yearmenu.add_command(label="2017", underline=1, command=self.callback) helpmenu = tk.Menu(self, tearoff=False) self.add_cascade(label="Help", menu=helpmenu) helpmenu.add_command(label="About...", command=self.callback) # ============================================================================= # def quit(self): # sys.exit(0) # ============================================================================= def callback(self): maude.parse_maude_file print ("Parsed the file") class St…
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88857670
tagged with: class
has comment: http://stackoverflow.com/comment/88866039
type: Question
tagged with: python

http://stackoverflow.com/comment/88866245
type: QuestionComment
comment on: http://stackoverflow.com/q/50925618
has text: I'm not sure, look at the answer to that post : https://stackoverflow.com/questions/32538758/nameerror-name-get-ipython-is-not-defined What do you think ?
score: 0
type: Comment

http://stackoverflow.com/q/50873875
has answer: http://stackoverflow.com/a/50874198
has title: Proper way to implement ABC SubClass
downvote count: 0
has answer: http://stackoverflow.com/a/50874130
has body: I have an Interface class which defines the requirements to an active "in-use" class: class Portfolio(ABC): @abstractmethod def update_portfolio(self): raise NotImplementedError @abstractmethod def update_from_fill(self): raise NotImplementedError @abstractmethod def check_signal(self, signal_event): raise NotImplementedError The methods update_portfolio and update_from_fill are both methods which will be the same in 99% of the required cases. Only the check_signal method will vary. Therefore, to avoid having to write the same code again and again, I have defined a base class with default methods for update_portfolio and update_from_fill: class BaseBacktestPortfolio(Portfolio): def __init__(self, ...): ... def update_portfolio(self, ...): ... def update_from_fill(self, ...): ... Then, finally, I have a class inheriting from the BacktestPortfolio class which specifies the correct implementation of the check_signal method: class USBacktestPortfolio(BaseBacktestPortfolio): def check_signal(self, ...): ... Now, the problem is that my editor complains about the BacktestPortfolio classing not having all the required abstract methods. I could ignore this, of course, but the perfect scenario would be if I could make sure that it is not possible to instantiate an object form the BacktestPortfolio class. Is this possible? And/or is there a more correct way to implement a structure like this?
favorite count: 0
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/50874198
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88750063
upvote count: 2
accepted answer: http://stackoverflow.com/a/50874130
type: Question
tagged with: abstract-class
answer count: 2
score: 2

http://stackoverflow.com/comment/88832254
score: 2
comment on: http://stackoverflow.com/q/50916071
has text: If this random person's unofficial Instagram interface module is low-quality and swallows exceptions to print to stdout, have you considered not using it, or forking it?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50919800
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50932585
tagged with: tkinter
upvote count: 1
has comment: http://stackoverflow.com/comment/88840241
type: Question
has body: This is the short form of my code. In [input] window, I want it to pop up the [input2] window only and the [solve] window will pop up after I hit the button Solve!. Currently, however, the [input2] and [solve] windows pop-up at the same time and the Solve! button doesn't do anything when it's clicked. This is my code: from tkinter import * class welcome(): def __init__(self, master): #master: root - the main window # welcome and introduction self.master=master self.master.geometry("500x200") self.welcome = Label(self.master, text="Welcome to The Bees's") self.welcome.pack() self.intro = Label(self.master, text="This is our project for Python course") self.intro.pack() self.intro2 = Label(self.master, text="This program is use for solving Linear Programming, IP, BIP, mixed... problem") self.intro2.pack() self.startbutton = Button(self.master, text="Start", bg="yellow") self.startbutton.pack() self.startbutton.config(command=self.gotoinput) def gotoinput(self): root2 = Toplevel(self.master) self.input1=input(root2) Class for input window: class input(): def __init__(self,master): self.master=master self.master.title("Input") self.master.geometry("700x500") #cancle self.Canclebutton=Button(self.master,text="Cancle",command=self.master.destroy).grid(row=3,column=1) #OK self.Enterbutton=Button(self.master,text="ENTER",command=self.gotoinput2).grid(row=3,column=2) def gotoinput2(self): root3=Toplevel(self.master) self.input22=input2(root3) Class for input2 window: class input2(): def __init__(self,master): self.master=master self.master.title("Input2") self.master.geometry("700x500") # cancle self.Canclebutton = Button(self.master, text="Cancle", command=self.master.destroy).grid(row=0, column=0) # OK self.Solvebutton = Button(self.master, text="Solve!", command=self.gotosolve()).grid(row=0, column=1) print("Through") def gotosolve(self): print("gotosolve") root4=Toplevel(self.master) self.solve11=solve(root4) Class for Solve window: class solve(): def __init__(self,maste…
accepted answer: http://stackoverflow.com/a/50932585
tagged with: toplevel
answer count: 1
tagged with: window
downvote count: 0
score: 1
favorite count: 0
tagged with: python-3.x
tagged with: python
has title: How to control display of tkinter Toplevel windows?
has comment: http://stackoverflow.com/comment/88840694

http://stackoverflow.com/comment/88986692
comment on: http://stackoverflow.com/a/50995229
has text: Basically I want to use regular expression to grab the interest rates on the 5 websites I have listed. I updated my post above with the updated code/output. The outputs with the "%" have the exact outputs I want. But now I am trying to figure out why there are so many outputs with only 5 websites, and why my regex is ignoring the or operator I have in place on there.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/50952044
has comment: http://stackoverflow.com/comment/88902272
accepted answer of: http://stackoverflow.com/q/50951964
type: Answer
answers question: http://stackoverflow.com/q/50951964
has comment: http://stackoverflow.com/comment/88902252
downvote count: 0
score: 3
upvote count: 3
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88901847
has body: You can use a dictionary to link to logic already defined: a = [12,34,2,3,4,23,16,84,3] def myfun(X): return([max(X),min(X),sum(X)]) dispatcher = {'max_min_sum': myfun} b = input('Enter a dispatcher key:\n') print(dispatcher[b](a)) Demo input / output: Enter a dispatcher key: max_min_sum [84, 2, 181]

http://stackoverflow.com/comment/88777760
type: Comment
comment on: http://stackoverflow.com/a/50888138
score: 1
type: AnswerComment
has text: Joyful example.

http://stackoverflow.com/comment/88877427
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50939381
has text: Did you try this: https://gist.github.com/fzakaria/2472889

http://stackoverflow.com/comment/88836714
type: Comment
comment on: http://stackoverflow.com/a/50917584
score: 1
has text: @J.S. You don't need `ffplay` to view stream. You can write it to file by: `ffmpeg -i udp://127.0.0.1:5000 ./out.mp4`.
type: AnswerComment

http://stackoverflow.com/comment/88974764
comment on: http://stackoverflow.com/q/50989767
score: 0
has text: So for first axis I will hide left spines for 2nd right and what for third?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50914729
has title: Gensim Word2Vec select minor set of word vectors from pretrained model
possible better answer: http://stackoverflow.com/a/50916669
has answer: http://stackoverflow.com/a/66210546
tagged with: keras
favorite count: 0
answer count: 3
linked to: http://stackoverflow.com/q/48941648
tagged with: word-embedding
accepted answer: http://stackoverflow.com/a/55725093
tagged with: python
tagged with: gensim
has answer: http://stackoverflow.com/a/50916669
score: 8
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/55725093
tagged with: word2vec
has body: I have a large pretrained Word2Vec model in gensim from which I want to use the pretrained word vectors for an embedding layer in my Keras model. The problem is that the embedding size is enormous and I don't need most of the word vectors (because I know which words can occure as Input). So I want to get rid of them to reduce the size of my embedding layer. Is there a way to just keep desired wordvectors (including the coresponding indices!), based on a whitelist of words?
upvote count: 8
type: Question

http://stackoverflow.com/q/50993866
favorite count: 0
has answer: http://stackoverflow.com/a/50993972
has body: I have 2 pandas dataframes. Each has a dimension and a metric. I need to aggregate the metric based on the dimension in each table and join them based on the dimension. So: A dim1 met1 a 100 a 200 b 50 B dim2 met2 a 70 a 20 c 50 I use pandas.groupby() on each dataframe, but when I check the result of the groupby by doing .dtypes, I see that the dim1 dim2 is no longer present in the aggregated output. So now, when I try to join based on dim1=dim2, I get message that dim1,dim2 does not exist. What did I do wrong?
tagged with: python
has comment: http://stackoverflow.com/comment/88982393
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88982295
score: 1
type: Question
downvote count: 0
has title: Pandas group by is dropping the dimnension on which the grouping is done
accepted answer: http://stackoverflow.com/a/50993972
tagged with: pandas
upvote count: 1
answer count: 1

http://stackoverflow.com/comment/88853478
type: QuestionComment
has text: You’re only supposed to decorate your tests. What happens if you remove the decorator from `callback`?
comment on: http://stackoverflow.com/q/50926584
score: 1
type: Comment

http://stackoverflow.com/a/50913987
answers question: http://stackoverflow.com/q/50913494
upvote count: 2
has body: The data does appear to be real. This is not formally documented by Seaborn, but: Several of the dataset are "real" well-known datasets that can be verified elsewhere, such as the Iris dataset hosted on UCI's Machine Learning repository. All of the data are sourced from https://github.com/mwaskom/seaborn-data, and in turn from actual CSVs on Michael Waskom's (core Seaborn developer) local drive, it appears. If the data were random/fake, it is more likely it would be generated by Python libraries such as NumPy.
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/comment/88907931
score: 0
type: Comment
has text: No, you don't have to get rid of your question. If it gets marked as duplicate, it may hang around as another way a user's search term might come across the answer. Though, you may want to change the title to something more specific to the error and not your specific task.
type: QuestionComment
comment on: http://stackoverflow.com/q/50954813

http://stackoverflow.com/q/50904150
tagged with: raspberry-pi
tagged with: template-matching
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/52644346
has title: Movidius and Template Matching
favorite count: 0
accepted answer: http://stackoverflow.com/a/52644346
tagged with: python
type: AnsweredQuestion
score: 1
upvote count: 1
has body: Is there a way to execute template matching algorithms over the Movidius VPU ? I see that Movidius is generally used for deep learning but I need to execute some template matching algorithms which executes painfully on RPi3. Note: Deep learning is not a good option for my current situation.
type: Question

http://stackoverflow.com/comment/89075446
type: Comment
score: 0
has text: @MartinThoma the error you posted is unrelated to the `--cov-append` option - for some reason, tests are run with `unittest` instead of `pytest`. you must have changed something else to cause that.
type: AnswerComment
comment on: http://stackoverflow.com/a/51015167

http://stackoverflow.com/comment/88815821
type: QuestionComment
comment on: http://stackoverflow.com/q/50904546
score: 0
has text: Okay, I wasn't aware of your use case. `2**(S(5)/6)` is how I'd write that exponent if typing it from scratch.
type: Comment

http://stackoverflow.com/comment/88756512
comment on: http://stackoverflow.com/q/50877281
type: Comment
type: QuestionComment
has text: Perhaps the error _message_ might give you, or us, a clue?
score: 3

http://stackoverflow.com/comment/88795012
type: AnswerComment
comment on: http://stackoverflow.com/a/50897603
type: Comment
has text: @BryanOakley Given that OP has asked a question specifically using sleep, I elected to provide an answer that fits the question. I don't use tkinter but I thought that `root.update()` returns control momentarily to the main loop.
score: 0

http://stackoverflow.com/q/50916462
has body: df=pd.read_csv("C:Tasks_Revised_For_Analysis.csv") print df['Days_Spent'] Out[16]: 0 5.0 1 43.333333333333336 2 176.66666666666666 3 80.5 4 78.5 5 0.3333333333333333 print df['Start_Date'] Out[17]: 0 2015-10-29 1 2016-01-07 2 2015-10-29 3 2015-10-29 4 2015-11-01 5 2015-11-02 Days_Spent is a float of a calculated value df['Days_Spent'] = (df['ActualHours'] / 6.00) This is my best guess as to what I should do g = (df['Days_Spent']) df['Est_end'] = df['Start_Date'] + datetime.timedelta(days = g) This is the error I am receiving even tho I have datetime and timedelta imported type object 'datetime.datetime' has no attribute 'timedelta'
tagged with: datetime
accepted answer: http://stackoverflow.com/a/50916691
tagged with: python
has comment: http://stackoverflow.com/comment/88832914
has title: Adding Column value(Days_Spent), to a datetime day value in column Est_end
tagged with: addition
has answer: http://stackoverflow.com/a/50916691
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88833221
has comment: http://stackoverflow.com/comment/88833432
tagged with: function
answer count: 1
tagged with: timedelta
score: 0

http://stackoverflow.com/q/50922436
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50922480
tagged with: dataframe
type: Question
has title: How to read a csv row wise and convert to a dataframe column using pandas?
has body: My dataset CSV file is row-wise: 1,2,3,4 1000,2000,3000,4000 I want to read this file and get a dataframe output of two columns, 'index and value'. Output: index value 1 1000 2 2000 3 3000 If I want to get only the 'value' column, I should be able to retrieve them by doing df['value'] I tried going about it like this: series = pd.read_csv('file.csv',index_col=0, header=0) df= series.T Frame=pd.DataFrame([df], columns = ["index","value"]) But this yields an error: &gt; ValueError: Shape of passed values is (1, 1), indices imply (2, 1)
downvote count: 0
tagged with: pandas
answer count: 1
has answer: http://stackoverflow.com/a/50922480
score: 1
favorite count: 0
upvote count: 1

http://stackoverflow.com/q/50916382
has comment: http://stackoverflow.com/comment/88832978
has comment: http://stackoverflow.com/comment/88832890
tagged with: tkinter
answer count: 0
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/291978
has title: my button does not change the variable's value. WHY?
has body: from tkinter import * from random import randint from math import sqrt def create_bubble(): x = WIDTH + GAP y = randint(0, HEIGHT) r = randint(MIN_BUB_R, MAX_BUB_R) id1 = c.create_rectangle(x - r, y - r, x + r, y + r, outline="light blue", fill=color) bub_id.append(id1) bub_r.append(r) bub_speed.append(randint(1, MAX_BUB_SPD)) def buton(): color = 'green' HEIGHT = 500 WIDTH = 800 window = Tk() window.title("Distrugatorul de bule") c = Canvas(window, width=WIDTH, height=HEIGHT, bg="darkblue") c.pack() color = 'blue' bub_id = list() bub_r = list() bub_speed = list() MIN_BUB_R = 10 MAX_BUB_R = 30 MAX_BUB_SPD = 10 GAP = 100 b = Button(window, text="change", command = buton) b.pack() mainloop() BUB_CHANCE = 10 if randint(1, BUB_CHANCE) == 1: create_bubble() color is the variable and, when start the program and press the button the bubbles stay still blue.what should i do? does the button not work or why this is happening?
type: Question
score: 0
has comment: http://stackoverflow.com/comment/88840210
has comment: http://stackoverflow.com/comment/88832982

http://stackoverflow.com/a/50916691
type: Answer
has comment: http://stackoverflow.com/comment/88833737
accepted answer of: http://stackoverflow.com/q/50916462
answers question: http://stackoverflow.com/q/50916462
score: 0
has body: You can use pd.to_timedelta: df['Est_end'] = df['Start_Date'] + pd.to_timedelta(df['Days_Spent'], unit='D') Take into accout that unit='D' implies that 8.5 will be interpreted as "8 and a half days", or "8 days and 12 hours". You might want to round up or down the numbers first. See more in the docs.
type: AcceptedAnswer

http://stackoverflow.com/comment/88989345
score: 0
type: Comment
has text: thanks, but i can not understand the method... how to use it...did you know easy method like miniCRAN packges in R?? miniCRAN provide related packages.tar.gz considered dependencies in directed local repository.
type: AnswerComment
comment on: http://stackoverflow.com/a/50997558

http://stackoverflow.com/q/51005431
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51005981
type: AnsweredQuestion
upvote count: 3
type: Question
accepted answer: http://stackoverflow.com/a/51005981
answer count: 1
downvote count: 0
has title: Parameter values for parameter (n_neighbors) need to be a sequence
score: 3
has body: I am trying to use the Skleanr module. However, my code is below n_range = {'n_neighbors': range(1,100)} knn_search = GridSearchCV(estimator = KNeighborsClassifier(), param_grid=n_range, scoring='f1_micro') knn_search.fit(features_vector, train_labels) results the error: Parameter values for parameter (n_neighbors) need to be a sequence. What I did wrong?
tagged with: python

http://stackoverflow.com/q/50918686
tagged with: matplotlib
has answer: http://stackoverflow.com/a/50924096
has comment: http://stackoverflow.com/comment/88854381
answer count: 1
score: 0
accepted answer: http://stackoverflow.com/a/50924096
has comment: http://stackoverflow.com/comment/88854393
tagged with: python
has body: Could someone help me figure out as to why error bars are shifted a bit as compared to line histogram? I wish to have error bars at the center of each bar of line histogram. #mc and data are two dataframes. norm = np.empty_like(mc['variable']) bins=np.linspace(0,30,101) binw=bins[1]-bins[0] xc = bins[1:]-binw*0.5 hist_mc_corr,_ = np.histogram(mc['variable'].values, density=False, weights=mc['weight_mc'].values, bins=bins) hist_data,_ = np.histogram(data['variable'].values, density=False, weights=data['weight_data'].values, bins=bins) norm.fill(hist_data.sum()/hist_mc_corr.sum() ) plt.hist(mc['variable'], bins=100, range=(0, 30),histtype='step', weights=norm*mc['weight_mc'],) (_, caps, _) = plt.errorbar(xc+binw*0.5, hist_data,ls='None', yerr=np.sqrt(hist_data), xerr=np.ones_like(hist_data)*binw*0.5, color='black', label='data', marker='.') for cap in caps: cap.set_markeredgewidth(0) While it should look like (except I do not want to fill histogram with color.) Many thanks!
has title: shifted errorbar plot wrt hist plot
type: Question
type: AnsweredQuestion

http://stackoverflow.com/a/50998955
has body: keys = ['a', 'b'] values = [1, 2] print(dict(zip(keys,values))) Output: {'a':1,'b':2}
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/50998859
upvote count: 1

http://stackoverflow.com/comment/88967291
type: Comment
comment on: http://stackoverflow.com/a/50986230
has text: Thanks, I've fixed it
type: AnswerComment
score: 0

http://stackoverflow.com/a/50865606
score: 10
has comment: http://stackoverflow.com/comment/88734141
upvote count: 10
downvote count: 0
has body: Assuming you're looking to copy the values 10 times, you can just stack 10 of the array: def repeat(arr, count): return np.stack([arr for _ in range(count)], axis=0) axis=0 is actually the default, so it's not really necessary here, but I think it makes it clearer that you're adding the new axis on the front. In fact, this is pretty much identical to what the examples for stack are doing: &gt;&gt;&gt; arrays = [np.random.randn(3, 4) for _ in range(10)] &gt;&gt;&gt; np.stack(arrays, axis=0).shape (10, 3, 4) At first glance you might think repeat or tile would be a better fit. But repeat is about repeating over an existing axis (or flattening the array), so you'd need to reshape either before or after. (Which is just as efficient, but I think not as simple.) And tile (assuming you use an array-like reps—with scalar reps it basically repeat) is about filling out a multidimensional spec in all directions, which is much more complex than what you want for this simple case. All of these options will be equally efficient. They all copy the data 10 times over, which is the expensive part; the cost of any internal processing, building tiny intermediate objects, etc. is irrelevant. The only way to make it faster is to avoid copying. Which you probably don't want to do. But if you do… To share row storage across the 10 copies, you probably want broadcast_to: def repeat(arr, count): return np.broadcast_to(arr, (count,)+arr.shape) Notice that broadcast_to doesn't actually guarantee that it avoids copying, just that it returns some kind of readonly view where "more than one element of a broadcasted array may refer to a single memory location". In practice, it's going to avoid copying. If you actually need that to be guaranteed for some reason (or if you want a writable view—which is usually going to be a terrible idea, but maybe you have a good reason…), you have to drop down to as_strided: def repeat(arr, count): shape = (count,) + arr.shape strides = (0,) + arr.strides return n…
has comment: http://stackoverflow.com/comment/88737423
type: Answer
has comment: http://stackoverflow.com/comment/88737319
has comment: http://stackoverflow.com/comment/88734095
has comment: http://stackoverflow.com/comment/88737386
answers question: http://stackoverflow.com/q/50865463

http://stackoverflow.com/comment/88908980
type: QuestionComment
comment on: http://stackoverflow.com/q/50955583
has text: sort them in order of none Eg first 1 2 3, N 2 3, 1 N 3, 1 2 N, N N 3, N 2 N, 1 N N, N N N. Now 1 Ns can go with only 2 Ns so compare those keeping two pointers
score: 0
type: Comment

http://stackoverflow.com/a/50890451
has comment: http://stackoverflow.com/comment/88783905
score: 0
has comment: http://stackoverflow.com/comment/88782121
has comment: http://stackoverflow.com/comment/88783874
answers question: http://stackoverflow.com/q/50890242
has comment: http://stackoverflow.com/comment/88797691
has comment: http://stackoverflow.com/comment/88783834
has comment: http://stackoverflow.com/comment/88782226
has body: Split the contents of the file and convert into a dict; On python 3.6 and greater, you would have only the last entry present in the dict &gt;&gt;&gt; data=""" ... 2018-06-11 12:29 692 ... 2018-06-11 12:55 690 ... 2018-06-11 13:00 690 ... 2018-06-11 14:40 690 ... 2018-06-11 15:01 690 &lt;-- this one ... 2018-06-12 06:00 687 ... 2018-06-12 09:27 688 ... 2018-06-12 09:30 688 ... 2018-06-12 09:37 688 ... 2018-06-12 09:48 688 ... 2018-06-12 10:08 688 &lt;-- this one ... 2018-06-13 06:00 699 ... 2018-06-13 08:06 700 ... 2018-06-13 10:34 702 ... 2018-06-13 10:40 702 &lt;-- this one ... 2018-06-14 06:00 709 &lt;-- this one ... 2018-06-15 06:57 719 &lt;-- this one ... 2018-06-16 07:50 721 &lt;-- this one ... """ &gt;&gt;&gt; from pprint import pprint &gt;&gt;&gt; new_d = dict(d.split(' ', 1) for d in data.strip().splitlines()) &gt;&gt;&gt; pprint(new_d) {'2018-06-11': '15:01 690 &lt;-- this one', '2018-06-12': '10:08 688 &lt;-- this one', '2018-06-13': '10:40 702 &lt;-- this one', '2018-06-14': '06:00 709 &lt;-- this one', '2018-06-15': '06:57 719 &lt;-- this one', '2018-06-16': '07:50 721 &lt;-- this one'} &gt;&gt;&gt; Edit If you want only the 3rd field &gt;&gt;&gt; from operator import itemgetter &gt;&gt;&gt; indexer = itemgetter(0,2) &gt;&gt;&gt; new_d = dict(indexer(d.split(' ', 3)) for d in data.strip().splitlines()) &gt;&gt;&gt; pprint(new_d) {'2018-06-11': '690', '2018-06-12': '688', '2018-06-13': '702', '2018-06-14': '709', '2018-06-15': '719', '2018-06-16': '721'} &gt;&gt;&gt; For getting this working in python version less than 3.6, use OrderedDict instead of dict &gt;&gt;&gt; from collections import OrderedDict as odict &gt;&gt;&gt; new_d = dict(indexer(d.split(' ', 3)) for d in data.strip().splitlines()) &gt;&gt;&gt; pprint(new_d) OrderedDict([('2018-06-11', '690'), ('2018-06-12', '688'), ('2018-06-13', '702'), ('2018-06-14', '709'), ('2018-06-15', '719'), ('2018-06-16', '721')])
type: Answer
has comment: http://stackoverflow.com/comment/88784123

http://stackoverflow.com/a/50867722
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/50867354
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50867354
type: Answer
has body: The fastest way I can think of is to overwrite the entire first level (innermost level) of the MultiIndex with a 20-minute-shifted version of itself: x.index = x.index.set_levels(x.index.levels[1].shift(20, 'min'), level=1) Example x = pd.DataFrame(index=pd.MultiIndex.from_product([pd.date_range('2017-01-03', '2017-01-06', freq='1D'), pd.date_range('09:00', '17:00', freq='20min')])) x.loc[:, 'x1'] = list(range(len(x))) x x1 2017-01-03 2018-06-14 09:00:00 0 2018-06-14 09:20:00 1 2018-06-14 09:40:00 2 2018-06-14 10:00:00 3 2018-06-14 10:20:00 4 ... .. 2017-01-06 2018-06-14 15:40:00 95 2018-06-14 16:00:00 96 2018-06-14 16:20:00 97 2018-06-14 16:40:00 98 2018-06-14 17:00:00 99 x.index = x.index.set_levels(x.index.levels[1].shift(20, 'min'), level=1) x x1 2017-01-03 2018-06-14 09:20:00 0 2018-06-14 09:40:00 1 2018-06-14 10:00:00 2 2018-06-14 10:20:00 3 2018-06-14 10:40:00 4 ... .. 2017-01-06 2018-06-14 16:00:00 95 2018-06-14 16:20:00 96 2018-06-14 16:40:00 97 2018-06-14 17:00:00 98 2018-06-14 17:20:00 99

http://stackoverflow.com/comment/88806436
has text: Why on Earth would you want to do that? https://stackoverflow.com/questions/824349/modify-the-url-without-reloading-the-page
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50903335

http://stackoverflow.com/a/50892151
answers question: http://stackoverflow.com/q/50891937
score: 0
has body: Not using permutation lib does not seem very reasonable to me. But you can make the equivalent of your nested loops by using generators: opers = ['+','*','-'] arr = [55, 3, 45, 33] def iterate(previous_iterator): for previous_list in previous_iterator: for oper in opers: yield [oper] + previous_list operator_iterator = [[]] for i in range(len(arr) - 1): operator_iterator = iterate(operator_iterator) print(list(operator_iterator)) # [['+', '+', '+'], ['*', '+', '+'], ['-', '+', '+'], ['+', '*', '+'], ['*', '*', '+'], ['-', '*', '+'], ['+', '-', '+'], ['*', '-', '+'], ['-', '-', '+'], ['+', '+', '*'], ['*', '+', '*'], ['-', '+', '*'], ['+', '*', '*'], ['*', '*', '*'], ['-', '*', '*'], ['+', '-', '*'], ['*', '-', '*'], ['-', '-', '*'], ['+', '+', '-'], ['*', '+', '-'], ['-', '+', '-'], ['+', '*', '-'], ['*', '*', '-'], ['-', '*', '-'], ['+', '-', '-'], ['*', '-', '-'], ['-', '-', '-']] And you can use this iterator to find your solutions: import operator ops = { "+": operator.add, "*": operator.mul, "-": operator.sub } # etc. opers = ['+','*','-'] arr = [55, 3, 45, 33, 25] # needs to work for any length of arr def iterate(previous_iterator): for previous_list in previous_iterator: for oper in opers: yield [oper] + previous_list operator_iterator = [[]] for i in range(len(arr) - 1): operator_iterator = iterate(operator_iterator) for operator_list in operator_iterator: x = arr[0] for operator, value in zip(operator_list, arr[1:]): x=ops[operator](x, value) if x % 101 == 0: print(operator_list) # ['*', '+', '-', '+'] # ['+', '-', '*', '-']
type: Answer

http://stackoverflow.com/comment/88744663
type: QuestionComment
score: 1
has text: [`plt.axes`](https://matplotlib.org/examples/pylab_examples/axes_demo.html) may be helpful. Or something like this [answer](https://stackoverflow.com/questions/17458580/embedding-small-plots-inside-subplots-in-matplotlib)
comment on: http://stackoverflow.com/q/50871461
type: Comment

http://stackoverflow.com/comment/116378836
has text: @ArtificiallyIntelligence we are using TensorRT for inference in production. Tensorflow used to have queue. But its deprecated .I think that a direction for replacing `feed_dict` will be checking tf.data
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51201681
score: 1

http://stackoverflow.com/q/50874150
score: 0
has body: I have this piece of code: import itertools as it .... temp_list = [] for elem in it.islice(myIter, 0, 3): temp_list.append(elem[0]) print(temp_list) Let's assume that the lenght of myIter is fixed but not known a priori, let's say 100 for this example. With the above code, i can put in the temp_list the first 3 elements of myIter. What i want to do is to continue to append in the temp_list all the elements of myIter until all the elements of myIter is in temp_list. How can i do this? EDIT the temp_list should be a list of list. So in the first position let's say temp_list[][0] i have the first 3 element of the myIter, then i want the second slice (elements from 4 to 6) in the temp_list[][1] and so on until myIter is at the end
answer count: 1
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has title: Multiple slice from an Iterator - Python3
has comment: http://stackoverflow.com/comment/88750390
type: Question
has comment: http://stackoverflow.com/comment/88752472
tagged with: iterator
has comment: http://stackoverflow.com/comment/88769849
has comment: http://stackoverflow.com/comment/88749714
has answer: http://stackoverflow.com/a/50874245

http://stackoverflow.com/q/50904470
type: Question
has comment: http://stackoverflow.com/comment/88808716
upvote count: 5
score: 2
has answer: http://stackoverflow.com/a/50904695
has answer: http://stackoverflow.com/a/50904570
has answer: http://stackoverflow.com/a/50904582
possible better answer: http://stackoverflow.com/a/50904556
favorite count: 0
has comment: http://stackoverflow.com/comment/88808844
has answer: http://stackoverflow.com/a/50904556
has title: How to put brackets in a list accordingly in Python 3?
answer count: 5
has body: I am trying to put brackets in a list. This is the code: list_1 = [1,2,2] list_2 = [1,2,3,4,5] I want to use the numbers in 'list_1' to put brackets on 'list_2'. Like this: [[1],[2,3],[4,5]] How can i achieve this using Python 3?
has comment: http://stackoverflow.com/comment/88808800
has answer: http://stackoverflow.com/a/50904509
tagged with: python
has comment: http://stackoverflow.com/comment/88808909
type: AnsweredQuestion
tagged with: python-3.x
tagged with: list
accepted answer: http://stackoverflow.com/a/50904570
downvote count: 3
has comment: http://stackoverflow.com/comment/88808739

http://stackoverflow.com/a/50989741
score: 32
type: Answer
has comment: http://stackoverflow.com/comment/95378824
answers question: http://stackoverflow.com/q/50975793
has comment: http://stackoverflow.com/comment/122780025
downvote count: 1
accepted answer of: http://stackoverflow.com/q/50975793
has body: In the latest version of Telethon, @Lonami's answer is, by far, the best, so just use it. You may use the following code snippet to get messages: client = TelegramClient('session_name', api_id, api_hash, update_workers=1, spawn_read_thread=False) assert client.connect() if not client.is_user_authorized(): client.send_code_request(phone_number) me = client.sign_in(phone_number, input('Enter code: ')) channel_username='tehrandb' # your channel channel_entity=client.get_entity(channel_username) posts = client(GetHistoryRequest( peer=channel_entity, limit=100, offset_date=None, offset_id=0, max_id=0, min_id=0, add_offset=0, hash=0)) # messages stored as `posts.messages`
upvote count: 33
has comment: http://stackoverflow.com/comment/122781186
has comment: http://stackoverflow.com/comment/88975962
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/107255474

http://stackoverflow.com/a/50925430
has comment: http://stackoverflow.com/comment/88850239
has comment: http://stackoverflow.com/comment/88852651
downvote count: 0
answers question: http://stackoverflow.com/q/50925366
score: 1
has comment: http://stackoverflow.com/comment/88850191
has body: This line: print(i for i in range(1, n+1)) Creates a generator and prints it out, it's exactly what's expected. To print the values as a list, which i'm guessing is what you intended, add []: print([i for i in range(1, n+1)]) If you intended to print each element on a separate line the syntax is similar but slightly modified: [print(i) for i in range(1, n+1)] EDIT: For everything on the same line as you requested in your comment: print(''.join(str(i) for i in range(1, n+1)))
upvote count: 1
has comment: http://stackoverflow.com/comment/88852354
type: Answer

http://stackoverflow.com/comment/88850898
type: Comment
comment on: http://stackoverflow.com/a/50921820
score: 0
type: AnswerComment
has text: My bad, it wasn't supposed to be a return but rather an append to list in case `i==j` fails.

http://stackoverflow.com/a/50941396
has body: You can try this code : WebDriverWait(driver, 20).until( EC.visibility_of_element_located((By.ID, "card_type"))) cardtype = Select(driver.find_element_by_id('card_type')) cardtype.select_by_value("Mastercard") #OR cardtype.select_by_visible_text('MasterCard') Hope this will be helpful.
upvote count: 1
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/50939687
has comment: http://stackoverflow.com/comment/88884005

http://stackoverflow.com/q/50985481
accepted answer: http://stackoverflow.com/a/50986062
has title: pandas how to add details to csv before writing a data frame
tagged with: python
favorite count: 0
downvote count: 2
score: 2
type: AnsweredQuestion
type: Question
upvote count: 4
tagged with: export-to-csv
answer count: 1
has body: I need to write to a csv file that have 3-5 lines(rows) of details about the file, following which 3 rows of blank lines before I can append to data frame. Here is how the file looks like. (Note: lines having '#' are comments for demonstration) some details some more details some details that were not covered in last two details #blankline1 #blankline2 #blankline3 A1;B;C #headers 1231;1241;abc 1232;1242;abd 1233;1243;abe 1234;1244;abf . . . Here is what I've tried so far: import pandas as pd file_name = 'my_csv_file.csv' df1 = pd.Dataframe({"some details":}) df2 = pd.DataFrame({"some more details":}) df3 = pd.DataFrame({"some details that were not covered in last two details'}) df4 = pd.DataFrame({"\n\n\n\":}) #write 3 blank lines df5 = pd.DataFrame({"A":[1231 1232 1233 1234] "B":[1241 1242 1243 1244] "headers":[abc abd abe abf] } df1.to_csv(file_name, sep=';', mode='a', index=False) df2.to_csv(file_name, sep=';', mode='a', index=False) df3.to_csv(file_name, sep=';', mode='a', index=False) df4.to_csv(file_name, sep=';', mode='a', index=False) df5.to_csv(file_name, sep=';', mode='a', index=False) but this doesn't seem to work. Can anyone help me with this?
tagged with: pandas
has answer: http://stackoverflow.com/a/50986062

http://stackoverflow.com/q/50875592
downvote count: 0
score: 1
has body: I have info in ES. The mapping is very simple : { "index": { "aliases": {}, "mappings": { "level1": { "properties": { "id": { "type": "string" }, "level2": { "type": "nested", "properties": { "level3": { "type": "nested", "properties": { "value1": { "type": "string" }, "value2": { "type": "long" }, "id": { "type": "string" }, "value3": { "type": "long" } } }, "id": { "type": "string" } } } } } }, "settings": { "index": { "creation_date": "1505476515647", "number_of_shards": "5", "number_of_replicas": "1", "uuid": "_0IiQCPrQ1i-kDP1481y8w", "version": { "created": "2030099" } } }, "warmers": {} } } and when i do the query: {"query": {"terms": {"_id": [ "value51" ] }}} I receive data with this structure: _source (dict) level1 (list) level2 (list) data1 (dict) id value1 value2 value3 data2 (dict) data3 (dict) ... data65000 (dict) The problem is that 65,000 data are too many, and I run out of memory, I would like to know if _search or ElasticSearch in general has some way of bringing that information (data1,data2,data3...) in batches. Or if there is some way to make that query so that I do not run out of memory on the computer. Any idea? Thank you!
type: Question
has title: How can I bring information from ElasticSearch in batches if it is on many levels?
has answer: http://stackoverflow.com/a/50914653
upvote count: 1
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: elasticsearch
tagged with: python
has comment: http://stackoverflow.com/comment/88839852

http://stackoverflow.com/comment/120876874
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50908925
has text: I turned my Dataframe to StyleFrame in the way suggested, but it throws AttributeError("'Series' object has no attribute 'style'") error. My simplified code: def save_file(results: DataFrame): StyleFrame(results).to_excel("path_to_file").save() Am I doing something wrong?

http://stackoverflow.com/q/50861080
type: UnansweredQuestion
tagged with: python
has body: I am writing this after spending quite some time in searching it on available internet resources. I have a simple program which ssh into a cisco routers device to do a configuration changes. Whenever I run my program I see cisco cli(terminal) says invalid command it is because there is some character inserted in my command. cisco-nexus(config)# username edwin password THISisWHERIAMtypingPWD&lt;0x08&gt;NG % Invalid command at '^' marker. cisco-nexus(config)# whilst the command which I am sending only contains following text: username edwin password THISisWHERIAMtypingPWDNG I have no idea how paramiko is inserting this randome code &lt;0x08>. completed code is here: import paramiko import time import re class ssh: def __init__(self, ip, user, pwd): self.ip = ip self.user = user self.pwd = pwd def device_conn(self): remote_con = paramiko.SSHClient() remote_con.set_missing_host_key_policy(paramiko.AutoAddPolicy()) remote_con.connect(hostname=self.ip, username=self.user, password=self.pwd, look_for_keys=False, allow_agent=False) remote_ses = remote_con.invoke_shell() output = remote_ses.recv(1000) time.sleep(1) remote_ses.send("conf t"+"\n") time.sleep(0.5) remote_ses.send("username edwin password THISisWHERIAMtypingPWDNG"+"\n") time.sleep(0.5) output = remote_ses.recv(10000) print output with open("device.txt","rb") as dev: for fw in dev: print fw.strip() ob = ssh(fw.strip(), "user", "pwd") output = ob.device_conn()
answer count: 0
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88743951
tagged with: network-programming
tagged with: cisco
tagged with: paramiko
has title: Python Paramiko shell invoke insert unwanted characters
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/88742085
score: 0
favorite count: 0

http://stackoverflow.com/q/50955288
has comment: http://stackoverflow.com/comment/88924922
tagged with: python-telegram-bot
upvote count: 5
has comment: http://stackoverflow.com/comment/89234763
tagged with: python
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88921818
has body: I developed a Telegram bot with the python-telegram-bot library and now i want to deploy it in my server, so i setup a webhook(following the Official Wiki) but when i try to communicate with my bot i don't get any reply. This is the source of the bot: def main(): PRIVTOKEN = "1134xxxx" updater = Updater(PRIVTOKEN) dp = updater.dispatcher dp.add_handler(CommandHandler("start", start)) # ... updater.start_webhook(listen='127.0.0.1', port=8843, url_path=PRIVTOKEN) updater.bot.set_webhook(webhook_url='https://example.com/' + PRIVTOKEN, certificate=open("cert.pem", "rb")) print("bot started") updater.idle() the nginx config file: server { listen 443 ssl; server_name example.com; location /1134xxxx { proxy_pass http://127.0.0.1:8443; } } The netstat status: sudo netstat -an | grep 8843 tcp 0 127.0.0.1:8843 0.0.0.0:* LISTEN No other errors where logged either by the bot(i've enabled the error logs) or by nginx(access/error.log) I’ve also added a custom rule for 8843 port in the firewall.
has title: How to deploy a Telegram Bot with Nginx reverse proxy
type: Question
score: 5
tagged with: nginx
has comment: http://stackoverflow.com/comment/88962822
has answer: http://stackoverflow.com/a/51123651
answer count: 1
favorite count: 0
tagged with: telegram-bot

http://stackoverflow.com/comment/88766419
has text: @abarnert just did
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50881996

http://stackoverflow.com/comment/88834742
comment on: http://stackoverflow.com/q/50917315
has text: I'm pretty sure there is no such functionality built in to wx, so you will have to build it yourself. But it's not that hard. For most the basic version, if `cellname` is your `A1` string, it's just `row, col = int(cellname[1:]), ord(cellname[0].upper()) - 'A'`. If you want to add error handling, handling more than 26 columns, or parse complex expressions, if you understand that code, you can build on it from there.
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/50977301
type: Question
has title: Extract URL from text file - Python
tagged with: python
score: 0
answer count: 2
has body: I am trying to extract a URL from a text file which contains a source code of a website. I want to get the website link inside href and I wrote some code I borrowed from stackoverflow but I can't get it to work. with open(sourcecode.txt) as f: urls = f.readlines() urls = ([s.strip('\n') for s in urls ]) print(url)
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/50977427
has comment: http://stackoverflow.com/comment/88950732
has answer: http://stackoverflow.com/a/50977357
tagged with: python-3.6
type: UnansweredQuestion
favorite count: 0
has comment: http://stackoverflow.com/comment/88950712

http://stackoverflow.com/comment/90969328
type: AnswerComment
has text: Thanks for the info, sailing in the same boat as you. I tried the [detailed instructions here](http://www.clemens-sielaff.com/create-a-portable-python-with-pip-on-windows/) after getting the embedded distribution, but ended up with the same error as yours. Looks like regular installation is the only way if you want pip.
type: Comment
score: 1
comment on: http://stackoverflow.com/a/50921047

http://stackoverflow.com/a/50983428
has body: You can try the below simple approach. &gt;&gt;&gt; arr ['[1,2,3]', '[4,5,6]', '[7,8,9]', '[10,11,12]'] &gt;&gt;&gt; &gt;&gt;&gt; '+'.join(arr) '[1,2,3]+[4,5,6]+[7,8,9]+[10,11,12]' &gt;&gt;&gt; &gt;&gt;&gt; eval('+'.join(arr)) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] &gt;&gt;&gt; Another approach using reduce() and lambda. &gt;&gt;&gt; import json &gt;&gt;&gt; &gt;&gt;&gt; arr = ['[1,2,3]','[4,5,6]','[7,8,9]','[10,11,12]'] &gt;&gt;&gt; &gt;&gt;&gt; arr2 = reduce(lambda list1, list2: list1 + '+' + list2, arr) &gt;&gt;&gt; &gt;&gt;&gt; arr2 '[1,2,3]+[4,5,6]+[7,8,9]+[10,11,12]' &gt;&gt;&gt; &gt;&gt;&gt; eval(arr2) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
has comment: http://stackoverflow.com/comment/88963736
has comment: http://stackoverflow.com/comment/88962934
score: 0
has comment: http://stackoverflow.com/comment/88968247
has comment: http://stackoverflow.com/comment/88962133
type: Answer
has comment: http://stackoverflow.com/comment/88961889
has comment: http://stackoverflow.com/comment/88968520
has comment: http://stackoverflow.com/comment/88962021
answers question: http://stackoverflow.com/q/50982372
has comment: http://stackoverflow.com/comment/88963239

http://stackoverflow.com/comment/88948676
comment on: http://stackoverflow.com/a/50970560
has text: Yeah I do have an alias set up because I am on ubuntu, and as I understand it, which python needs to point to python 2 for internal purposes
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/51010285
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/89015231
answer count: 1
tagged with: flask
tagged with: flask-sqlalchemy
favorite count: 0
has body: Flask-SQLAlchemy suggests the Declarative pattern for setting up a database connection. The example hard-codes a single database path, and it seems like I should avoid that, so that I can configure different databases for unit testing, local development, and then eventually production. this is their database.py: from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.ext.declarative import declarative_base engine = create_engine('sqlite:////tmp/test.db', convert_unicode=True) db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine)) Base = declarative_base() Base.query = db_session.query_property() def init_db(): # import all modules here that might define models so that # they will be registered properly on the metadata. Otherwise # you will have to import them first before calling init_db() import yourapplication.models Base.metadata.create_all(bind=engine) But I haven't been able to figure out how to avoid hard-coding this db path. Environment variables: I could just replace the sqlite:///.... path with an environment variable. But that would require some way to have pytest run with one set of environment vars and flask run use a different set. I'd much rather have my unit tests keep track of their own temporary database.[2] I'd also like create_app() that creates the Flask app to take a database path that's a config variable. Import database.py within an application context I thought I could replace the database path with current_app.config['DB'], and import the database within with app.app_context(). But the Model classes need to import Base, and I can't subclass Base within the application context. So when the models get loaded, they're loaded outside the application context and that throws runtime errors. So what's the right way to use declarative_base in a flask app with unit tests? Thanks for your help! [2]: If that's what I should do, then I can live with it. But it seems …
tagged with: python
has comment: http://stackoverflow.com/comment/89044810
score: 2
downvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51026456
has title: How to avoid hard-coding database path using flask, SQLAlchemy, and declarative_base

http://stackoverflow.com/a/74677730
score: 2
has body: os.walk() uses scandir which is the fastest and we get the file object that can be used for many other purposes as well like, below I am getting the modified time. Below code implement recursive serach using os.scandir() import os import time def scantree(path): """Recursively yield DirEntry objects for given directory.""" for entry in os.scandir(path): if entry.is_dir(follow_symlinks=False): yield from scantree(entry.path) else: yield entry for entry in scantree('/home/'): if entry.is_file(): print(entry.path,time.ctime(entry.stat().st_mtime))
downvote count: 0
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/50948391

http://stackoverflow.com/q/50938850
tagged with: python
score: -2
possible better answer: http://stackoverflow.com/a/50938934
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50938934
type: Question
has answer: http://stackoverflow.com/a/50938918
answer count: 2
has title: How to assign values with respective variable name?
upvote count: 0
tagged with: python-2.7
accepted answer: http://stackoverflow.com/a/50938918
favorite count: 0
tagged with: python-3.x
has body: How to create a new column by using loop to assign different number with respective string in data frame? For example:['buy','sell',hold'] to [-1,+1,0] ? This is my column and i wish to add a new column enter image description here
downvote count: 2

http://stackoverflow.com/a/50949809
type: Answer
has comment: http://stackoverflow.com/comment/88897301
downvote count: 0
score: 1
has body: As mentioned in 4d11's answer, one of the biggest challenges in machine learning is often getting a high quality, significantly sized set of training data. In terms of feeding data into a Tensorflow network/model, I'd recommend you check out their 'get started' tutorial on feature columns: https://www.tensorflow.org/get_started/feature_columns Feature columns are used to represent data of different types numerically for a representation that can be fed into the model. The tutorial goes into some detail on the ways in which this works and why you may choose to represent different data in different ways. I found it pretty helpful as an intro.
upvote count: 1
answers question: http://stackoverflow.com/q/50949318

http://stackoverflow.com/a/50976569
type: AcceptedAnswer
downvote count: 0
has body: Use frozenset and duplicated df[~df'source', 'target'.apply(frozenset, 1).duplicated()] source target weight 0 1 2 5 3 3 1 6 4 1 1 6 If you want to account for unordered source/target and weight df[~df'weight'.assign(A=df'source', 'target'.apply(frozenset, 1)).duplicated()] source target weight 0 1 2 5 3 1 2 7 4 3 1 6 5 1 1 6 However, to be explicit with more readable code. # Create series where values are frozensets and therefore hashable. # With hashable things, we can determine duplicity. # Note that I also set the index and name to set up for a convenient `join` s = pd.Series(list(map(frozenset, zip(df.source, df.target))), df.index, name='mixed') # Use `drop` to focus on just those columns leaving whatever else is there. # This is more general and accommodates more than just a `weight` column. mask = df.drop(['source', 'target'], axis=1).join(s).duplicated() df[~mask] source target weight 0 1 2 5 3 1 2 7 4 3 1 6 5 1 1 6
type: Answer
accepted answer of: http://stackoverflow.com/q/50975798
score: 4
answers question: http://stackoverflow.com/q/50975798
upvote count: 4

http://stackoverflow.com/a/50920684
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/88841071
has body: You've got two things writing to stdout, both with their own buffers. This is one of the many reasons you usually don't want to use os.system. You can force Python to flush it output after each print just by using the flush=True argument. Or you can even open(sys.stdout.fileno(), 'wb', buffering=0) and then write your own bytes to that to disable buffering. But that may or may not be sufficient, because you still won't have any control over what os.system writes. If you want to make sure its output is either unbuffered, or shares the same buffers as Python, there's no way around that except using subprocess. As the docs for os.system said to do in the first place. So: for i in log_list: print("==============================") proc = subprocess.run(['tail', '-n', '2', log_path + i], stdout=subprocess.PIPE) print(proc.stdout)
answers question: http://stackoverflow.com/q/50920618
accepted answer of: http://stackoverflow.com/q/50920618
upvote count: 2
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/88841082
has comment: http://stackoverflow.com/comment/88840992

http://stackoverflow.com/q/50895243
has answer: http://stackoverflow.com/a/50895269
tagged with: user-input
downvote count: 2
has comment: http://stackoverflow.com/comment/88790595
linked to: http://stackoverflow.com/q/306400
linked to: http://stackoverflow.com/q/291978
type: Question
linked to: http://stackoverflow.com/q/4693120
tagged with: if-statement
has comment: http://stackoverflow.com/comment/88790585
has title: Python Function requesting input doesn't execute if statement - no error shown
upvote count: 2
score: 0
has comment: http://stackoverflow.com/comment/88790575
tagged with: function
linked to: http://stackoverflow.com/q/2612802
answer count: 1
favorite count: 0
has body: I thoroughly searched for an answer to my question but couldn't find anything that would explain my results. I truly hope that anyone of you can point me in the right direction. At the moment I am trying to program a text-based adventure game using Python 3 in order to better understand the language. While doing so I created a function that should ask the user for input and print a specific statement depending on the users input. In case the users input is invalid the function should then keep asking for input until it is valid. Unfortunately the function only seems to keep asking for input, without ever executing the if/elif statements within the function. Due to no errors being shown I am currently at a loss as to why this is the case... print("If You want to start the game, please enter 'start'." + "\n" + "Otherwise please enter 'quit' in order to quit the game.") startGame = True def StartGame_int(answer): if answer.lower() == "start": startGame = False return "Welcome to Vahlderia!" elif answer.lower() == "quit": startGame = False return "Thank You for playing Vahlderia!" + "\n" + "You can now close the window." else: return "Please enter either 'r' to start or 'q' to quit the game." def StartGame(): answ = input("- ") StartGame_int(answ) while startGame == True: StartGame()
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/379906

http://stackoverflow.com/a/50904570
has comment: http://stackoverflow.com/comment/88809380
type: Answer
has comment: http://stackoverflow.com/comment/88809118
answers question: http://stackoverflow.com/q/50904470
has comment: http://stackoverflow.com/comment/88809254
score: 4
accepted answer of: http://stackoverflow.com/q/50904470
upvote count: 4
has body: Here is an approach that uses an iterator for a change. list_1 = [1,2,2] list_2 = [1,2,3,4,5] it = iter(list_2) res = [] for take in list_1: res.append([next(it) for _ in range(take)]) print(res) # -&gt; [[1], [2, 3], [4, 5]] Of course, a list-comprehension version of that exists as well1:. it = iter(list_2) res = [[next(it) for _ in range(take)] for take in list_1] Finally, as @Chris_Rands notes in the comments below, you can use islice from the extremely useful itertools module. It takes care of the iterator-creating part of the code above and is this thus more compact. import itertools res = [list(itertools.islice(list_2, take)) for take in list_1] print(res) # -&gt; [[1], [2, 3], [4, 5]] ========================================================================== 1 Just remember to re-create the iterator!
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/50978424
has title: How to show variable order in python lists?
has body: How would you go about displaying the order of the variables in python after using sort(). For an example: A=3 B=1 C=2 D=[A,B,C] D.sort() would be [1,2,3], but I want to see [B,C,A] somehow
linked to: http://stackoverflow.com/q/592746
type: Question
has comment: http://stackoverflow.com/comment/88952982
has comment: http://stackoverflow.com/comment/88952825
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/88952808
has comment: http://stackoverflow.com/comment/88952834
has comment: http://stackoverflow.com/comment/88952831
has answer: http://stackoverflow.com/a/50978467
has comment: http://stackoverflow.com/comment/88952848
has comment: http://stackoverflow.com/comment/88952793
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88952887
has comment: http://stackoverflow.com/comment/88952992
has answer: http://stackoverflow.com/a/50978506

http://stackoverflow.com/a/50915487
has body: There are two errors in your code. First, doing user_input1 == user_input1.isalpha() compares a string and a boolean, this will always be False. Second, checking user_input1.isalpha() checks if the string is composed only of alphabetical characters. This will not print if only some characters are alphabetical. '123a'.isalpha() # False What you want to do is to print if any character is not numerical with not and str.isdigit. user_input1 = input("Enter the first number: ") if not user_input1.isdigit(): print ("Please use only numbers") Alternatively, you can always try to cast your inputs to int and catch the exception. try: num1 = int(input("Enter the first number: ")) num2 = int(input("Enter the second number: ")) print(f'{num1} + {num2} = {num1 + num2}') except ValueError: print("Please use only numbers...")
accepted answer of: http://stackoverflow.com/q/50915346
score: 0
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/50915346

http://stackoverflow.com/a/50954693
has comment: http://stackoverflow.com/comment/88907448
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50954569
accepted answer of: http://stackoverflow.com/q/50954569
type: Answer
upvote count: 1
has body: What you want to use is numpy.concatenate(), not numpy.column_stack(): YY = numpy.concatenate( (Yq[N//2:]-2*PI, Yq, Yq[:N//2]+2*PI))
score: 1

http://stackoverflow.com/a/69834469
has body: The python extension picks up the venv automatically, and activates it for new terminals panes: So selecting interpreter is not the issue. The only way I can get this to work is to install pylint into the user path after activating the venv: ./venv/bin/pip install -U pylint How this works to solve the E0401 I got in VSCode, don't ask me, I can't explain it. Feels like cheating. I thought the point of using virtualenvs was so that we could avoid having to deal with ambiguities across system/site/user modules.
downvote count: 0
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/50905636

http://stackoverflow.com/a/58495709
answers question: http://stackoverflow.com/q/50895643
upvote count: 21
type: Answer
downvote count: 0
score: 21
has body: A cleaner approach might be to override the model field itself if you don't mind losing the formatting of how the user entered their email. This worked better for me because I only had to change it in one place. Otherwise, you might have to worry about Signup, Login, User Update, API views, etc. The only method you will have to overwrite is to_python. This will just lowercase anything being saved to the UserModel.email field. from django.db import models class LowercaseEmailField(models.EmailField): """ Override EmailField to convert emails to lowercase before saving. """ def to_python(self, value): """ Convert email to lowercase. """ value = super(LowercaseEmailField, self).to_python(value) # Value can be None so check that it's a string before lowercasing. if isinstance(value, str): return value.lower() return value Your user model would then just be.. # Assuming you saved the above in the same directory in a file called model_fields.py from .model_fields import LowercaseEmailField class UserModel(AbstractBaseUser, PermissionsMixin): email = LowercaseEmailField(unique=True) # other stuff...

http://stackoverflow.com/q/50958065
type: Question
has body: So I have a dataframe that looks something like this: df1 = pd.DataFrame([[1,2, 3], [5,7,8], [2,5,4]]) 0 1 2 0 1 2 3 1 5 7 8 2 2 5 4 I then have a function that adds 5 to a number called add5. I'm trying to create a new column in df1 that adds 5 to all the numbers in column 2 that are greater than 3. I want to use vectorization not apply as this concept is going to be expanded to a dataset with hundreds of thousands of entries and speed will be important. I can do it without the greater than 3 constraint like this: df1['3'] = add5(df1[2]) But my goal is to do something like this: df1['3'] = add5(df1[2]) if df1[2] &gt; 3 Hoping someone can point me in the right direction on this. Thanks!
tagged with: pandas
upvote count: 1
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/50958206
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50958206
downvote count: 0
score: 1
has title: Pandas Vectorization with Function on Parts of Column

http://stackoverflow.com/comment/88904062
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50938369
has text: @Daniel I think `send_mail` is working well because when I tried with the SMTP setting, the mailing worked very well. I put my SMTP setting in my original post.

http://stackoverflow.com/a/50996970
has body: You should add the while loop at the beginning and ask the user at the end. Like this: num = 2 total = 0 con_1 = True while con_1: while num &lt;= 100: if num % 2 == 0: total = total + num num += 1 else: num += 1 print("Sum of even numbers between 2 and 100 is:", total) ask = str(input("Do you want to run this program again(Y/n)?:")) if ask == "Y" or ask == "y": con_1 = True elif ask == "N" or ask == "n": con_1 = False else: print("Your input is out of bounds.") break
answers question: http://stackoverflow.com/q/50996913
score: 0
type: Answer

http://stackoverflow.com/q/50895225
answer count: 0
type: UnansweredQuestion
tagged with: string-formatting
has title: Unusual KeyError when formatting HTML
has comment: http://stackoverflow.com/comment/88790517
tagged with: python
has comment: http://stackoverflow.com/comment/88790494
type: Question
has body: I have a class that takes an arbitrary HTML template and str.format()s it for a specific use case. For instance: Hi, {userName}! It's {weather} today. would become: Hi, Jon Skeet! It's sunny today. To do this, I have a Template class: class Template: def __init__(self, name, **kwargs): templateDirectory = getTemplateDirectory() # we don't need to worry about this with open(os.path.join(templateDirectory, "templates", name + ".html")) as templateFile: # we get the template we need self.template = templateFile.read() print(self.template) # all in order: we get the un-formatted HTML print(kwargs) # all in order: we get a dict of things to replace (i.e. {'userName': 'Jon Skeet', 'weather': 'sunny'} ) self.final = self.template.format(**kwargs) # this should just replace things nicely, but it doesn't: why? def __str__(self): return self.final I instantiate like this: ErrorTemplate = Template('foo', var1=42, var2='foo') print(str(ErrorTemplate)) The error I get is as follows: Traceback (most recent call last): File "/path/to/file.py", line 11, in <module> ErrorTemplate = Template('foo', var1=42, var2='bar') File "/path/to/the/file/with/Template/class.py", line 10, in __init__ self.final = self.template.format(**kwargs) KeyError: 'document' I'm not using 'document' anywhere. I have no idea where it gets 'document' from. What am I doing wrong?
score: 0
has comment: http://stackoverflow.com/comment/88790521
has comment: http://stackoverflow.com/comment/88790544
has comment: http://stackoverflow.com/comment/88790489
has comment: http://stackoverflow.com/comment/88790567
has comment: http://stackoverflow.com/comment/88790549

http://stackoverflow.com/q/50956392
has body: I have read distributed tensorflow documentation and this answer. According to this, in data parallelism approach: The algorithm distributes the data between various cores. Each core independently tries to estimate the same parameter(s) Cores then exchange their estimate(s) with each other to come up with the right estimate for the step. And in model parallelism approach: The algorithm sends the same data to all the cores. Each core is responsible for estimating different parameter(s) Cores then exchange their estimate(s) with each other to come up with the right estimate for all the parameters. How do In-graph replication and Between-graph replication relate to these approaches? This article says: For example, different layers in a network may be trained in parallel on different GPUs. This training procedure is commonly known as "model parallelism" (or "in-graph replication" in the TensorFlow documentation). And: In "data parallelism" (or “between-graph replication” in the TensorFlow documentation), you use the same model for every device, but train the model in each device using different training samples. Is that accurate? From the Tensorflow DevSummit video linked in tensorflow documentation page: It looks like data is split and distributed to each worker. So isn't In-graph replication following data parallelism approach?
upvote count: 8
accepted answer: http://stackoverflow.com/a/51137534
has title: Is Tensorflow's Between-graph replication an example of data parallelism?
tagged with: python
linked to: http://stackoverflow.com/q/41600321
type: AnsweredQuestion
tagged with: tensorflow
type: Question
tagged with: distributed
downvote count: 0
has comment: http://stackoverflow.com/comment/88911072
answer count: 1
has answer: http://stackoverflow.com/a/51137534
favorite count: 0
score: 8

http://stackoverflow.com/q/50936242
linked to: http://stackoverflow.com/q/48938449
score: 0
answer count: 3
linked to: http://stackoverflow.com/q/3148225
tagged with: document-ready
has answer: http://stackoverflow.com/a/50936735
tagged with: jquery
has answer: http://stackoverflow.com/a/50936324
has title: How to calculate page load time of a website which includes the total time and not just document.ready() time?
has body: I was trying to write a function either in Javascript or in Python using Selenium to calculate the page load time of a website. document.ready() will only give the DOM load time but there might be some AJAX calls which cannot be detected using document.ready(). There is even an extension in chrome web store named 'Page Load Time', which will calculate the total time, as per my requirements. How do I replicate same kind of functionality?
linked to: http://stackoverflow.com/q/14341156
type: UnansweredQuestion
tagged with: python
duplicate of: http://stackoverflow.com/q/48938449
tagged with: selenium
has answer: http://stackoverflow.com/a/50936394
type: Question
tagged with: javascript

http://stackoverflow.com/comment/88888252
type: Comment
type: QuestionComment
has text: @JonathonReinhart Yes, I just used this to have a simple minimal example, but in real life, I'll use something like Celery.
comment on: http://stackoverflow.com/q/50945329
score: 0

http://stackoverflow.com/comment/88787102
comment on: http://stackoverflow.com/q/50893328
type: Comment
type: QuestionComment
has text: This time it is producing the error from line 70: elif dupeboard[2] == XoY and dupeboard[5] == XoY and dupeboard[8] == XoY:
score: 0

http://stackoverflow.com/comment/88827384
type: Comment
has text: Yes of course! Why didn't I think of that. I just confirmed that this works. Thanks!
score: 1
comment on: http://stackoverflow.com/a/50913599
type: AnswerComment

http://stackoverflow.com/a/50999471
score: 2
answers question: http://stackoverflow.com/q/50999445
downvote count: 0
has body: l1 = list means assignment of list class in l1 variable. l2=list() mreans calling list() function to create a list and assign the list to l2 variable.
upvote count: 2
type: Answer

http://stackoverflow.com/comment/88991097
comment on: http://stackoverflow.com/q/50998454
type: Comment
has text: I just wanted to make the append mode functionality for better performance. If you run the code you can see when the file gets larger it took more time to append. I thought maybe there are better approaches to do that.
type: QuestionComment
score: 0

http://stackoverflow.com/a/50932879
score: 3
has body: Just loop over each key, and use all but the last element of the key to add dictionaries. Keep a reference to the last dictionary so set, then use the last element in the key tuple to actually set a key-value pair in the output dictionary: def nest(d: dict) -&gt; dict: result = {} for key, value in d.items(): target = result for k in key[:-1]: # traverse all keys but the last target = target.setdefault(k, {}) target[key[-1]] = value return result You could use functools.reduce() to handle the traversing-down-the-dictionaries work: from functools import reduce def nest(d: dict) -&gt; dict: result = {} traverse = lambda r, k: r.setdefault(k, {}) for key, value in d.items(): reduce(traverse, key[:-1], result)[key[-1]] = value return result I used dict.setdefault() rather than the auto-vivication defaultdict(nested_dict) option, as this produces a regular dictionary that won't further implicitly add keys when they don't yet exist. Demo: &gt;&gt;&gt; from pprint import pprint &gt;&gt;&gt; pprint(nest(d1)) {'A': {0: 0, 1: 1}, 'B': {0: 2, 1: 3}} &gt;&gt;&gt; pprint(nest(d2)) {'A': {0: {False: 1, True: 0}, 1: {False: 3, True: 2}}, 'B': {0: {False: 5, True: 4}, 1: {False: 7, True: 6}}} &gt;&gt;&gt; pprint(nest(d3)) {'C': {0: {False: {'A': 2, 'B': 3}, True: {'A': 0, 'B': 1}}, 1: {False: {'A': 6, 'B': 7}, True: {'A': 4, 'B': 5}}}, 'D': {0: {False: {'A': 10, 'B': 11}, True: {'A': 8, 'B': 9}}, 1: {False: {'A': 14, 'B': 15}, True: {'A': 12, 'B': 13}}}} Note that the above solution is a clean O(N) loop (N being the length of the input dictionary), whereas a groupby solution as proposed by Ajax1234 has to sort the input to work, making that a O(NlogN) solution. That means that for a dictionary with 1000 elements, a groupby() would need 10.000 steps to produce the output, whereas an O(N) linear loop only takes 1000 steps. For a million keys, this increases to 20 million steps, etc. Moreover, recursion in Python is.. slow, as Python can't optimise such solutions to an iterative appro…
accepted answer of: http://stackoverflow.com/q/50932755
answers question: http://stackoverflow.com/q/50932755
upvote count: 3
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/comment/88977807
type: Comment
comment on: http://stackoverflow.com/q/50991461
score: 0
has text: As an aside, please be aware that `str` is a reserved word in Python, and shouldn't be used as a variable name.
type: QuestionComment

http://stackoverflow.com/comment/88929330
has text: Side note: Are you sure you want an empty string in `F`, which appears to be a numeric column? Adding a string will turn the entire series to `object` dtype, which is expensive and inefficient.
score: 2
comment on: http://stackoverflow.com/q/50966435
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88857533
type: QuestionComment
score: 0
has text: `str` is a whole string (by the way, don't name variables by python classes). Did you want to split it into words?
comment on: http://stackoverflow.com/q/50929367
type: Comment

http://stackoverflow.com/q/50945463
has answer: http://stackoverflow.com/a/50945603
score: 2
upvote count: 2
type: Question
has title: timer() usage within a while loop, resetting caused by if statements in Python
has comment: http://stackoverflow.com/comment/88889426
has comment: http://stackoverflow.com/comment/88888507
has comment: http://stackoverflow.com/comment/88888424
answer count: 1
downvote count: 0
has body: I'm attempting to have a timer that counts down from 5 and when 0 is reached it will set a boolean value to false. The code follows: def touchInput(): while inputTime &lt; lastInputTime + 5: inputTable = [] inputTime = timer() lastInputTime = timer() TouchSensor('in2') if True: inputTable.append(".") inputTime = timer() TouchSensor('in3') if True: inputTable.append("-") inputTime = timer() else: lastInputTime = timer() inputAllowed = False I'm receiving an error within the else statement saying that the variable is unreachable in PyCharm. Is there a better way to phrase this code?
favorite count: 0
tagged with: python-3.x
tagged with: timer
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/88945955
type: AnswerComment
comment on: http://stackoverflow.com/a/50971704
type: Comment
has text: Backslash is just a [line continuation](https://stackoverflow.com/questions/38125328/what-does-a-backslash-by-itself-mean-in-python) character in Python. I've also added an explanation.
score: 1

http://stackoverflow.com/a/50926499
downvote count: 0
score: 1
type: Answer
upvote count: 1
has body: I believe it is the expected behavior. According to the documentation, pgpool-II's parallel query feature allows queries to be split in different servers: Load Balance If a database is replicated(because running in either replication mode or master/slave mode), performing a SELECT query on any server will return the same result. pgpool-II takes advantage of the replication feature in order to reduce the load on each PostgreSQL server. It does that by distributing SELECT queries among available servers, improving the system's overall throughput. In an ideal scenario, read performance could improve proportionally to the number of PostgreSQL servers. Load balancing works best in a scenario where there are a lot of users executing many read-only queries at the same time. Parallel Query Using the parallel query feature, data can be split among multiple servers, so that a query can be executed on all the servers concurrently, reducing the overall execution time. Parallel query works best when searching large-scale data. Here is a list of the config parameters for the parallel mode feature.
accepted answer of: http://stackoverflow.com/q/50924843
answers question: http://stackoverflow.com/q/50924843
type: AcceptedAnswer

http://stackoverflow.com/q/50908028
upvote count: 9
has body: I currently have TensorFlow code in python and are trying to find the best way to add this to an android app. As I see it there are a few options to do this. I've been looking at ML kit (https://developers.google.com/ml-kit/). But I'm not sure if this would work since I am using some specific TensorFlow functions to make calculations in the graph. For example these two lines: t_score = tf.reduce_mean(t_obj) t_grad = tf.gradients(t_score, t_input)[0] Would that be possible to do with ML kit? Another option would then be to use TensorFlow (lite) for Java without ML kit, but looking at the Java API it seems to be limited, would those two calls above be possible to do in java? The last option would be to host the python code and use it as backend so that the Android app could send the data to it and receive the result. That would be more expensive since the computations can't be made on mobile. So if possible the other options are preferred. How would you do this?
score: 9
has comment: http://stackoverflow.com/comment/88985612
downvote count: 0
answer count: 1
tagged with: firebase-mlkit
favorite count: 0
has title: Use TensorFlow python code with android app
tagged with: android
tagged with: python
has comment: http://stackoverflow.com/comment/88816040
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51078065
tagged with: tensorflow
type: Question

http://stackoverflow.com/comment/88796830
comment on: http://stackoverflow.com/a/50894409
score: 1
type: AnswerComment
has text: this should be a comment, not an answer
type: Comment

http://stackoverflow.com/a/56034030
upvote count: 7
downvote count: 0
type: Answer
has body: This sort of error is caused by the type of app associated with that client id. Logging in with a password is restricted to script type apps. When you create a new application, there are three types of apps to choose from: web app: A web based application installed app: An app intended for installation, such as on a mobile phone script: Script for personal use. Will only have access to the developers accounts If the application has the web app or installed app types then this form of authentication can't be used. You can't change the app type once it's created, but you can simply create a new one with a script type.
score: 7
has comment: http://stackoverflow.com/comment/116997677
answers question: http://stackoverflow.com/q/50973516

http://stackoverflow.com/q/50861659
tagged with: image-processing
type: Question
has title: Without using CV2, how do I display an image showing only the isolated green colors
has comment: http://stackoverflow.com/comment/88725846
answer count: 1
score: 0
has answer: http://stackoverflow.com/a/50861978
tagged with: spyder
tagged with: python
has body: My goal is to read an image of a plant and then output the picture showing only the green parts without any other background colors. Essentially, I only want to extract the leaf part from the picture and not the soil or anything else. So far I've been able to read my images and change them to green, however my goal was to actually extract the green rather than change the whole green. Any ideas on what I might doing wrong? HERE IS MY CODE import matplotlib.pyplot as plt import numpy as np # Read and display picture originalImage = plt.imread("C:/Users/user/Desktop/Image for detection1.jpg") imgplot = plt.imshow(originalImage) # Copy 1st picture and turn into an array edittedImage = originalImage.copy() arr = np.asarray(originalImage) # create array for image lowerGreen = np.array([130,137,10]) # define lower values for green upperGreen = np.array([220,235,130]) # define higher values for green for color in arr: # loop through pixels to find the color green if color &gt;= lowerGreen and &lt;= upperGreen: print (color) # print the image showing only the green sections imgplot = plt.imshow(edittedImage) ERROR MSG: File "C:/Users/user/.spyder-py3/extract green.py", line 28, in if color >= lowerGreen and color &lt;= upperGreen: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88727015

http://stackoverflow.com/q/50966822
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/88930430
tagged with: python
type: AnsweredQuestion
type: Question
accepted answer: http://stackoverflow.com/a/50967259
has comment: http://stackoverflow.com/comment/88930377
has comment: http://stackoverflow.com/comment/88930295
has title: Removing ambiguous lines from csv using Pandas or csv python
upvote count: 2
has answer: http://stackoverflow.com/a/50967259
score: 0
downvote count: 2
has comment: http://stackoverflow.com/comment/88930314
tagged with: pandas
tagged with: python-3.5
answer count: 1
favorite count: 0
has body: I have tried to remove the duplicate from the line using the following code: import csv file_in = '1.csv' file_out = 'output_file.csv' with open(file_in, 'r',encoding="utf-16") as fin, open(file_out, 'w',encoding="utf-16") as fout: reader = csv.reader(fin) writer = csv.writer(fout) d = {} for row in reader: color = row[0] if color not in d: d[color] = row writer.writerow(row) Here is the output file of my above program: File Output Here is the input file: File Input But there is a problem I thought I will get the filtered values, but the logic only remove the copied lines. See the following result values: For the same values I am getting yes as well as no in the different rows. These are ambiguous values 1 0 -1 -1 -1 -1 -1 -1 yes 1 0 -1 -1 -1 -1 -1 -1 no 1 0 1 1 1 -1 -1 -1 yes 1 0 1 1 1 -1 -1 -1 no These are ambiguous values and have nothing impact on my neural model. These are creating ambiguous situations. I am willing to remove such entries along with the duplicate rows. I was willing to use pandas, but don't have much knowledge. Kindly, help me remove the duplicate rows from the csv along with the ambiguous values. Mostly all the values are same except the last column which may have different values.

http://stackoverflow.com/a/50897300
has comment: http://stackoverflow.com/comment/88794351
score: 0
answers question: http://stackoverflow.com/q/50897121
type: Answer
has body: The newline character was removed from the set as it will generate an error. 1 -20 -100 50 60 3 4 -100 -3 -10 5 45 10 -15 with open('number.txt','r') as file1: file2 = open('text2.txt','w') line = file1.readlines() for s in line: # get the individual data and make them floating-point data = map(float, s.split()) # doing stuffs with the data print(sum(data) / len(data)) Updated my answer after @SpghttCd comment. You should now be able to access the columns. with open('number.txt','r') as file1: file2 = open('text2.txt','w') # recreating the matrix get the individual data and make them floating-points m = list([map(float, s.split()) for s in file1.readlines()]) # calculations in lines print(sum(m[0]) / len(m[0])) print(sum(m[1]) / len(m[1])) print(sum(m[2]) / len(m[2])) # calculations in columns c = [l[0] for l in m] print(sum(c) / len(c)) # or in a way more like what you tried tmp = 0 for j in range(len(m)): # accessing the first columns of each line of the matrix tmp += int(m[j][0]) / len(m[j]) print(tmp)

http://stackoverflow.com/comment/88813774
comment on: http://stackoverflow.com/a/50906814
type: Comment
has text: Nice answer ! how to get col1 ?
score: 0
type: AnswerComment

http://stackoverflow.com/q/50996107
answer count: 1
tagged with: unique
has comment: http://stackoverflow.com/comment/88986694
accepted answer: http://stackoverflow.com/a/50996328
tagged with: grouping
tagged with: python
has body: Here is my dataframe: data1 = [['2017-02-10','orange','jon','small','1','1.1'], ['2017-02-10','orange','jon','medium','1','2.1'], ['2017-02-10','orange','jon','large','1','3.1'], ['2017-02-11','orange','mary','small','2','1.2'], ['2017-02-10','orange','jon','medium','2','2.2'], ['2017-02-10','orange','jon','large','2','3.2'], ['2017-02-10','orange','jon','small','1','7.1'], ['2017-02-11','orange','mary','medium','1','8.1'], ['2017-02-11','orange','mary','large','1','9.1'], ['2017-02-11','orange','mary','small','2','10.1'], ['2017-02-11','orange','mary','medium','2','11.1'], ['2017-02-11','orange','mary','large','2','12.1']] df = pd.DataFrame(data1,columns=['date', 'fruit', 'name', 'size', 'replicate', 'weight']) print df date fruit name size replicate weight 0 2017-02-10 orange jon small 1 1.1 1 2017-02-10 orange jon medium 1 2.1 2 2017-02-10 orange jon large 1 3.1 3 2017-02-11 orange mary small 2 1.2 4 2017-02-10 orange jon medium 2 2.2 5 2017-02-10 orange jon large 2 3.2 6 2017-02-10 orange jon small 1 7.1 7 2017-02-11 orange mary medium 1 8.1 8 2017-02-11 orange mary large 1 9.1 9 2017-02-11 orange mary small 2 10.1 10 2017-02-11 orange mary medium 2 11.1 11 2017-02-11 orange mary large 2 12.1 I need to group this dataframe so that the output has a small, medium, and large values separated by replicate, like so: val1 = ['2017-02-10', 'orange', 'jon', 'small', '1', '1.1'], ['2017-02-10', 'orange', 'jon', 'medium', '1', '2.1'], ['2017-02-10', 'orange', 'jon', 'large', '1', '3.1'], val2 = ['2017-02-10', 'orange', 'jon', 'small', '2', '7.1'], ['2017-02-10', 'orange', 'jon', 'medium', '2', '2.2'], ['2017-02-10', 'orange', 'jon', 'large', '2', '3.2'], val3 = ['2017-02-11', 'orange', 'mary', 'small', '1', '1.2'], ['2017-02-11', 'orange', 'mary', 'medium', '1', '8.1'], ['2017-02-11', 'orange', 'mary', 'large', '1', '9.1'], val4.... The format of the output doesn't matter, its more how to group the data appropriately. Using a non-pandas/numpy approach, I can create a uniq…
type: AnsweredQuestion
has title: pandas/numpy: Grouping a dataframe with specified number of replicates
has comment: http://stackoverflow.com/comment/88986887
type: Question
has answer: http://stackoverflow.com/a/50996328
tagged with: numpy
score: 0
tagged with: pandas

http://stackoverflow.com/comment/89065847
type: QuestionComment
has text: I dont have the exact numbers with me. length of variable `labels` was larger than the length of variable `preds`
score: 0
comment on: http://stackoverflow.com/q/50931168
type: Comment

http://stackoverflow.com/q/50988223
has body: This here is the code: import cv2 import numpy as np mouth_cascade = cv2.CascadeClassifier('./haarcascade_mcs_mouth.xml') face_cascade = cv2.CascadeClassifier('./haarcascade_frontalface_default.xml') if mouth_cascade.empty(): raise IOError('Unable to load the mouth cascade classifier xml file') img = cv2.imread('/home/victor/Vic.jpg') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray,1.5,12) for(x,y,w,h) in faces: cv2.rectangle(img, (x,y), (x+w,y+h), (255,0,0),2) roi_gray = gray[y:y+h, x:x+h] roi_color = img[y:y+h, x:x+h] mouth = mouth_cascade.detectMultiScale(roi_gray,2.0,25) for (ex, ey, ew, eh) in mouth: cv2.rectangle(img, (ex,ey), (ex+ew, ey+eh),(0,255,0),3) crop_img = img[ey:ey+eh, ex:ex+ew] cv2.imshow('Cropped mouth', crop_img) cv2.waitKey(0) This is what I run in the terminal and the message I get as the output respectively: python MouthDetection.py [ INFO:0 ] Initialize OpenCL runtime... However, what I want is an image to pop up displaying the mouth that has been cropped from the face. What am I doing wrong here? Thank you. P.S I checked that all the paths are correct and all the libraries have been installed correctly. The PYTHONPATH variable is correct too.
has title: My Python script (to crop the mouth from a face) with Haarcascades and OpenCV throws the following error when run in Ubuntu 16.04 LTS terminal
type: Question
tagged with: opencv
score: 0
answer count: 1
tagged with: opencl
type: UnansweredQuestion
tagged with: python
tagged with: computer-vision
tagged with: haar-classifier
has answer: http://stackoverflow.com/a/51007083

pyqt5
tags question: http://stackoverflow.com/q/50859934
tags question: http://stackoverflow.com/q/50879977
type: Tag
tags question: http://stackoverflow.com/q/50967870
tags question: http://stackoverflow.com/q/50914252
tags question: http://stackoverflow.com/q/50880660
tags question: http://stackoverflow.com/q/50868830
tags question: http://stackoverflow.com/q/50977603
tags question: http://stackoverflow.com/q/50923163
tags question: http://stackoverflow.com/q/50955182
tags question: http://stackoverflow.com/q/50966244
tags question: http://stackoverflow.com/q/51000507
tags question: http://stackoverflow.com/q/51005745
tags question: http://stackoverflow.com/q/50926669
tags question: http://stackoverflow.com/q/50941790
tags question: http://stackoverflow.com/q/50915351
tags question: http://stackoverflow.com/q/51004906
tags question: http://stackoverflow.com/q/50886889
tags question: http://stackoverflow.com/q/50864375
tags question: http://stackoverflow.com/q/50905170
tags question: http://stackoverflow.com/q/50890645
tags question: http://stackoverflow.com/q/50896924
tags question: http://stackoverflow.com/q/50880850
tags question: http://stackoverflow.com/q/50885667
tag name: pyqt5
tags question: http://stackoverflow.com/q/50980192
tags question: http://stackoverflow.com/q/50956886
tags question: http://stackoverflow.com/q/50952726
tags question: http://stackoverflow.com/q/50981097
tags question: http://stackoverflow.com/q/50913151
tags question: http://stackoverflow.com/q/50881691
tags question: http://stackoverflow.com/q/50858666
tags question: http://stackoverflow.com/q/50965916
tags question: http://stackoverflow.com/q/51004728

http://stackoverflow.com/comment/88957100
type: QuestionComment
type: Comment
has text: What have your tried so far?
comment on: http://stackoverflow.com/q/50980795
score: 0

http://stackoverflow.com/q/50967491
has comment: http://stackoverflow.com/comment/88998799
has body: I am trying to use google task queues in python3, but I am facing some trouble while importing taskqueue library. On issuing the following command from google.appengine.api import taskqueue I am getting this error Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ModuleNotFoundError: No module named 'google.appengine' I have installed Google Cloud SDK and additionally installed 2 more packages as mentioned in the link. google-cloud-sdk-app-engine-python google-cloud-sdk-app-engine-python-extras I have checked the version of gcloud components that has been installed $ gcloud --version Google Cloud SDK 206.0.0 alpha 2018.06.18 app-engine-python 1.9.70 app-engine-python-extras 1.9.70 beta 2018.06.18 bq 2.0.34 core 2018.06.18 gsutil 4.32 Why I cannot be able to import taskqueue, Any help would appreciated.
tagged with: task-queue
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/88931294
has comment: http://stackoverflow.com/comment/88999855
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52120652
linked to: http://stackoverflow.com/q/38848896
tagged with: python
has title: How to import google's taskqueue library in python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88992687
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/52120652
type: Question
tagged with: google-cloud-sdk
has comment: http://stackoverflow.com/comment/88998744
tagged with: ubuntu

http://stackoverflow.com/q/50886185
has comment: http://stackoverflow.com/comment/88774068
type: Question
has body: I'm drawing a simple horizontal bar plot. For readability, I'd like to use keyword arguments, but I get an error with undocumented required parameter, when I do this. import pandas as pd import matplotlib.pyplot as plt plt.figure(figsize=(4,2)) # this example works plt.barh([1, 1, 1], [9.5, 8.5, 28.5], [.3, .3, .3], [-2207, -2197, -2188]) # here I want to use keyword arguments for readability, according to # https://matplotlib.org/api/_as_gen/matplotlib.pyplot.barh.html?highlight=barh plt.barh(y=[1, 1, 1], width= [9.5, 8.5, 28.5], height = [.3, .3, .3], left = [-2207, -2197, -2188]) # But I get error: # File "&lt;ipython-input-6-2f6ee5c89917&gt;", line 4, in &lt;module&gt; # left = [-2207, -2197, -2188]) # TypeError: barh() missing 1 required positional argument: 'bottom' There is no 'bottom' argument in the documentation: bar(y, width, *, align='center', **kwargs) bar(y, width, height, *, align='center', **kwargs) bar(y, width, height, left, *, align='center', **kwargs)```
has comment: http://stackoverflow.com/comment/88774387
type: UnansweredQuestion
tagged with: python
has title: unexpected required parameter 'bottom' in matplotlib.pyplot.barh()
has comment: http://stackoverflow.com/comment/88774139
answer count: 0
has comment: http://stackoverflow.com/comment/88774150
score: 0
tagged with: matplotlib

http://stackoverflow.com/comment/88767535
has text: I agree that it doesn't seem intended to be one. For example, in the [`gc` documentation](https://docs.python.org/3/library/gc.html#gc.garbage), they reference the PEP, not as an implementation detail.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50882416
score: 0

http://stackoverflow.com/q/51005155
answer count: 1
score: 0
tagged with: python
has title: Can IPython console be interactive in Eclipse/Pydev?
accepted answer: http://stackoverflow.com/a/51022043
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51022043
has body: I use Eclipse(version Neon 3 (4.6.3))to learn Python code. Is there anyway to make IPython Console opened in Eclipse Neon/PyDev? Please note that I already tried the PyDev Console but it doesn't work. For example, I tested a function in the PyDev Console, it gave me the error: File "", line 1, in I don't understand the message. Can anyone please help! Thank you! Ben
tagged with: ipython
tagged with: eclipse
type: Question
tagged with: pydev

http://stackoverflow.com/comment/91327798
type: Comment
comment on: http://stackoverflow.com/a/50919844
score: 0
type: AnswerComment
has text: Thanks, this solved my problem as I was trying to feed a dictionary in the wrong way

http://stackoverflow.com/q/50951803
favorite count: 0
has comment: http://stackoverflow.com/comment/88901591
tagged with: hierarchy
tagged with: python
has comment: http://stackoverflow.com/comment/88901359
tagged with: jupyter-notebook
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50952543
tagged with: http://stackoverflow.com/tag/json
upvote count: 1
possible better answer: http://stackoverflow.com/a/50952543
type: Question
has comment: http://stackoverflow.com/comment/88902390
has answer: http://stackoverflow.com/a/50952248
tagged with: nested-loops
has body: I'll preface this with I am not a developer by any means, but I was thrown this assignment and I am just lost. This is my first time using python and first time coding in 7+ years, and it's not going well. The JSON I have is an organizational tree, where each level potentially has children underneath it. I need to write a script in Python in Jupyter Notebook to flatten it into this format, or something similar where each new child is a new row. level1 | level2 | level3 org1 org1 org2 org1 org2 org3 Here is the JSON: [{ "Id": "f035de7f", "Name": "Org1", "ParentId": null, "Children": [{ "Id": "8c18a70d", "Name": "Org2", "ParentId": "f035de7f", "Children": [] }, { "Id": "b4514099", "Name": "Org3", "ParentId": "f035de7f", "Children": [{ "Id": "8abe58d1", "Name": "Org4", "Children": [] }] }, { "Id": "8e35bdc3", "Name": "Org5", "ParentId": "f035de7f", "Children": [{ "Id": "331fffbf", "Name": "Org6", "ParentId": "8e35bdc3", "Children": [{ "Id": "3bc3e085", "Name": "Org7", "ParentId": "331fffbf", "Children": [] }] }] }] }] I've tried a variety of for loops and have scoured the internet for days, but I think I'm missing some very basic knowledge to make this work. I would highly appreciate any help someone can give. Here are my starters: for item in orgs_json: orgs_json_children = item["Children"] orgs_list.append(orgs_json_children) or wanted = ['Children', 'Name'] for item in orgs_json[0]: details = [X["Name"] for X in orgs_json] for key in wanted: print(key, ':', json.dumps(details[key], indent=4)) # Put a blank line at the end of the details for each item print()
has title: Flatten a nested JSON hierarchy in Python
has answer: http://stackoverflow.com/a/55025083
answer count: 3
downvote count: 0
score: 1
accepted answer: http://stackoverflow.com/a/50952248

http://stackoverflow.com/q/50872479
has comment: http://stackoverflow.com/comment/88747816
has title: How to unittest a function that use app.logger of Flask
tagged with: unit-testing
type: Question
tagged with: flask
downvote count: 0
has comment: http://stackoverflow.com/comment/88748381
favorite count: 0
has comment: http://stackoverflow.com/comment/88754518
type: UnansweredQuestion
tagged with: python
has body: For sure I'm missing something in Flask and unit test integration (or logger configuration maybe) But when I'm trying to unittest some class methods that have some app.logger I'm having troubles with RuntimeError: working outside of the application context So a practical example: utils.py import boto3 from flask import current_app as app class CustomError(BaseException): type = "boto" class BotoManager: def upload_to_s3(self, file): try: # do something that can trigger a boto3 error except boto3.exceptions.Boto3Error as e: app.logger.error(e) raise CustomError() test_utils.py import pytest from utils.py import CustomError, BotoManager def test_s3_manager_trigger_error(): boto_manager = BotoManager() with pytest.raises(CustomError): boto_manager.upload_to_s3('file.txt') # file doesn't exist so trigger error So the thing is that when I run it show me the error: RuntimeError: Working outside of application context. Becuase the app is not created and I'm not working with the app, so have sense. So I only see two possible solutions (spoiler I don't like any of them): Don't log anything with app.logger outside of the views (I think I can use the python logging system, but this is not the desired behaviour) Don't unittest the parts that use app.logger Did someone face this problem already? How did you solve it? Any other possible solution?
tagged with: logging
linked to: http://stackoverflow.com/q/48353929
score: 3
answer count: 0
tagged with: pytest
upvote count: 3

http://stackoverflow.com/q/50901077
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/70134541
has title: Ensuring user inputs only whole numbers when using BMI Analyzer
has answer: http://stackoverflow.com/a/50901267
upvote count: 3
has answer: http://stackoverflow.com/a/50901226
type: Question
tagged with: idl-programming-language
tagged with: if-statement
answer count: 3
has body: # This program calculates a person's BMI after # user inputs their height and weight, it then converts # the data from inches to meters and pounds to kilograms. # Based on findings the program displays persons BMI # Display welcome message. print( "Welcome to My BMI Calculator \n " ) # Ask the user to input their name. persons_name = input( 'Name of person that we are calculating the BMI for: ' ) # Ask for the user's height in inches. inches = float(input( 'Supply Height in Inches: ' )) # Ask for the user's weight in pounds. pounds = int(input( 'Supply Weight in Pounds: ' )) # Convert from inches to meters inches_to_meters = float(inches / 39.36) # Convert from pounds to kilograms pounds_to_kilograms = float(pounds / 2.2) # Calculate the person's BMI BMI = float(pounds_to_kilograms / ( inches_to_meters * inches_to_meters )) # Display the BMI print( persons_name, 'BMI is:' , format(BMI, '.2f' )) # Display person's BMI findings based on the given data if BMI &lt;= 18.50: print( 'BMI finding is the subject is: Underweight ' ) elif BMI &gt; 18.51 &lt; 24.90: print( 'BMI finding is the subject is: Normal ' ) elif BMI &gt; 24.91 &lt; 29.90: print( 'BMI finding is the subject is: Overweight ' ) elif BMI &gt; 29.90: print( 'BMI finding is the subject is: Obese ' ) I apologize in advance if I formatted this code wrong after pasting it here. If its wrong, please let me know, so I learn how to properly format it on this website. From what I understand, I indent each line by 4 spaces. Here is a BMI analyzer program that takes person's height in inches and converts it to meters, takes the persons weight in pounds and converts it to kilograms. After testing it, it seems to work, but only if you input whole numbers. So if you enter 0 for weight or 0 for height, there wont be an error, instead it will use that number in the BMI calculation. My question is: How do I make sure the user inputs only real numbers, no negatives, or numbers with decimal points, and if they do, to display …
score: 3
downvote count: 0
tagged with: string

http://stackoverflow.com/comment/88960144
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50964829
has text: If think "B" is a more generic approach so you can the trained network also to test on single table-cloth item and/or on a table with multiple table-cloth items. I think that performance depends mainly on how do you train the model w.r.t. the strategy.
type: AnswerComment

http://stackoverflow.com/a/50988494
has body: This should work: import random result = [''.join(random.choice('01') for _ in range(30))] for i in range(29): result.append(''.join(random.choice('01') for _ in range(5))) The result is: ['110100110100110111100001100001', '01111', '01011', '10110', '10101', '00011', '01010', '00110', '11000', '00111', '11001', '00001', '11001', '00111', '00001', '10011', '11011', '01100', '11001', '11001', '01100', '01101', '01010', '01111', '00111', '01100', '10001', '11111', '01111', '01011'] The ''.join() function joins an iterable of strings into a single string. '' is the delimiter. If you prefer lists of integers, then use this code: import random result = [random.choice([0, 1]) for _ in range(30)] for i in range(29): result.append([random.choice([0, 1]) for _ in range(5)])
score: 3
has comment: http://stackoverflow.com/comment/88971564
has comment: http://stackoverflow.com/comment/88972297
upvote count: 4
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88971922
type: Answer
has comment: http://stackoverflow.com/comment/88972146
accepted answer of: http://stackoverflow.com/q/50988346
has comment: http://stackoverflow.com/comment/88972372
answers question: http://stackoverflow.com/q/50988346
has comment: http://stackoverflow.com/comment/88972625
downvote count: 1

http://stackoverflow.com/comment/88791826
type: Comment
has text: then if we keep on increasing the epochs...will we overfit the model?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50892212

http://stackoverflow.com/comment/89002769
score: 0
comment on: http://stackoverflow.com/q/51003899
type: Comment
type: QuestionComment
has text: @Gev_2000 Yes, of course, you are right. Apologies, I misread your post.

http://stackoverflow.com/a/50894725
type: Answer
answers question: http://stackoverflow.com/q/50894444
score: 2
upvote count: 2
has body: What you could do is take the text from each row, split that into words and use the words and the row number to fill a new defaultdict(list) with the word as the key and the line number as data. In [1]: from collections import defaultdict In [2]: rows = ['This here is text', 'My Text was here', 'This was not ready'] In [3]: where = defaultdict(list) In [4]: for n, line in enumerate(rows): # A mockup for the pandas table. ...: for word in line.split(): ...: where[word.lower()].append(n) ...: In [5]: where Out[5]: defaultdict(list, {'here': [0, 1], 'is': [0], 'my': [1], 'not': [2], 'ready': [2], 'text': [0, 1], 'this': [0, 2], 'was': [1, 2]}) In a larger dataset you would find words in more than two rows. But using the list of line numbers, you can easily make all possible combinations to two lines using permutations: In [6]: from itertools import permutations In [7]: list(permutations([1,3,7], 2)) Out[7]: [(1, 3), (1, 7), (3, 1), (3, 7), (7, 1), (7, 3)] As the final step, you can merge the dictionaries from the original dataframe.
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50894444

http://stackoverflow.com/comment/88796407
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50886038
has text: When I tried doing this every temp_df row comes out as NaN

http://stackoverflow.com/comment/118304548
has text: Hi :), It seems like this answer has already been answered. If you have nothing extra to add to it, please consider removing this post.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/66924999

http://stackoverflow.com/q/50899488
has answer: http://stackoverflow.com/a/50899669
score: 0
accepted answer: http://stackoverflow.com/a/50899669
answer count: 1
tagged with: tensorflow
type: AnsweredQuestion
has title: Tensorflow python: reshape input [batchsize] to tensor [batchsize, 2] with specific order
has body: I have a tensor (shape=[batchsize]). I want to reshape the tensor in a specific order and into shape=[-1,2]. But I want to have: Element at [0,0] Element at [1,0] Element at [0,1] Element at [1,1] Element at [0,2] Element at [0,3] Element at [2,1] Element at [3,1] and so on for an unknow batchsize. Here is an example code with a tensor range=(0 to input=8). import tensorflow as tf import numpy as np batchsize = tf.placeholder(shape=[], dtype=tf.int32) x = tf.range(0, batchsize, 1) x = tf.reshape(x, shape=[2, -1]) y = tf.transpose(x) z = tf.reshape(y, shape=[-1, 2]) input = 8 with tf.Session() as sess: sess.run(tf.global_variables_initializer()) msg = sess.run([z], feed_dict={batchsize: input}) print(msg) Now my output is: [array([[0, 4], [1, 5], [2, 6], [3, 7]], dtype=int32)] But I want the output to be: [array([[0, 2], [1, 3], [4, 6], [5, 7]], dtype=int32)] Keep in mind I do not know how big batchsize is, I just set input= 8 for exemplary reason. Furthermore here I want to break the order after every 2nd element. In future I also would like to have this flexible. And in my real code the tensor ´x´ is no range array but complex random numbers, so you cannot sort in any way w.r.t. the values. I just made this code for a demonstration purpose.
tagged with: tensor
type: Question
tagged with: reshape
tagged with: python

http://stackoverflow.com/q/50996574
has answer: http://stackoverflow.com/a/68195480
has comment: http://stackoverflow.com/comment/119653385
score: 5
downvote count: 0
has title: error when trying to use keras.utils.plot_model
tagged with: keras
favorite count: 0
has answer: http://stackoverflow.com/a/79429982
has answer: http://stackoverflow.com/a/53999301
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50996755
linked to: http://stackoverflow.com/q/47188756
has answer: http://stackoverflow.com/a/67157093
tagged with: python
has answer: http://stackoverflow.com/a/71136951
has answer: http://stackoverflow.com/a/68312350
has answer: http://stackoverflow.com/a/67278641
has answer: http://stackoverflow.com/a/54003623
has answer: http://stackoverflow.com/a/72621358
tagged with: tensorflow
type: Question
upvote count: 5
has comment: http://stackoverflow.com/comment/119683498
has answer: http://stackoverflow.com/a/72842903
has answer: http://stackoverflow.com/a/77256708
answer count: 13
has body: I am trying to make a plot/graph of deep learning model in Python using Keras package but unfortunately it keeps giving me an error which is not very informative. I run python on Linux with Python 3.5.2, Anaconda 4.2.0, Keras 2.1.6 and I use tensorflow-gpu 1.7.0 Backend. Here is the error message: keras.utils.plot_model(unet, to_file='model.png', show_shapes=False, show_layer_names=True, rankdir='TB') ['dot', '-Tps', '/tmp/tmphesl1j0c'] return code: 127 stdout, stderr: b'' b'dot: error while loading shared libraries: libexpat.so.0: cannot open shared object file: No such file or directory\n' --------------------------------------------------------------------------- AssertionError Traceback (most recent call last) &lt;ipython-input-9-60bb0e3b97bd&gt; in &lt;module&gt;() ----&gt; 1 keras.utils.plot_model(unet, to_file='model.png', show_shapes=False, show_layer_names=True, rankdir='TB') /.../anaconda3-4.2.0/lib/python3.5/site-packages/keras/utils/vis_utils.py in plot_model(model, to_file, show_shapes, show_layer_names, rankdir) 132 'LR' creates a horizontal plot. 133 """ --&gt; 134 dot = model_to_dot(model, show_shapes, show_layer_names, rankdir) 135 _, extension = os.path.splitext(to_file) 136 if not extension: /.../anaconda3-4.2.0/lib/python3.5/site-packages/keras/utils/vis_utils.py in model_to_dot(model, show_shapes, show_layer_names, rankdir) 53 from ..models import Sequential 54 ---&gt; 55 _check_pydot() 56 dot = pydot.Dot() 57 dot.set('rankdir', rankdir) /.../anaconda3-4.2.0/lib/python3.5/site-packages/keras/utils/vis_utils.py in _check_pydot() 24 # Attempt to create an image of a blank graph 25 # to check the pydot/graphviz installation. ---&gt; 26 pydot.Dot.create(pydot.Dot()) 27 except OSError: 28 raise OSError( /.../anaconda3-4.2.0/lib/python3.5/site-packages/pydot.py in create(self, prog, format, encoding) 1882 out=stdout_data, 1883 err=stderr_data)) -&gt; 1884 assert p.returncode == 0, p.returncode 1885 return stdout_data AssertionError: 127 I would really…
has answer: http://stackoverflow.com/a/60230624

http://stackoverflow.com/comment/88840758
comment on: http://stackoverflow.com/q/50920618
has text: To achieve what you want, this is not perfect but it might works. Make file which contains "===========" name as 'line.file'. Change inside of loop as follow. os.system("cat line.file") os.system("tail -n 2 " + log_path + "" + i)
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88912797
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50956747
has text: Ah, hood you figured it out! I was just typing that out in an answer... :)

http://stackoverflow.com/q/50972285
tagged with: rpy2
possible better answer: http://stackoverflow.com/a/63843546
score: 0
answer count: 2
has body: A now closed discussion shows how to use the R dtw package in python. This is a little clumsy, but the R dtw package is great and better than currently available python dtw implementations. Unfortunately, the windowing functions like the Sakoe-Chiba band do not work when trying to specify a "window.size". There appears to be an issue with the mapping to the argument. Note that "." in arguments is supposed to be replaced with "_" when using rpy2. But following this convention, the argument is not being used for some reason. import numpy as np import rpy2.robjects.numpy2ri from rpy2.robjects.packages import importr rpy2.robjects.numpy2ri.activate() # Set up our R namespaces R = rpy2.robjects.r DTW = importr('dtw') # Generate our data idx = np.linspace(0, 2*np.pi, 100) template = np.cos(idx) query = np.sin(idx) + np.array(R.runif(100))/10 # Calculate the alignment vector and corresponding distance alignment = R.dtw(query, template, keep=True,window_type='sakoechiba', window_size=5) &gt;&gt;&gt; RRuntimeError: Error in window.function(row(wm), col(wm), query.size= n, reference.size = m, : argument "window.size" is missing, with no default You can see that the error states "window.size" is missing, despite "window_size" clearly being specified in the rpy2 fashion.
has title: rpy2 Dynamic Time Warping (dtw) in python - windowing does not work
tagged with: python
tagged with: dtw
has answer: http://stackoverflow.com/a/63843546
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50972944
type: Question
accepted answer: http://stackoverflow.com/a/50972944
linked to: http://stackoverflow.com/q/5695388

http://stackoverflow.com/comment/88735185
has text: Thanks a lot Jean-François for your kind help and explanations! I am still struggling a bit to have all this nested in a for loop. I created a related question [here](https://stackoverflow.com/questions/50866386/subprocess-popen-inside-a-for-loop-how-to-properly-get-its-output). If it happens that you also have an answer there, your help would also be appreciated :)
type: Comment
score: 0
comment on: http://stackoverflow.com/a/50863371
type: AnswerComment

http://stackoverflow.com/q/51002998
tagged with: class
type: Question
tagged with: python-import
has comment: http://stackoverflow.com/comment/88999812
duplicate of: http://stackoverflow.com/q/38649575
has body: I'm quite new to python and I'm working on an application with singleton classes (I know what people say about singletons, but they're suitable for my needs), but I encountered a problem which isn't caused by the singletons but does prevent them from working properly. Consider this code (which doesn't involve singletons): main.py class Test: pass def main(): print("main.py:", Test, id(Test)) import test if __name__ == '__main__': main() test.py from main import Test print("test.py:", Test, id(Test)) results: main.py: &lt;class '__main__.Test'&gt; 1382824602424 test.py: &lt;class 'main.Test'&gt; 1382824594872 It looks like the Test class in main.py is not the same as the one in test.py (they have different name and id), so the Test class was duplicated when imported in test.py? note: I tried that with import main and main.Test instead - same results. This strange behavior of python actually prevents my implementation of singletons from working correctly. Here's the singleton metaclass implementation: from collections import defaultdict # A `defaultdict` subclass which passes the missing key # as an argument to `default_factory` class KeyDefaultDict(defaultdict): def __missing__(self, key): if self.default_factory is None: raise KeyError(key) res = self[key] = self.default_factory(key) return res class Singleton(type): # a dictionary that maps between the singleton class # and the singleton object of that class. When attempting # to access the singleton object for the first time (via # the `instance` property), the object will be created and # added to the dictionary (lazy initialization). __instances = KeyDefaultDict(type.__call__) def __new__(mcs, name, bases, dct): # prevent inheritance from a singleton class for base in bases: if isinstance(base, mcs): raise TypeError("Singletons can't be inherited from") return super().__new__(mcs, name, bases, dct) def __call__(cls, *args, **kwargs): raise TypeError("Singletons can't be instantiated") @property def instance(cls)…
score: 0
tagged with: singleton
tagged with: python
has comment: http://stackoverflow.com/comment/88999743
has title: Importing class from the main script creates a duplicate of that class?
answer count: 0
linked to: http://stackoverflow.com/q/38649575
type: UnansweredQuestion

http://stackoverflow.com/q/50983508
has comment: http://stackoverflow.com/comment/88962893
score: 0
has comment: http://stackoverflow.com/comment/88961922
tagged with: url
type: UnansweredQuestion
has body: Why does url disappear from python scrapy? disappear_url = 'https://disqus.com/embed/comments/?base=default&amp;f=zdnet-1&amp;t_i=5d1b4eb7-9581-4eaa-acb9-5fbc6c15bdb7&amp;t_u=https%3A%2F%2Fwww.zdnet.com%2Fproduct%2Fsamsung-chg9-series-c49hg90dmn-qled-monitor-curved-49%2F&amp;t_e=Samsung%2049%20inch%20QLED%20business%20monitor%20review%3A%20Multi-tasking%20single%20monitor%20setup&amp;t_d=Samsung%2049%20inch%20QLED%20business%20monitor%20review%3A%20Multi-tasking%20single%20monitor%20setup&amp;t_t=Samsung%2049%20inch%20QLED%20business%20monitor%20review%3A%20Multi-tasking%20single%20monitor%20setup&amp;s_o=default#version=48537a333e429dcb726ce9cdcc57a44f' I tried this. scrapy shell disppear_url response.url https://disqus.com/embed/comments/?base=default&amp;f=zdnet-1&amp;t_i=5d1b4eb7-9581-4eaa-acb9-5fbc6c15bdb7&amp;t_u=https%3A%2F%2Fwww.zdnet.com%2Fproduct%2Fsamsung-chg9-series-c49hg90dmn-qled-monitor-curved-49%2F&amp;t_e=Samsung%2049%20inch%20QLED%20business%20monitor%20review%3A%20Multi-tasking%20single%20monitor%20setup&amp;t_d=Samsung%2049%20inch%20QLED%20business%20monitor%20review%3A%20Multi-tasking%20single%20monitor%20setup&amp;t_t=Samsung%2049%20inch%20QLED%20business%20monitor%20review%3A%20Multi-tasking%20single%20monitor%20setup&amp;s_o=default response.request.url https://disqus.com/embed/comments/?base=default&amp;f=zdnet-1&amp;t_i=5d1b4eb7-9581-4eaa-acb9-5fbc6c15bdb7&amp;t_u=https%3A%2F%2Fwww.zdnet.com%2Fproduct%2Fsamsung-chg9-series-c49hg90dmn-qled-monitor-curved-49%2F&amp;t_e=Samsung%2049%20inch%20QLED%20business%20monitor%20review%3A%20Multi-tasking%20single%20monitor%20setup&amp;t_d=Samsung%2049%20inch%20QLED%20business%20monitor%20review%3A%20Multi-tasking%20single%20monitor%20setup&amp;t_t=Samsung%2049%20inch%20QLED%20business%20monitor%20review%3A%20Multi-tasking%20single%20monitor%20setup&amp;s_o=default#version=48537a333e429dcb726ce9cdcc57a44f help me.
tagged with: python
has comment: http://stackoverflow.com/comment/88968387
answer count: 0
has title: Why does url disappear from python scrapy?
has comment: http://stackoverflow.com/comment/88962262
tagged with: scrapy
has comment: http://stackoverflow.com/comment/88962070
type: Question

button
tags question: http://stackoverflow.com/q/50910764
tags question: http://stackoverflow.com/q/50982097
tags question: http://stackoverflow.com/q/50946084
type: Tag
tags question: http://stackoverflow.com/q/50868751
tags question: http://stackoverflow.com/q/50899563
tag name: button

http://stackoverflow.com/a/50993188
has comment: http://stackoverflow.com/comment/88981142
answers question: http://stackoverflow.com/q/50993165
has body: Use pd.to_datetime and specify the unit as microseconds. Mind that the microseconds unit is us (I didn't know that a few minutes ago (-:) df['Event Time'] = pd.to_datetime(df['Event Time'], unit='us') MCVE df = pd.DataFrame({'Event Time': [1519952249827533]}) df['Event Time'] = pd.to_datetime(df['Event Time'], unit='us').dt.floor('s') df Event Time 0 2018-03-02 00:57:29 If you wanted a string result instead of Timestamps use strftime pd.to_datetime(df['Event Time'], unit='us').dt.strftime('%Y-%m-%d %H:%M:%S') 0 2018-03-02 00:57:29 Name: Event Time, dtype: object See strftime.org for more info on using strftime.
has comment: http://stackoverflow.com/comment/88981052
type: Answer
has comment: http://stackoverflow.com/comment/88981549
has comment: http://stackoverflow.com/comment/88981189
score: 3
has comment: http://stackoverflow.com/comment/88981005
has comment: http://stackoverflow.com/comment/88981247
upvote count: 3
has comment: http://stackoverflow.com/comment/88980907
has comment: http://stackoverflow.com/comment/88981311
has comment: http://stackoverflow.com/comment/88980936
has comment: http://stackoverflow.com/comment/88981251
has comment: http://stackoverflow.com/comment/88981453
has comment: http://stackoverflow.com/comment/88981091
has comment: http://stackoverflow.com/comment/88981161
downvote count: 0
has comment: http://stackoverflow.com/comment/88981512
has comment: http://stackoverflow.com/comment/88981030

http://stackoverflow.com/comment/88716684
type: Comment
has text: They are not modifying the collection that they iterate over (a list) they are modifying the string, which effects the resulting counts of course
type: AnswerComment
comment on: http://stackoverflow.com/a/50857053
score: 0

http://stackoverflow.com/a/50893483
answers question: http://stackoverflow.com/q/50893347
type: Answer
score: 11
downvote count: 0
upvote count: 11
has body: Tuples are immutable.So you have to replace it .Here _ is meant to avoid conflict with fieldnames ._replace from urllib.parse import parse_qs, urlencode, urlsplit url = 'http://example.com/?page=1&amp;text=test#section' param, newvalue = 'page', '2' parsed = urlsplit(url) query_dict = parse_qs(parsed.query) query_dict[param][0] = newvalue query_new = urlencode(query_dict, doseq=True) parsed=parsed._replace(query=query_new) url_new = (parsed.geturl())

http://stackoverflow.com/q/50992156
has answer: http://stackoverflow.com/a/51025430
score: 3
has body: I am fairly new to SNS and Lambda. I have successfully created a SNS topic and I am able to send a text message. I did set up an S3 event when a file was uploaded. However, I would like to change the text of that message and therefore created a Lambda function from a blueprint that is supposed to send a message to the SNS topic. Here is a screenshot of the Designer This is the blueprint code I am using: from __future__ import print_function import json import urllib import boto3 print('Loading message function...') def send_to_sns(message, context): # This function receives JSON input with three fields: the ARN of an SNS topic, # a string with the subject of the message, and a string with the body of the message. # The message is then sent to the SNS topic. # # Example: # { # "topic": "arn:aws:sns:REGION:123456789012:MySNSTopic", # "subject": "This is the subject of the message.", # "message": "This is the body of the message." # } sns = boto3.client('sns') sns.publish( TopicArn=message['arn:aws:sns:MySNS_ARN'], Subject=message['File upload'], Message=message['Files uploaded successfully'] ) return ('Sent a message to an Amazon SNS topic.') When testing the Lamda function, I receive the following error: Response: { "stackTrace": [ [ "/var/task/lambda_function.py", 25, "send_to_sns", "TopicArn=message['arn:aws:sns:MySNS_ARN']," ] ], "errorType": "KeyError", "errorMessage": "'arn:aws:sns:MySNS_ARN'" } Request ID: "7253aa4c-7635-11e8-b06b-838cbbafa9df" Function Logs: START RequestId: 7253aa4c-7635-11e8-b06b-838cbbafa9df Version: $LATEST 'arn:aws:sns:MySNS_ARN': KeyError Traceback (most recent call last): File "/var/task/lambda_function.py", line 25, in send_to_sns TopicArn=message['arn:aws:sns:MySNS_ARN'], KeyError: 'arn:aws:sns:MySNS_ARN' END RequestId: 7253aa4c-7635-11e8-b06b-838cbbafa9df REPORT RequestId: 7253aa4c-7635-11e8-b06b-838cbbafa9df Duration: 550.00 ms Billed Duration: 600 ms Memory Size: 128 MB Max Memory Used: 30 MB I am not sure I understand what is goin…
tagged with: amazon-web-services
answer count: 2
has answer: http://stackoverflow.com/a/50995992
downvote count: 0
tagged with: aws-lambda
favorite count: 0
has title: AWS Lambda function to trigger SNS topic on S3 upload
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50995992
tagged with: amazon-s3
upvote count: 3
tagged with: amazon-sns
possible better answer: http://stackoverflow.com/a/51025430
type: Question

http://stackoverflow.com/comment/88948791
has text: Ok, reopened. Someone can tie those elements together. I still think that most of the relevant information is embedded in that answer.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50970859

http://stackoverflow.com/a/50864968
accepted answer of: http://stackoverflow.com/q/50864930
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50864930
has comment: http://stackoverflow.com/comment/88732646
downvote count: 0
has body: This can be done with shutil's rmtree function. So long as PATH is the directory you want deleted, just check to make sure your subprocess has finished, and then just run shutil.rmtree(PATH) If you need to wait until your subprocess is done, you can accomplish this by calling .poll() on your proc and waiting for it to return None. For example: while proc.poll() == None: # .poll() will return a value once it's complete. time.sleep(1) [then remove your directory here]
has comment: http://stackoverflow.com/comment/88732959
type: AcceptedAnswer

http://stackoverflow.com/comment/88793651
type: Comment
type: QuestionComment
has text: I don't think bulk mtime requests are possible, but retrieving the mtimes of 10,000 files is hardly the slowest operation. Have you tried profiling your code and finding other slow parts? Perhaps it would be worth to optimize those...
comment on: http://stackoverflow.com/q/50896965
score: 0

http://stackoverflow.com/q/51010963
tagged with: loss-function
tagged with: tensorflow
type: Question
answer count: 1
accepted answer: http://stackoverflow.com/a/51010994
tagged with: keras
has body: I am currently programming an autoencoder for image compression. I would like to use a custom loss function written in pure python, i.e. without making use of keras backend functions. Is this at all possible and if so how? If it is possible I'd be very grateful for a minimum working example (MWE). Please look at this MWE, in particular the mse_keras function: # -*- coding: utf-8 -*- import matplotlib.pyplot as plt import numpy as np import keras.backend as K from keras.datasets import mnist from keras.models import Model, Sequential from keras.layers import Input, Dense def mse_keras(A,B): mse = K.mean(K.square(A - B), axis=-1) return mse # Loads the training and test data sets (ignoring class labels) (x_train, _), (x_test, _) = mnist.load_data() # Scales the training and test data to range between 0 and 1. max_value = float(x_train.max()) x_train = x_train.astype('float32') / max_value x_test = x_test.astype('float32') / max_value x_train.shape, x_test.shape # ((60000, 28, 28), (10000, 28, 28)) x_train = x_train.reshape((len(x_train), np.prod(x_train.shape[1:]))) x_test = x_test.reshape((len(x_test), np.prod(x_test.shape[1:]))) (x_train.shape, x_test.shape) # ((60000, 784), (10000, 784)) # input dimension = 784 input_dim = x_train.shape[1] encoding_dim = 32 compression_factor = float(input_dim) / encoding_dim print("Compression factor: %s" % compression_factor) autoencoder = Sequential() autoencoder.add(Dense(encoding_dim, input_shape=(input_dim,), activation='relu')) autoencoder.add(Dense(input_dim, activation='sigmoid')) autoencoder.summary() input_img = Input(shape=(input_dim,)) encoder_layer = autoencoder.layers[0] encoder = Model(input_img, encoder_layer(input_img)) encoder.summary() autoencoder.compile(optimizer='adam', loss=mse_keras, metrics=['mse']) history=autoencoder.fit(x_train, x_train, epochs=3, batch_size=256, shuffle=True, validation_data=(x_test, x_test)) num_images = 10 np.random.seed(42) random_test_images = np.random.randint(x_test.shape[0], siz…
downvote count: 0
favorite count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/89030549
tagged with: python
has answer: http://stackoverflow.com/a/51010994
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89014719
has title: keras custom loss pure python (without keras backend)

http://stackoverflow.com/q/50876702
has answer: http://stackoverflow.com/a/61637298
has answer: http://stackoverflow.com/a/55248113
favorite count: 0
has answer: http://stackoverflow.com/a/73019860
type: UnansweredQuestion
tagged with: windows
tagged with: python
score: 31
has comment: http://stackoverflow.com/comment/88842034
has answer: http://stackoverflow.com/a/70815031
upvote count: 31
tagged with: fiona
has title: Can't install Fiona on Windows
type: Question
has answer: http://stackoverflow.com/a/61483254
answer count: 8
has answer: http://stackoverflow.com/a/60767145
downvote count: 0
has answer: http://stackoverflow.com/a/73681158
has answer: http://stackoverflow.com/a/72936761
has body: I've done a software on Ubuntu, and I'm having several problems running this software on Windows. My biggest issue point now is that I'm trying to install "fiona" - I have it already installed on my PIP packages - but for some reason it's not working. So I've tried to install it via setup download from the original repository. By following the rules: using python setup.py install I've already added some environment variables as: GDAL_DATA GDAL_DRIVER_PATH and beyond that I've added on variable PATH the path of GDAL There's another way to do it, by using another command but I don't how would it be gdal include files gdal library python setup.py build_ext -I<path to gdal include files> -lgdal_i -L<path to gdal library> install --gdalversion 2.1 My current version of GDAL is GDAL 1.11.4, released 2016/01/25 I'd already tried with 2.3 etc. and it didn't work. I've tried using only this command: python setup.py install --gdalversion 1.11 fiona/_geometry.c(578) : fatal error C1083: Cannot open include file: 'ogr_api.h ': No such file or directory Which results when I try to use a software that has fiona, I receive the following error: import fiona File "C:\Python27\fiona\__init__.py", line 81, in <module> from fiona.collection import Collection, BytesCollection File "C:\Python27\fiona\collection.py", line 9, in <module> from fiona.ogrext import Iterator, ItemsIterator, KeysIterator ImportError: No module named ogrext

http://stackoverflow.com/a/50877468
score: 1
has comment: http://stackoverflow.com/comment/88757056
downvote count: 0
answers question: http://stackoverflow.com/q/50877247
type: Answer
has comment: http://stackoverflow.com/comment/102150485
upvote count: 1
has body: It looks like what your values are in this screenshot is not "NaN" or some real error, but a parsed string of the value "na". In order to filter out the rows with this value in this column, you can use to simply refer to the df with a condition, instead of using dropna: df = pd.read_csv(...) filtered_df = df[df['Filmname'] != 'na'] The condition inside may be anything, see this guide for a start

http://stackoverflow.com/q/50876396
favorite count: 0
type: Question
has title: CTest custom target for python scripts with arguments
tagged with: python
has body: I would like to be able to run some python unit tests apart from other tests by means of CTest and the following command: make unit_tests I tried the following combination but it does not work: ADD_TEST(unit_test_1 ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/unit_test_1.py --verbose) ADD_TEST(unit_test_2 ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/unit_test_2.py --verbose) ADD_CUSTOM_TARGET(unit_tests COMMAND ${CMAKE_CTEST_COMMAND} DEPENDS unit_test_1 unit_test_2) Do you know how to do it?
upvote count: 1
tagged with: cmake
answer count: 1
type: UnansweredQuestion
tagged with: ctest
has answer: http://stackoverflow.com/a/50876939
downvote count: 0
score: 1

http://stackoverflow.com/a/50881808
has comment: http://stackoverflow.com/comment/88765961
has comment: http://stackoverflow.com/comment/88766383
has comment: http://stackoverflow.com/comment/88766128
has comment: http://stackoverflow.com/comment/88766382
answers question: http://stackoverflow.com/q/50881693
downvote count: 0
has comment: http://stackoverflow.com/comment/88766322
has comment: http://stackoverflow.com/comment/88766173
has comment: http://stackoverflow.com/comment/88766152
has comment: http://stackoverflow.com/comment/88766401
has comment: http://stackoverflow.com/comment/88765990
has comment: http://stackoverflow.com/comment/88766495
type: Answer
has comment: http://stackoverflow.com/comment/88765947
has body: After discussion and testing in various versions, the final conclusions can be drawn. Python will interpret and compile instructions in blocks. Depending on the syntax used, Python version, Operating System, distribution, different results may be achieved depending on what instructions Python takes in one block. The general rules are: (from official documentation) The current implementation keeps an array of integer objects for all integers between -5 and 256 Therefore: a = 256 id(a) Out[2]: 1997190544 id(256) Out[3]: 1997190544 # int actually stored once within Python a = 257 id(a) Out[5]: 2365489141456 id(257) Out[6]: 2365489140880 #literal, temporary. as you see the ids differ id(257) Out[7]: 2365489142192 # literal, temporary. as you see it gets a new id everytime # since it is not pre-stored The part below returns False in Python 3.6.3 |Anaconda custom (64-bit)| (default, Oct 17 2017, 23:26:12) [MSC v.1900 64 bit (AMD64)] a = 257; a is 257 Out[8]: False But a=257; print(a is 257) ; a=258; print(a is 257) &gt;&gt;&gt;True &gt;&gt;&gt;False As it is evident, whatever Python takes in "one block" is non deterministic and can be swayed depending on how it is written, single line or not, as well as the version, operating system and distribution used.
upvote count: 2
score: 2

http://stackoverflow.com/q/50865730
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51105407
answer count: 1
downvote count: 0
has title: Add output to the "FAILURES" section of a test, while not capturing stdout
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: I have a custom decorator on my tests that just gives some extra info to the test. I'd like that when a test fails, I can print some of this info and have it show up in the failures section, so our build tools can display it well. Right now I just have some code that looks like this: @pytest.hookimpl(tryfirst=True, hookwrapper=True) def pytest_runtest_makereport(item, call): outcome = yield if outcome.get_result().outcome != "passed": print("Some extra info: {}".format(item.function.detail1)) The problem is that this when a test fails I get output that looks like this: test_foo.py .Some extra info: more info F ================================== FAILURES =================================== __________________________________ test_foo2 __________________________________ @info("more info") def test_foo(): &gt; raise ValueError("OH NO") E ValueError: OH NO test_foo.py:11: ValueError I'd like the Some extra info: more info to showup in that bottom section. Is it possible to hook into this somehow?
tagged with: pytest
score: 1

http://stackoverflow.com/comment/88745882
comment on: http://stackoverflow.com/a/50862115
type: AnswerComment
has text: great this works, hut how can i store i store the output of the second execution to a variable ?
score: 0
type: Comment

http://stackoverflow.com/comment/88874540
has text: if the end time is before starttime, i guess we need to raise an error
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50938119

http://stackoverflow.com/a/50953881
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50952667
type: Answer
score: 3
downvote count: 0
upvote count: 3
has body: Try that way: r = sr.Recognizer() m = sr.Microphone(device_index=2) def loop(): with m as source: print("say something") audio = r.listen(source) try: print("you said "+r.recognize_google(audio)) except sr.UnknownValueError: print("Could not understand") except sr.RequestError as e: print("errpr: {0}".format(e)) loop() Don't create multiple Microphone() instances.
answers question: http://stackoverflow.com/q/50952667

http://stackoverflow.com/a/50930591
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/50913988
answers question: http://stackoverflow.com/q/50913988
upvote count: 1
type: AcceptedAnswer
has body: pywinauto is a Python module to automatize graphical user interface (GUI) operations for example to simulate mouse clicking and everything else humans used to do on GUIs to interact with the computer. SSH is a remote access protocol designed primarily for command line and having excellent programmatic support in Python. Putty is a little GUI tool to manage SSH and Telnet connections. Although, based on quick check, I think it is possible to read the console output (you mean in cmd.com?) by pywinauto, I think your approach is unnecessarily complicated: you don't need to use a GUI tool designed for human interaction to access a protocol with excellent command line and programmatic library support. I suggest you to use paramiko which gives a very simple and convenient interface to SSH: import paramiko def ssh_connect(server, **kwargs): client = paramiko.client.SSHClient() client.load_system_host_keys() # note: here you can give other paremeters # like user, port, password, key file, etc. # also you can wrap the call below into # try/except, you can expect many kinds of # errors here, if the address is unreachable, # times out, authentication fails, etc. client.connect(server, **kwargs) return client servers = ['10.55.167.4', '10.56.127.23'] # connect to all servers clients = dict((server, ssh_connect(server)) for server in servers) # execute commands on the servers by the clients, 2 examples: stdin, stdout, stderr = clients['10.55.167.4'].exec_command('pwd') print(stdout.read()) # b'/home/denes\n' stdin, stdout, stderr = clients['10.56.127.23'].exec_command('rm foobar') print(stderr.read()) # b"rm: cannot remove 'foobar': No such file or directory\n" # once you finished close the connections _ = [cl.close() for cl in clients.values()]
type: Answer

http://stackoverflow.com/comment/88815780
comment on: http://stackoverflow.com/q/50907764
type: Comment
score: 2
has text: `dateutil.parser.isoparse('0001-04-23T01:25:43.511Z')` gives `datetime.datetime(1, 4, 23, 1, 25, 43, 511000, tzinfo=tzutc())` - but so does simple parse. I can't reproduce this.
type: QuestionComment

http://stackoverflow.com/q/50923413
answer count: 2
tagged with: pandas
has body: I tried to open .csv file on google csv by this way import pandas as pd from google.colab import files uploaded = files.upload() for fn in uploaded.keys(): print('User uploaded file "{name}" with length {length} bytes'.format( name=fn, length=len(uploaded[fn]))) import io df = pd.read_csv(io.StringIO(uploaded['test.csv'].decode('utf-8'))) But I got an error : ParserError Traceback (most recent call last) &lt;ipython-input-6-7c1e8871ef06&gt; in &lt;module&gt;() 1 import io ----&gt; 2 df = pd.read_csv(io.StringIO(uploaded['test.csv'].decode('utf-8'))) 3 print(df) /usr/local/lib/python3.6/dist-packages/pandas/io/parsers.py in parser_f(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, squeeze, prefix, mangle_dupe_cols, dtype, engine, converters, true_values, false_values, skipinitialspace, skiprows, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, dayfirst, iterator, chunksize, compression, thousands, decimal, lineterminator, quotechar, quoting, escapechar, comment, encoding, dialect, tupleize_cols, error_bad_lines, warn_bad_lines, skipfooter, skip_footer, doublequote, delim_whitespace, as_recarray, compact_ints, use_unsigned, low_memory, buffer_lines, memory_map, float_precision) 707 skip_blank_lines=skip_blank_lines) 708 --&gt; 709 return _read(filepath_or_buffer, kwds) 710 711 parser_f.__name__ = name /usr/local/lib/python3.6/dist-packages/pandas/io/parsers.py in _read(filepath_or_buffer, kwds) 453 454 try: --&gt; 455 data = parser.read(nrows) 456 finally: 457 parser.close() /usr/local/lib/python3.6/dist-packages/pandas/io/parsers.py in read(self, nrows) 1067 raise ValueError('skipfooter not supported for iteration') 1068 -&gt; 1069 ret = self._engine.read(nrows) 1070 1071 if self.options.get('as_recarray'): /usr/local/lib/python3.6/dist-packages/pandas/io/parsers.py in read(self, nrows) 1837 def read(self, nrows=None): 1838 try: -&gt; 1839 data = self._reader…
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has title: Google colab open csv file
type: Question
has comment: http://stackoverflow.com/comment/88846176
has answer: http://stackoverflow.com/a/50932312
has answer: http://stackoverflow.com/a/50923727
tagged with: google-colaboratory
score: 0

http://stackoverflow.com/comment/88968027
comment on: http://stackoverflow.com/q/50986580
has text: Apparently someone has a workaround here. https://github.com/keras-team/keras/issues/7362
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88783886
has text: Strictly speaking you don't really need `elif` (just `if`) or `else` clauses because each clause returns.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50891542
score: 1

http://stackoverflow.com/comment/93149645
has text: sorry for late reply, I did worked on zscore approach, but i worked in some different way, Thank you so much for your kind reply
score: 0
comment on: http://stackoverflow.com/a/51018875
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/89014022
type: AnswerComment
has text: Thank you Eugene. Shall try this code and keep it in mind as an alternative.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51010458

http://stackoverflow.com/comment/88882974
type: Comment
type: QuestionComment
has text: You want something that will print the line about to execute right before it executes?
comment on: http://stackoverflow.com/q/50942365
score: 0

http://stackoverflow.com/comment/88940332
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50971784
type: Comment
has text: Thank you your support!! post_list.html was located outside. So I put it in

http://stackoverflow.com/q/50868309
tagged with: freeze
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88738614
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88755765
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/50869271
tagged with: remote-server
has comment: http://stackoverflow.com/comment/88739252
downvote count: 0
answer count: 1
has body: I have a python script called ergo.py on my local machine and I want to run it on a remote machine but I have a couple of issues: The remote machine has python 2.x installed on it but my code is written in python 3.x The remote machine doesn't have python modules like numpy or matplotlib. I only have ssh access to remote machine and I don't have sudo privilege or any root access I even don't have sudo privilege or any root access on my local machine but I have python 3.6.3 and anaconda packages installed on it which make me able to write my codes with Pycharm IDE. The remote machine and my local system both have Linux Red hat 7.x operating systems. What is my best way to run my codes on the remote machine. I tried to freeze my code using pyinstaller, bbfreeze and cx_freeze but I didn't succeed, each time becasue of a specific error so I quitted this option.
score: 1
tagged with: virtualenv
has comment: http://stackoverflow.com/comment/88738783
has title: Run a python script on a remote machine without sudo previlage
has comment: http://stackoverflow.com/comment/88740231
favorite count: 0
tagged with: python

http://stackoverflow.com/comment/88810699
comment on: http://stackoverflow.com/q/50905462
type: Comment
type: QuestionComment
score: 4
has text: For `i=4` you run `j` in the range `(2,2)`, which is an empty range. If you increase the endpoint by one, you will find a factor.

http://stackoverflow.com/comment/88732518
type: QuestionComment
score: 2
has text: `a` and `b` are results of your function, you're returning a tuple... Just time the main fibonacci call from _outside_ the function.
comment on: http://stackoverflow.com/q/50864956
type: Comment

http://stackoverflow.com/q/50955605
has answer: http://stackoverflow.com/a/50957014
accepted answer: http://stackoverflow.com/a/50955743
upvote count: 2
tagged with: django
type: Question
has body: I am trying to access my followers in the available module, I can get the number of count such as the number of followers and number of followings but I can't get the list of followers to see my followers. Need suggestions. My module.py File: from django.db import models class FollowerFollowing(models.Model): user_from = models.ForeignKey('User', on_delete=models.SET_NULL, null=True, related_name='rel_from_set') user_to = models.ForeignKey('User', on_delete=models.SET_NULL, null=True, related_name='rel_to_set') created = models.DateTimeField(auto_now_add=True, db_index=True) class Meta: ordering = ('-created',) def __str__(self): return '{} follows {}'.format(self.user_from, self.user_to) User.add_to_class('following', models.ManyToManyField('User', through=FollowerFollowing, related_name='followers', symmetrical=False)) My views.py File: def follower(request): print(request) if request.session['user_id']: query = FollowerFollowing.objects.filter(user_from=request.user) print(query) context = { 'query': query } return render(request, 'Instagram_app/following.html', context) else: pass return HttpResponse("No user logged in") follower.html (template) {% extends 'Instagram_app/home.html'%} {% block content %} following {% for result in query %} {{ result }} {% endfor %} {% endblock %} Console error is: (value, opts.object_name)) ValueError: Cannot query "mayur": Must be "User" instance. [20/Jun/2018 11:45:27] "GET /Instagram_app/follower HTTP/1.1" 500 105165 Need suggestions to solve this problem. Thank you
type: AnsweredQuestion
tagged with: django-views
has title: How can I resolve query object error - ValueError: Cannot query "mayur": Must be "User" instance
tagged with: django-models
answer count: 2
has answer: http://stackoverflow.com/a/50955743
score: 2
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/50957014
tagged with: python

http://stackoverflow.com/a/50916808
downvote count: 0
has comment: http://stackoverflow.com/comment/92343265
accepted answer of: http://stackoverflow.com/q/50915207
type: Answer
answers question: http://stackoverflow.com/q/50915207
has comment: http://stackoverflow.com/comment/88834177
score: 1
upvote count: 1
has body: driver = webdriver.Chrome(executable_path=exe_path) Are you sure you use chrome? Maybe change the webdriver.Chrome
type: AcceptedAnswer

http://stackoverflow.com/q/50972167
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/50972522
tagged with: pandas
answer count: 1
downvote count: 0
score: 1
favorite count: 0
has body: I want to use python's pandas for some simple matrix calculation and encountered one problem when trying to do the following simple multiplication: df = df.mul(column, axis=1) df is one 3x3 dataframe and looks like: 441090707 441090801 441090408 441090408 0.255061 0.202650 0.689114 441090707 0.287952 0.218351 0.116750 441090801 0.456987 0.578998 0.194136 while column is one series which looks like: area 441090707 179.727362 441090801 698.939741 441090408 1377.909774 Name: Test, dtype: float64 The multiplication throws a RuntimeWarning ('&lt;' not supported between instances of 'str' and 'int', sort order is undefined for incomparable objects) and returns the following: 441090707 441090801 ... 441090801 441090408 441090408 NaN NaN ... NaN NaN 441090707 NaN NaN ... NaN NaN 441090801 NaN NaN ... NaN NaN As the documentation states "Mismatched indices will be unioned together", so there seems to be a problem with my index. But I can't figure out how to make the series-indices match the dataframe- columns. (The multiplication worked when I used "column.values", but this is not a solution because the order of the series might change)
has comment: http://stackoverflow.com/comment/88941202
has answer: http://stackoverflow.com/a/50972522
tagged with: python
has title: Columnwise Multiplication of Pandas Dataframe with Series (missmatched indices)
type: AnsweredQuestion

http://stackoverflow.com/q/50882880
possible better answer: http://stackoverflow.com/a/50882947
has answer: http://stackoverflow.com/a/50882947
linked to: http://stackoverflow.com/q/44413020
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/50882960
has body: My following code: import numpy as np from matplotlib import pyplot as plt from matplotlib.pyplot import legend as legend x = np.matrix( [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4] ] ) y = x.transpose() xx = x yy = y+0.2 # Vertical Lines of grid: plt.plot(x, y, 'b-o', label='data1') plt.plot(xx, yy, 'r-*', label='data2') legend() plt.show() generates figures looking like I'd like to do two things: stop the legend from duplicating it self; it should only show each label once; something like position the legend nicely; say put it upper right corner with no overlap with the content of the graph Easy/elegant solution is really appreciated. Thanks a lot.
has comment: http://stackoverflow.com/comment/88768095
score: 0
tagged with: legend
has title: legend() duplicating itself
accepted answer: http://stackoverflow.com/a/50882960
tagged with: python
tagged with: plot
type: AnsweredQuestion

http://stackoverflow.com/q/50945364
upvote count: 1
has comment: http://stackoverflow.com/comment/88892150
type: Question
has body: I am trying to paste values from one sheet to another within a google spreadsheet using the code below in python 3.6. from apiclient.discovery import build from httplib2 import Http from oauth2client import file, client, tools SCOPES = 'https://www.googleapis.com/auth/spreadsheets' store = file.Storage('credentials.json') creds = store.get() if not creds or creds.invalid: flow = client.flow_from_clientsecrets('client_secret.json', SCOPES) creds = tools.run_flow(flow, store) service = build('sheets', 'v4', http=creds.authorize(Http())) spreadsheet_id = 'XXXXXXXXXXXXXXXXX' request_body = { 'requests': [{ 'copyPaste':{ "source": { "sheetId": XXXXXX, "startRowIndex": 0, "endRowIndex": 1000, "startColumnIndex": 0, "endColumnIndex": 5 }, "destination": { "sheetId": XXXXXXXX, "startRowIndex": 0, "endRowIndex": 1000, "startColumnIndex": 0, "endColumnIndex": 5 }, "pasteOrientation": "NORMAL", "pasteType": "PASTE_VALUES" } }] } request = service.spreadsheets().batchUpdate(spreadsheetId=spreadsheet_id, body=request_body) response = request.execute() pprint(response) However I keep getting the following error, I have tried adding more scope URLs but for no avail. --------------------------------------------------------------------------- ---&gt; 41 response = request.execute() HttpError: &lt;HttpError 403 when requesting https://sheets.googleapis.com/v4/spreadsheets/xxxxxxxxxxxxxxxxxx?alt=json returned "Request had insufficient authentication scopes."&gt;
has title: google sheets API batchUpdate returning error in python
downvote count: 0
has comment: http://stackoverflow.com/comment/88892200
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88891596
tagged with: google-apis-explorer
tagged with: python
answer count: 0
score: 1

http://stackoverflow.com/comment/88878827
score: 0
type: QuestionComment
has text: I know by source code that on every page h2 with a text "See also" exists and the next sibling with tag ul exists too
type: Comment
comment on: http://stackoverflow.com/q/50940424

http://stackoverflow.com/a/68652598
has comment: http://stackoverflow.com/comment/137279968
has comment: http://stackoverflow.com/comment/137314642
downvote count: 0
score: 7
answers question: http://stackoverflow.com/q/50860448
upvote count: 7
has body: This question was answered in this GitHub link, which might help to resolve your issue. The error you encountered is TypeError: Object of type 'RepeatedCompositeContainer' is not JSON serializable Below is the solution provided in the GitHub thread The Vision library returns plain protobuf objects, which can be serialized to JSON using: from google.protobuf.json_format import MessageToJson serialized = MessageToJson(original) You can also go to dictionaries using something like protobuf3-to-dict.
has comment: http://stackoverflow.com/comment/136671581
type: Answer

http://stackoverflow.com/q/50878549
favorite count: 0
has answer: http://stackoverflow.com/a/50878667
has comment: http://stackoverflow.com/comment/88759484
tagged with: python
tagged with: regex
answer count: 4
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50878637
has answer: http://stackoverflow.com/a/50878637
downvote count: 2
accepted answer: http://stackoverflow.com/a/51192642
has title: regex to match a word and the first parenteshis i find
type: Question
has comment: http://stackoverflow.com/comment/88759223
has answer: http://stackoverflow.com/a/50878681
score: -2
has comment: http://stackoverflow.com/comment/88759187
upvote count: 0
has answer: http://stackoverflow.com/a/51192642
has body: I need a regex to match a word like 'estabilidade' and then matches anything until it gets to the first parenteshis. I already tried some regex that i found on internet, but i have difficulties to make my own regex, as i dont understand how it works very well. Someone can help me? The regex i already tried were: re.search(r"([^\(]+)", resultado) -&gt; trying to get just the parenteshis. and re.search(r"estabilidade((\s*|.*))\(+", resultado).group(1) Real Example (need to pick up all the numbers inside the parenthesis, but knowing which word this number is related to. For instance, the first 7 is related to the sentence 'Procura por estabilidade'): Procura por estabilidade (7) É assertivo(a) com os outros (5) Procura convencer os outros (7) Espontaneamente se aproxima dos outros LIDERANÇA INFLUÊ 10 9 (6) Demonstra diplomacia (5)

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

http://stackoverflow.com/q/50879424
tagged with: id3
favorite count: 0
type: UnansweredQuestion
has body: I am working on using python to add an explicit tag into my mp3s. My kids are getting older and I would like to share some music with them, but it would probably be best not to share the ones with naughty words. So I wrote up a python script to read through the lyrics, USLT tag, if available and compare to a list. All works fairly well. My question is where does the tag go? Based on ID3 standard, there does not seem to be a place for this. Most info online points to using ITunes to convert to m4a file and use the CONTENTADVISORY tag, which does not seem standard. I can use mutagen to add in a tag but I not sure where I would put it. Would it be a custom tag under the TXXX and how is the best way to add those so players like ITunes can pick that up. My hope was to use the tag in smart playlists for filtering. Thanks. Code Example: def search_files(src_path): for root, _, filenames in os.walk(src_path): for files in filenames: explicit= False if files.endswith('.mp3'): audio = ID3(os.path.join(root, files)) for key in audio: if key.startswith("USLT"): explicit = explict_check(audio[key].text) break if explicit: #audio["TXXX"] = ???XX print audio["TIT2"].text, "Explicit"
upvote count: 1
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/88762315
score: 1
tagged with: http://stackoverflow.com/tag/mp3
type: Question
has title: Python Adding Explicit Tag to MP3
downvote count: 0
tagged with: mutagen

http://stackoverflow.com/q/50879860
downvote count: 0
type: UnansweredQuestion
has body: I would like to preface this with saying that I have combed the website and the tips i saw did not help my specific situation. Essentially, All I am trying to do is rewrite one string as another. One instance requires a new line to be generated before more data is added. All of the method I have tried have not worked. Any ideas? Thanks in advance. Here is what I have right now: if (Shape[z]) == 'Spherical': SpecPlat = SpecPlat.replace('[SHAPE]',(Shape[z])) elif (Shape[z]) == 'Conical': SpecPlat = SpecPlat.replace('[SHAPE]',(Shape[z]) + (" ") + (Min_Cone[z]) + (" ") + (Max_Cone[z])) else: print("Invalid Sensor Input") out.write(SpecPlat) I am trying to go to a new line in the Conical section right after the (Shape[z]) entry. Thanks
has title: Creating a new line when using .Replace
type: Question
upvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/88761974
has answer: http://stackoverflow.com/a/50879913
tagged with: python
favorite count: 0
score: 2

http://stackoverflow.com/comment/88772904
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50885545
has text: And incorrect values don't matter? Like ('123', 'Sue', 'Brady')
score: 0

http://stackoverflow.com/q/50886817
tagged with: http://stackoverflow.com/tag/html
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/88776187
has comment: http://stackoverflow.com/comment/88775255
type: Question
has comment: http://stackoverflow.com/comment/88775934
has answer: http://stackoverflow.com/a/62134398
has comment: http://stackoverflow.com/comment/88775945
score: 0
has body: I have this chat server I normally run with ./manage.py run_chat_server. I recently deployed my app to Heroku and I can't figure out how to run the chat_server. can I get help I have tried with the console in Heroku but I just realized that it does not run the manage.py command since it tells me command not found.
has comment: http://stackoverflow.com/comment/88775314
answer count: 1
has title: chat server in heroku
type: UnansweredQuestion

http://stackoverflow.com/q/50880399
has comment: http://stackoverflow.com/comment/88763103
has title: tensorflow TypeError: unhashable type: 'numpy.ndarray'
tagged with: scope
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/50880568
tagged with: python
type: AnsweredQuestion
has body: So I was trying to make a tensorflow model with my own data but it seems like numpy array isnt a feedable type in tf.Session.run()? I checked the website and it is supposed to be feedable as shown in one of their example: x = tf.placeholder(tf.float32, shape=(1024, 1024)) y = tf.matmul(x, x) with tf.Session() as sess: print(sess.run(y)) # ERROR: will fail because x was not fed. rand_array = np.random.rand(1024, 1024) #HERE IS THE NUMPY ARRAY print(sess.run(y, feed_dict={x: rand_array})) # Will succeed. After searching a couple of time, it seems like most of the time the problem is with renaming placeholder variable during the code which mess stuff up but it isn't the case in my code, at least I don't think so. Here is the full working code and the input file data: import tensorflow as tf import numpy as np data = np.load("test_data.npz") trng_input = np.array(data['Input'], dtype=np.float64) trng_output = np.array(data['Output'], dtype=np.float64) nhl1 = 16 nhl2 = 8 n_classes = 4 x = tf.placeholder(dtype=tf.float64, shape=[len(trng_input),24]) y = tf.placeholder(dtype=tf.float64, shape=[len(trng_output),n_classes]) def NN(data): hl1 = {"weights":tf.Variable(tf.random_normal([24, nhl1], dtype=tf.float64)), "biases":tf.Variable(tf.random_normal([nhl1], dtype=tf.float64))} hl2 = {"weights":tf.Variable(tf.random_normal([nhl1, nhl2], dtype=tf.float64)), "biases":tf.Variable(tf.random_normal([nhl2], dtype=tf.float64))} output_layer = {"weights":tf.Variable(tf.random_normal([nhl2, n_classes], dtype=tf.float64)), "biases":tf.Variable(tf.random_normal([n_classes], dtype=tf.float64))} l1 = tf.add(tf.matmul(data, hl1["weights"]), hl1["biases"]) l1 = tf.nn.leaky_relu(l1, alpha=0.2) l2 = tf.add(tf.matmul(l1, hl2["weights"]), hl2["biases"]) l2 = tf.nn.leaky_relu(l2, alpha=0.2) output = tf.add(tf.matmul(l2, output_layer["weights"]), output_layer["biases"]) ## output = tf.nn.leaky_relu(l1, alpha=0.2) return output def train(x): prediction = NN(x) cost = tf.reduce_mean(tf.nn.softmax…
tagged with: tensorflow
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/50880568

http://stackoverflow.com/comment/88757908
comment on: http://stackoverflow.com/q/50867539
score: 0
has text: @martineau, this looks promising, I'll respond with my results later today.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/88717834
comment on: http://stackoverflow.com/a/50857445
type: AnswerComment
score: 0
type: Comment
has text: @gussilago But it will only work if your column names actually match (in your dataframe it is called `"Score 4"`, but in your weights it is called `"Score_4"`).

http://stackoverflow.com/a/50859241
score: 1
has comment: http://stackoverflow.com/comment/88722248
answers question: http://stackoverflow.com/q/50858659
has comment: http://stackoverflow.com/comment/88722570
upvote count: 2
has body: Use agg() to compute multiple values from a single groupby(): df.groupby(['a', 'b']).agg([ ('1': lambda x: f(x, 1)), ('2': lambda x: f(x, 2)), ('3': lambda x: f(x, 3)), ('4': lambda x: f(x, 4)), ]) Or equivalently: df.groupby(['a', 'b']).agg([(str(i), lambda x: f(x, i)) for i in range(1, 5)])
downvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/131076181
has comment: http://stackoverflow.com/comment/88722021

http://stackoverflow.com/comment/88946969
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50930281
has text: You're correct. I've been working more with pipes recently.

http://stackoverflow.com/comment/88845379
type: AnswerComment
score: 0
type: Comment
has text: Index([1, '1.1'], dtype='object') So should I replace 0 with 1 in the code?
comment on: http://stackoverflow.com/a/50922946

http://stackoverflow.com/a/51003161
type: AcceptedAnswer
downvote count: 0
upvote count: 2
type: Answer
score: 2
has body: Okay so decided to go with the requests module as suggested by @Manhattan. It's much easier and simple to send post request with json data using requests. r = requests.post(url, json={"audienceId":id,"leadCount":500}, headers=h) Here the json parameter is just a python dictionary. and headers is also a dictionary. Official documentation
answers question: http://stackoverflow.com/q/50914432
accepted answer of: http://stackoverflow.com/q/50914432
has comment: http://stackoverflow.com/comment/112609621

http://stackoverflow.com/comment/119010133
has text: it does work, you need to put in conftest.py (pytest)
comment on: http://stackoverflow.com/a/53457149
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/50886019
type: Answer
answers question: http://stackoverflow.com/q/50883054
has body: Here is the code to replicate the original plot, something like this is expected in the question, would allow more time to answer the problem (as opposed to re-creating it). import pandas as pd import matplotlib.pyplot as plt xia = pd.DataFrame([['Da Yu', -2207, -2197], ['Qi', -2197, -2188], ['Tai Kang', -2188, -2159]], columns=['EnglishName', 'Start', 'Finish']) event = xia['EnglishName'] begin = xia['Start'] end = xia['Finish'] length = xia['Finish'] - xia['Start'] plt.figure(figsize=(12,6)) plt.barh(range(len(begin)), (end-begin), .3, left=begin) plt.tick_params(axis='both', which='major', labelsize=15) plt.tick_params(axis='both', which='minor', labelsize=20) plt.title('Xia Dynasty', fontsize = '25') plt.xlabel('Year', fontsize = '20') plt.yticks(range(len(begin)), "") plt.xlim(-2250, -1750) plt.ylim(-1,18) for i in range(3): plt.text(begin.iloc[i] + length.iloc[i]/2, i+.25, event.iloc[i], ha='center', fontsize = '12') Grievances (to settle what to do next): The issue is that 1. This is difficult to read and 2. I don't know how to flatten it out so that it looks like a traditional timeline. The issue becomes more apparent when I try and work with larger segments I'd prefer if the bars were either closer together or differently colored and all on the same y-value. The designs are rather difficult to specifiy in words. If you put on a single line (eg with this plt.barh([1 for _ in begin], (end-begin)-0.5, .3, left=begin)) the text would be overlapping even more unreadable. Here is a small code to reproduce the horizontal timeline: plt.figure(figsize=(4,2)) plt.ylim(0.5, 1.5) plt.yticks(range(len(begin)), "") # 0.25 is a stub, it controls for white separator plt.barh([1 for _ in begin], (end-begin)-0.25, .3, left=begin) But where would you expect to place the names? If you want different colors, need some rule about what the colors are. A programmer would have said you need a better specification for the task.
score: 3
upvote count: 3
downvote count: 0

http://stackoverflow.com/q/50977476
tagged with: google-streetview-publish
has answer: http://stackoverflow.com/a/50989023
tagged with: pkg-resources
has title: "pkg_resources.DistributionNotFound: google-gax" when testing Google Street View Publish API
tagged with: python-2.7
score: 0
answer count: 2
tagged with: google-cloud-platform
has answer: http://stackoverflow.com/a/50986971
type: UnansweredQuestion
has body: I am testing the Google Street View Publish API so I installed the library gapic-google-maps-streetview_publish-v1 and then I tried running the Python code example to upload a photo. In the line: from google.streetview.publish.v1 import street_view_publish_service_client as client the code raises an error: pkg_resources.DistributionNotFound: google-gax According to my package list, google-gax==0.15.16 is included in the installation of gapic-google-maps-streetview_publish-v1. I have tried updating to 0.16.0 but it doesn't work either. Any hint to fix this? EDIT: pip freeze cachetools==2.1.0 certifi==2018.4.16 chardet==3.0.4 dill==0.2.8.1 enum34==1.1.6 future==0.16.0 futures==3.2.0 gapic-google-maps-streetview-publish-v1==0.1.4 google-auth==1.5.0 google-gax==0.15.16 googleapis-common-protos==1.5.3 grpcio==1.12.1 httplib2==0.11.3 idna==2.7 oauth2client==3.0.0 ply==3.8 proto-google-maps-streetview-publish-v1==0.1.4 protobuf==3.6.0 pyasn1==0.4.3 pyasn1-modules==0.2.1 pyreadline==2.1 requests==2.19.1 rsa==3.4.2 six==1.11.0 urllib3==1.23
tagged with: python
has comment: http://stackoverflow.com/comment/88971978
has comment: http://stackoverflow.com/comment/88968364
type: Question

http://stackoverflow.com/a/50971846
answers question: http://stackoverflow.com/q/50971429
score: 0
type: Answer
has body: flat_d = [v[1] for v in myD.items()] {"x":min([v["x"] for v in flat_d ]),"y":min([v["y"] for v in flat_d ])}
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/88980062
has text: can you check that your car is booked in django shell? After make booking, just check the car object is updated well
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50982757

http://stackoverflow.com/comment/88901584
has text: There's nothing wrong with the code review code you posted, `super` is the correct way of doing things there. Note that the `namedtuple('AuthorBase', 'id first_name last_name')` that `Author` inherits from is created in the `class` statement, there's no other way to reference that object except through `super`.
type: QuestionComment
comment on: http://stackoverflow.com/q/50951335
type: Comment
score: 1

http://stackoverflow.com/q/51001877
type: Question
has comment: http://stackoverflow.com/comment/102055285
upvote count: 12
tagged with: flask
score: 12
tagged with: ldap
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: flask-appbuilder
has title: How to map LDAP AD Groups to User roles in python flask AppBuilder
has answer: http://stackoverflow.com/a/69178830
has body: I'm currently trying to map automatically user groups in LDAP to user roles in a flask AppBuilder framework based application but can't come up with a solution. I have read through the entire flask AppBuilder documentation and didn't find anything related to this. Here is the basic configuration I have come up with. I don't know how I could map different roles to different user groups. AUTH_TYPE = AUTH_LDAP AUTH_LDAP_SERVER = "ldap://ldapserver.local" AUTH_LDAP_USE_TLS = False AUTH_LDAP_SEARCH = "dc=domain,dc=local" AUTH_LDAP_BIND_USER = "CN=Query User,OU=People,dc=domain,dc=local" AUTH_LDAP_BIND_PASSWORD = "password" AUTH_USER_REGISTRATION = True AUTH_USER_REGISTRATION_ROLE = "Admin"

http://stackoverflow.com/comment/88883180
type: Comment
comment on: http://stackoverflow.com/q/50935514
type: QuestionComment
has text: I've removed the Lock Table statement, but the errors are still there.
score: 0

http://stackoverflow.com/comment/90769219
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50992374
has text: Have you any progress on this?

http://stackoverflow.com/comment/89006855
score: 0
type: QuestionComment
has text: Here’s a link that may be of use: [outlier detection on skewed distributions](https://stats.stackexchange.com/questions/129274/outlier-detection-on-skewed-distributions)
type: Comment
comment on: http://stackoverflow.com/q/51006163

http://stackoverflow.com/a/50951230
downvote count: 0
has comment: http://stackoverflow.com/comment/88900272
upvote count: 11
accepted answer of: http://stackoverflow.com/q/50950784
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50950784
type: Answer
score: 11
has body: Simply add ansible_python_interpreter to the task: - name: db_config -&gt; Create MY database mysql_db: ...create some db delegate_to: "{{ ec2_instance_ip }}" vars: ansible_python_interpreter: /path/to/python

http://stackoverflow.com/q/50878529
accepted answer: http://stackoverflow.com/a/50878817
favorite count: 0
has body: Working in Python 3.6, I have a list of html files with date prefixes. I'd like to return all dates, so I join the list and use some regex, like so: import re snapshots = ['20180614_SII.html', '20180615_SII.html'] p = re.compile("(\d|^)\d*(?=_)") snapshot_dates = p.findall(' '.join(snapshots)) snapshot_dates is a list, ['2', '2'], but I'm expecting ['20180614', '20180615']. Demonstration here: https://regexr.com/3r44o. What am I missing?
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/88759325
tagged with: python-3.x
upvote count: 1
has answer: http://stackoverflow.com/a/50878817
type: AnsweredQuestion
score: 1
has title: Python re.findall returning only first character
has comment: http://stackoverflow.com/comment/88761021
type: Question
tagged with: regex-lookarounds
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/88815219
score: 1
has text: you can try http://arrow.readthedocs.io/en/latest/, but I think you may end up redisgning the result to timedelta from current date. also please post the code you tryied, it help answering the question greatly
comment on: http://stackoverflow.com/q/50906943
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88792551
score: 0
type: QuestionComment
type: Comment
has text: How would I express the upper and lower in code? Edited the question to include the error. The code is copied from the linked one.
comment on: http://stackoverflow.com/q/50895791

http://stackoverflow.com/a/78674630
answers question: http://stackoverflow.com/q/51003197
has body: You should specify dictionary where keys are column numbers starting with 0: types_dict = {0: "int32", 1: "float32", 2: "str", 3: "str"} df = pd.read_csv("data.csv", dtype=types_dict, header=None)
type: Answer
score: 0

http://stackoverflow.com/comment/88958916
type: Comment
has text: Thank you very much, it worked with the implementation of the "auth" variable inside the request! Thanks.
comment on: http://stackoverflow.com/a/50930245
type: AnswerComment
score: 0

http://stackoverflow.com/comment/88741673
has text: This is not working as I still need to run my code and it would hinder my workflow if I would need to switch back and forth. However, @abarnert pointed already to this https://superuser.com/a/1070519/196371 answer, which also works in my situation!
comment on: http://stackoverflow.com/a/50863723
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50998547
score: 0
tagged with: pandas
answer count: 1
type: UnansweredQuestion
tagged with: python
has body: I am trying to use cancer dataset from sklean and it was imported well and all the things seems good but when i try to creat a dataframe it shows error in tracebak "Shape of passed values is (30, 569), indices imply (569, 569)" from sklearn.datasets import load_breast_cancer cancer=load_breast_cancer() cancer.keys() df_feat = pd.DataFrame(cancer['data'],columns=cancer['target']) ValueError Traceback (most recent call last) C:\Users\Bilal Pharmacist\Anaconda3\lib\site- packages\pandas\core\internals.py in create_block_manager_from_blocks(blocks, axes) 4293 blocks = [make_block(values=blocks[0], 4294 placement=slice(0, len(axes[0])))] 4295 C:\Users\Bilal Pharmacist\Anaconda3\lib\site- packages\pandas\core\internals.py in make_block(values, placement, klass, ndim, dtype, fastpath) 2718 2719 return klass(values, ndim=ndim, fastpath=fastpath, placement=placement) 2720 C:\Users\Bilal Pharmacist\Anaconda3\lib\site- packages\pandas\core\internals.py in __init__(self, values, placement, ndim, fastpath) 114 'implies %d' % (len(self.values), 115 len(self.mgr_locs))) 116 ValueError: Wrong number of items passed 30, placement implies 569 During handling of the above exception, another exception occurred: ValueError Traceback (most recent call last) &lt;ipython-input-16-24a03a5e14d7&gt; in &lt;module&gt;() 1 df_feat = pd.DataFrame(cancer['data'],columns 2 =cancer['target']) C:\Users\Bilal Pharmacist\Anaconda3\lib\site-packages\pandas\core\frame.py in __init__(self, data, index, columns, dtype, copy) 304 else: 305 mgr = self._init_ndarray(data, index, columns, dtype=dtype, 306 copy=copy) 307 elif isinstance(data, (list, types.GeneratorType)): 308 if isinstance(data, types.GeneratorType): C:\Users\Bilal Pharmacist\Anaconda3\lib\site-packages\pandas\core\frame.py in _init_ndarray(self, values, index, columns, dtype, copy) 481 values = maybe_infer_to_datetimelike(values) 482 483 return create_block_manager_from_blocks([values], [columns, index]) 484 485 @property C:\Users\Bilal Pharm…
has answer: http://stackoverflow.com/a/50998719
has title: Shape of passed values is (30, 569), indices imply (569, 569)
type: Question
tagged with: numpy
tagged with: dataframe

http://stackoverflow.com/a/50927656
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50924487
answers question: http://stackoverflow.com/q/50924487
type: Answer
has comment: http://stackoverflow.com/comment/88861563
has body: Is it possible to read the the futures' task once it has been executed? In asyncio, the word task has a specialized meaning, referring to a class that subclasses Future specialized for driving coroutines. In your code, asyncio.gather() returns results, and you also have the futures variable that contains the Future objects which can also be used to access the same results. If you need to access additional information (like the original fun or arg), you can attach it to the appropriate Future or use a dict to map it. For example: futures = [] for conn in connections: fut = loop.run_in_executor(executor, fun, arg) fut.conn = conn # or other info you need await asyncio.wait(futures) # at this point all the futures are done, and you can use future.result() # to access the result of an individual future, and future.conn to obtain # the connection the future was created for
score: 2
downvote count: 0

performance
tags question: http://stackoverflow.com/q/50978507
tags question: http://stackoverflow.com/q/50861003
tags question: http://stackoverflow.com/q/50930734
tags question: http://stackoverflow.com/q/50864956
tags question: http://stackoverflow.com/q/51008636
tags question: http://stackoverflow.com/q/50880504
tags question: http://stackoverflow.com/q/50938382
tags question: http://stackoverflow.com/q/50992034
tags question: http://stackoverflow.com/q/50943043
tags question: http://stackoverflow.com/q/50964480
tags question: http://stackoverflow.com/q/50914546
tags question: http://stackoverflow.com/q/50899676
tags question: http://stackoverflow.com/q/50982372
tags question: http://stackoverflow.com/q/50890336
tags question: http://stackoverflow.com/q/50878960
tags question: http://stackoverflow.com/q/50985232
tags question: http://stackoverflow.com/q/50896965
tags question: http://stackoverflow.com/q/50861098
tag name: performance
tags question: http://stackoverflow.com/q/50913174
tags question: http://stackoverflow.com/q/50868100
type: Tag
tags question: http://stackoverflow.com/q/50970476
tags question: http://stackoverflow.com/q/50897860
tags question: http://stackoverflow.com/q/50856890

http://stackoverflow.com/comment/88872234
type: AnswerComment
has text: Updated to answer your questions
type: Comment
score: 0
comment on: http://stackoverflow.com/a/50895775

http://stackoverflow.com/comment/89018967
has text: @gohanman What I described is not official, but it is the "most logical" thing, so to say: the placeholder variants are there to help the library choose the simplest way to solve their task. And `?` and `:XYZ` are some which are used by some prepared statement libraries, `%s` is used for libraries which assemble the query on their own.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50992745
type: Comment

http://stackoverflow.com/comment/88732703
comment on: http://stackoverflow.com/q/50865018
score: 0
type: QuestionComment
has text: sorry my mistake, I will fix it
type: Comment

http://stackoverflow.com/q/50974860
has comment: http://stackoverflow.com/comment/88982541
answer count: 1
downvote count: 0
has title: Is ggplot2 for python via plotnine not supported anymore?
favorite count: 0
tagged with: plotnine
upvote count: 2
tagged with: python
tagged with: ggplot2
score: 2
type: AnsweredQuestion
type: Question
has body: Eventhough I get a proper diagram (yeay!), I also get this warning each time I run ggplot: FutureWarning: Attribute 'is_copy' is deprecated and will be removed in a future version.return object.__setattr__(self, name, value) I use Python 3.6 and: from plotnine import * #Vers. 0.3.0 import pandas as pd #Vers. 0.23.1 from pandas import DataFrame The ggplot code is: g = ggplot(df, aes(x='date', y='meanDN')) + geom_point() print(g) Should I be concerened?
tagged with: python-ggplot
has answer: http://stackoverflow.com/a/51138090
accepted answer: http://stackoverflow.com/a/51138090

http://stackoverflow.com/comment/130986828
type: Comment
score: 1
comment on: http://stackoverflow.com/a/64177543
has text: I can see your opinion, but I see it differently, I can to this question when searching how trying to represent float and arrays, which is why I am answering both the original question and also my specific use-case.
type: AnswerComment

pivot
tags question: http://stackoverflow.com/q/50959350
tag name: pivot
tags question: http://stackoverflow.com/q/50912873
tags question: http://stackoverflow.com/q/50855155
type: Tag

http://stackoverflow.com/comment/88785725
type: AnswerComment
type: Comment
has text: Side question... Let's say I wanted to give a right/left pad between the words, how can I achieve it?
comment on: http://stackoverflow.com/a/50892566
score: 0

http://stackoverflow.com/a/50915555
type: AcceptedAnswer
has body: Swap your slashes: import subprocess #import call,subprocess completed = subprocess.run(['c:/Progra~1/Inkscape/Inkscape.exe', '-z', '-f', r'N:/pdf_skunkworks/inflation-report-may-2018-page0.pdf' , '-l', r'N:/pdf_skunkworks/inflation-report-may-2018-page0.svg']) print ("stderr:" + str(completed.stderr)) print ("stdout:" + str(completed.stdout)) Python knows to swap forward slashes for back slashes on windows OS, and your back slashes are currently acting as escape prefixes.
accepted answer of: http://stackoverflow.com/q/50915483
answers question: http://stackoverflow.com/q/50915483
type: Answer
has comment: http://stackoverflow.com/comment/88831996
score: 2
downvote count: 0
upvote count: 2

http://stackoverflow.com/q/50959226
answer count: 2
has answer: http://stackoverflow.com/a/51002347
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/51002347
has title: Python: Reading Excel and automatically turning a string into a Date object?
tagged with: python
tagged with: parsing
type: AnsweredQuestion
score: 1
tagged with: openpyxl
upvote count: 1
tagged with: excel
type: Question
has comment: http://stackoverflow.com/comment/138996464
possible better answer: http://stackoverflow.com/a/50959375
has body: I'm using the openpyxl library in Python and I'm trying to read in the value of a cell. The cells value is a date in the format MM/DD/YYYY. I would like for the value to be read into my script simply as a string (i.e. "8/6/2014"), but instead Python is somehow automatically reading it as a date object (Result is "2014-08-06 00:00:00") I don't know if this is something I need to fix in Excel or Python, but how do I get the string I'm looking for?
has answer: http://stackoverflow.com/a/50959375

http://stackoverflow.com/comment/88917994
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50960520
type: AnswerComment
has text: @TanakornTaweepoka You are welcome. You can also try `print(' '.join(k))` (or `s = ' '.join(k)`) to get a string with all parts of the sentence "glues" together into a single string.

http://stackoverflow.com/a/50941889
has comment: http://stackoverflow.com/comment/88951722
accepted answer of: http://stackoverflow.com/q/50893486
answers question: http://stackoverflow.com/q/50893486
upvote count: 2
has body: You can set lists of strings, so in your python code you have to turn those lists of dicts into list of strings. Why do you use FOREACH here and not another UNWIND ? I don't see where you create the author? WITH $pubmed_dict as pubmed_article UNWIND pubmed_article as particle UNWIND particle.MedlineCitation.Article.AuthorList.Author as author MERGE (a:Author {last_name: COALESCE(author.LastName, 'LAST NAME MISSING!')}) SET a.first_name = author.ForeName, a.affiliation = author.AffiliationInfo.Affiliation MERGE (p)&lt;-[:WROTE]-(a)
type: AcceptedAnswer
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/88951768
downvote count: 0
has comment: http://stackoverflow.com/comment/88951477

http://stackoverflow.com/a/50994710
answers question: http://stackoverflow.com/q/50982701
has body: If I understand correctly, your use case is to prohibit installation from source distribution (tar.gz, tar.bz2, zip) when installing a particular package subprocess32. Do it with $ pip install subprocess32 --only-binary=subprocess32 The difference between --only-binary=pkgname and --only-binary=:all: is that in the first case, the source dists will be forbidden for pkgname only, while the latter prohibits source dists for all packages scheduled for installation, including dependencies. Multiple packages can be selected by comma-separating their names, e.g. --only-binary=spam,eggs,bacon. Permanent configuration Entering the --only-binary option every time starts to annoy pretty quickly. To apply it permanently, open pip.conf and add: # ~/.pip/pip.conf [global] only-binary=subprocess32 Now issuing pip install subprocess32 will have the same effect as the above command - the latest binary wheel available for the target platform will be selected. If no binary wheels will be eligible for installation, the command will fail. Specifying binary requirement You can also force the --only-binary option in the requirement file if you have one: # requirements.txt subprocess32 --only-binary=subprocess32 Now, when installing from the requirement file (via pip install -r requirements.txt), the latest binary wheel available for the target platform will be selected.
upvote count: 3
type: AcceptedAnswer
type: Answer
score: 3
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50982701

http://stackoverflow.com/q/50903578
has comment: http://stackoverflow.com/comment/88806835
has answer: http://stackoverflow.com/a/50903976
has comment: http://stackoverflow.com/comment/88809246
type: Question
accepted answer: http://stackoverflow.com/a/50903976
has comment: http://stackoverflow.com/comment/88806897
score: 0
tagged with: pandas
answer count: 1
has title: Apply functions in a dataset
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88807065
has body: I'm trying to apply multiple functions in a CSV document. I would like to have a first function that resends the data to other functions according to the value of your column Data (test.csv): sentence,language .,fr .,en .,en .,it .,es .,fr .,fr .,fr .,es .,ge .,fr .,fr "Prezzi",it "it's not expensive",en "prix à baisser",fr "casi 50 euros la alfombra es cara",es "Prix,fr "PREZZI più bassi",it "Preis",ge "Precio",es "Price",en "es ist nicht teuer",fr Script: import string import pandas as pd def main(dataset): dataset = pd.read_csv(dataset, sep =',') text = dataset['sentence'] language = dataset['language'] for language in dataset: if language == 'fr': cleanText_FR() if language == 'es': cleanText_ES() if language == 'it': cleanText_IT() if language == 'en': cleanText_EN() if language == 'ge': cleanText_EN() def cleanText_FR(): text_lower = text.str.lower() punct = string.punctuation pattern = r"[{}]".format(punct) text_no_punct = text_lower.str.replace(pattern, ' ') text_no_blancks = text_no_punct.replace('\s+', ' ', regex=True) text_no_blancks = text_no_blancks.str.rstrip() text_no_duplicate = text_no_blancks.drop_duplicates(keep=False) text_cluster_random = text_no_small.sample(n=1000) text_list = text_cluster_random.tolist() return text_list def cleanText_ES(): text_lower = text.str.lower() punct = string.punctuation pattern = r"[{}]".format(punct) text_no_punct = text_lower.str.replace(pattern, ' ') text_no_blancks = text_no_punct.replace('\s+', ' ', regex=True) text_no_blancks = text_no_blancks.str.rstrip() text_no_duplicate = text_no_blancks.drop_duplicates(keep=False) text_cluster_random = text_no_small.sample(n=1000) text_list = text_cluster_random.tolist() return text_list def cleanText_IT(): text_lower = text.str.lower() punct = string.punctuation pattern = r"[{}]".format(punct) text_no_punct = text_lower.str.replace(pattern, ' ') text_no_blancks = text_no_punct.replace('\s+', ' ', regex=True) text_no_blancks = text_no_blancks.str.rstrip() text_no_duplicat…
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/88790585
type: QuestionComment
has text: Also, you should put `global startGame` at the start of each function that you expect will change that value from `True` to `False`
comment on: http://stackoverflow.com/q/50895243
score: 0
type: Comment

http://stackoverflow.com/a/50864528
has body: If there are any non-data lines after the Chores heading, you can use a technique like this. # Define the patterns # HEADER_PATTERN = re.compile(...) # DATA_PATTERN = re.compile(...) def parse(line): """ Do whatever it is to the data lines you need """ ... # Scan the file until you find the header pattern for line in file: m = HEADER_PATTERN.match(line) if m: break # Collect the data lines data = [] # We can use the file again because it remembers how many lines we've # passed already. for line in file: m = DATA_PATTERN.match(line) if m: data.append(parse(line)) else: # No more data lines break
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88859101
answers question: http://stackoverflow.com/q/50863706
score: 0
has comment: http://stackoverflow.com/comment/88858335
has comment: http://stackoverflow.com/comment/88857905
has comment: http://stackoverflow.com/comment/88857832
has comment: http://stackoverflow.com/comment/88821201
type: Answer
has comment: http://stackoverflow.com/comment/88731691
has comment: http://stackoverflow.com/comment/88731845
accepted answer of: http://stackoverflow.com/q/50863706
has comment: http://stackoverflow.com/comment/88857967

http://stackoverflow.com/a/51000620
type: Answer
has body: Here is an example which does the same thing, and you will understand it better: def f(): print('Hello') print(f()) Outputs: Hello None None is at the end because you are basically doing print(print('Hello')), print writes something in the python interpreter and also when you do type(print()) it outputs: &lt;class 'NoneType'&gt; So this part is print(None). So that's why the output of print(print(print('aaa'))) includes None's
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/51000516

http://stackoverflow.com/comment/88786338
has text: Welcome yto stack overflow. Unfortunately your question doesn't comply with the general approach required of StackOverflow. You should make some attempt and show what you have tried. There must be some aspect of this that you have already tried, if so show your code. Read the tutorial on how to ask questions.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50892899

http://stackoverflow.com/a/51008822
score: 0
answers question: http://stackoverflow.com/q/51007402
has body: df=pd.DataFrame(data={"1":["a,bb,c,d"],"2":["n,g,r,h,l"]},index=['firstcolumn']).T df['secondcolumn']=df['firstcolumn'].apply(lambda s:s.split(',')[1]) df['firstcolumn'] =df['firstcolumn'].apply(lambda s:s.split(',')[0])
type: Answer

http://stackoverflow.com/comment/89006106
type: QuestionComment
has text: Question updated for clarity @abarnert. You're right, I apologise.
comment on: http://stackoverflow.com/q/51006279
score: 0
type: Comment

http://stackoverflow.com/a/50915102
score: 1
has comment: http://stackoverflow.com/comment/88835606
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50892429
has body: I think this question may be better suited over on the Code Review Stack Exchange, but as you mention that your code sometimes crashes and returns NoneType errors I'll give it the benefit of the doubt. Looking at your description, this is what stands out to me Each organisation has a name, orgcode and dictionary listing its child organisations. [API calls] will return the immediate child organisations of any other. So, what this suggests to me (and how it looks in your sample data) is that all your data is exactly equivalent; the hierarchy only exists due to the nesting of the data and is not enforced by the format of any particular node. This, consequently, means that you should be able to have a single piece of code which handles the nesting of an infinitely (or arbitrarily, if you prefer) deep tree. Obviously, you do this for the API call itself (get_child_orgs()), so just replicate that for constructing the tree. def populate_hierarchy(organization,year): """ Recursively Populate the Organization Hierarchy organization should be a dict with an "orgcode" key with a string value and "children" key with a dict value. year should be a 2-4 character string representing a year. """ orgcode = organization['orgcode'] ## get_child_orgs returns a list of organizations children = get_child_orgs(orgcode,year) ## get_child_orgs returns None on Errors if children: for child in children: ## Add child to the current organization's children, using ## orgcode as its key organization['children'][child['orgcode']] = child ## Recursively populate the child's sub-hierarchy populate_hierarchy(child,year) ## Technically, the way this is written, returning organization is ## pointless because we're modifying organization in place, but I'm ## doing it anyway to explicitly denote the end of the function return organization for country in hierarchy.values(): populate_hierarchy(country,year) It's worth noting (since you were checking for empty lists prior to iterating in your original code)…
answers question: http://stackoverflow.com/q/50892429
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/50931641
type: Question
tagged with: python
answer count: 1
has body: Is there a way to access the full range of colors that excel has using xlsxwriters workbook.add_format? I have the following cell_format1 = workbook.add_format({'bold':True,'align':'center','bg_color':'#217,217,217'}) In Excel the # 217, 217, and 217 refers to a light grey but the xlsxwriter is filling the cell in with black?
accepted answer: http://stackoverflow.com/a/50931933
tagged with: format
upvote count: 3
tagged with: xlsxwriter
downvote count: 0
has title: Full excel color list with xlsxwriter
tagged with: colors
has answer: http://stackoverflow.com/a/50931933
type: AnsweredQuestion
score: 3
favorite count: 0

http://stackoverflow.com/q/50910062
tagged with: display
tagged with: email
has comment: http://stackoverflow.com/comment/88820682
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88820582
has body: I am currently trying to write a function which will create a mail and then displayed it through Outlook. Like this the user will be able to create and see his new mail under Outlook, and just decide to click on Send or not. I struggle to find an attribute to smtplib, or an attribute to Mimemultipart like smtplib.display() or msg = MIMEMultipart('alternative') msg = email.message.Message() msg.display(True). I already succesfully create and send automatically mail with smtplib. What I can't find on the web, is this attribute to display the crated mail..... What I have: def createEmailConfirmation(): email_content = """\ Title Confirmation """ msg = MIMEMultipart('alternative') msg = email.message.Message() msg['Subject'] = 'Confirmation Mail' toaddr = ['useraddressmail@test.com'] bcc = [''] cc = [''] fromaddr = ''other_useraddressmail@test.com' toaddrs = toaddr + cc + bcc password = "password" msg.add_header('Content-Type', 'text/html') msg.set_payload(email_content) s = smtplib.SMTP('**.***.**.**') s.set_debuglevel(False) # show communication with the server msg.display I think it something really easy, that will only fit In one line but I can't find it... Best Regards,
tagged with: python
has title: Python: Create mail - display mail but not send it - smtplib + MIMEmultipart + Outlook
answer count: 0
score: 0
has comment: http://stackoverflow.com/comment/88820103
linked to: http://stackoverflow.com/q/20956424
type: Question
linked to: http://stackoverflow.com/q/23864234
tagged with: smtplib

http://stackoverflow.com/a/54383230
score: 4
upvote count: 4
downvote count: 0
answers question: http://stackoverflow.com/q/50905636
type: Answer
has body: Due to the fact that you are using a virtual environment, first of all it's required that Pylint is installed inside this virtual env. Furthermore, you need to add the following entry to your workspace settings to avoid the [pylint] E0401 error: "python.linting.pylintPath": "/path/to/your/virtualenv/bin/pylint" This overrides the user settings (global settings) and instructs VSCode to use the Pylint version within your virtual env (instead of the global one). That was probably the point you was missing ;-)

http://stackoverflow.com/q/50903916
has comment: http://stackoverflow.com/comment/88807773
accepted answer: http://stackoverflow.com/a/50909251
type: Question
has body: I have an empty dataframe indexed with three pandas timestamps: import pandas as pd ts1=pd.Timestamp('2017-06-01 00:05:00') ts2=pd.Timestamp('2017-06-01 00:15:00') ts3=pd.Timestamp('2017-06-01 00:25:00') df=pd.DataFrame(index=[ts1, ts2, ts3]) Now I want to round the timestamp indexes to their nearest 10min: df.index.round('10min') But I get some unexpected output: DatetimeIndex(['2017-06-01 00:00:00', '2017-06-01 00:20:00', '2017-06-01 00:20:00'], dtype='datetime64[ns]', freq=None) Note that the 2017-06-01 00:20:00 timestamp appears twice. Is this correct behaviour? My desired output is: DatetimeIndex(['2017-06-01 00:00:00', '2017-06-01 00:10:00', '2017-06-01 00:20:00'], dtype='datetime64[ns]', freq=None) Can I achieve this using the pandas round function? Any other suggestions for rounding pandas timestamps? I'm using pandas 0.23.1
has comment: http://stackoverflow.com/comment/88807857
has comment: http://stackoverflow.com/comment/88807920
has answer: http://stackoverflow.com/a/50904738
has comment: http://stackoverflow.com/comment/88807610
answer count: 2
tagged with: pandas
score: 2
linked to: http://stackoverflow.com/q/45021268
has title: Rounding pandas timestamps to nearest 10min
downvote count: 0
has comment: http://stackoverflow.com/comment/88807983
possible better answer: http://stackoverflow.com/a/50904738
favorite count: 0
has answer: http://stackoverflow.com/a/50909251
has comment: http://stackoverflow.com/comment/88807577
has comment: http://stackoverflow.com/comment/88808024
tagged with: python
has comment: http://stackoverflow.com/comment/88807952
type: AnsweredQuestion
upvote count: 2
has comment: http://stackoverflow.com/comment/88808212

http://stackoverflow.com/q/50951077
tagged with: f-string
has comment: http://stackoverflow.com/comment/88900309
tagged with: python-3.6
tagged with: eclipse
has title: Syntax errors with parsing f-strings in PyDev Eclipse
answer count: 1
accepted answer: http://stackoverflow.com/a/50969872
downvote count: 0
favorite count: 0
tagged with: python
type: AnsweredQuestion
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/50969872
has body: I've a python project using PyDev in Eclipse. For sample code like below, var = 'element' width = 11 print(f'{var:&gt;{width}}') the code is executed printing the desired output element with right alignment and no errors. However, PyDev parses this code raising error at &gt; character and an error message SyntaxError: Unbalanced '{'. But PyDev does support double braces in f-strings since release 6.3.1 (#PyDev-884). If I remove this &gt; character, the string is printed 'left-aligned' (which I don't want) and PyDev doesn't raise any error. This confirms PyDev does support double braces, but the error message is incorrect. On the other hand, PEP 498 for f-strings doesn't mention anything about alignment using f-strings. Is alignment part of the f-string syntax? If it is why is it not mentioned in PEP guide, and why does PyDev parser raise an error? Python: 3.6.3 PyDev: 6.3.3 Eclipse: Oxygen.2 (4.7.2) Thanks!
type: Question
tagged with: pydev

http://stackoverflow.com/q/50893347
has comment: http://stackoverflow.com/comment/88787322
has body: How change a parameter's value of url? Without regexps. Now I try this, but it's long: from urllib.parse import parse_qs, urlencode, urlsplit url = 'http://example.com/?page=1&amp;text=test#section' param, newvalue = 'page', '2' url, sharp, frag = url.partition('#') base, q, query = url.partition('?') query_dict = parse_qs(query) query_dict[param][0] = newvalue query_new = urlencode(query_dict, doseq=True) url_new = f'{base}{q}{query_new}{sharp}{frag}' Also, I tried by urlsplit: parsed = urlsplit(url) query_dict = parse_qs(parsed.query) query_dict[param][0] = newvalue query_new = urlencode(query_dict, doseq=True) parsed.query = query_new url_new = urlencode(parsed) But on urlparsed.query = query_new it rise error AttributeError: can't set attribute.
answer count: 3
has answer: http://stackoverflow.com/a/50893483
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/57007578
has comment: http://stackoverflow.com/comment/88787156
score: 11
tagged with: urllib
has title: Change a url parameter
downvote count: 0
has answer: http://stackoverflow.com/a/74617536
tagged with: url
favorite count: 0
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/88787240
upvote count: 11

http://stackoverflow.com/comment/88920993
score: 0
type: QuestionComment
type: Comment
has text: Not sure what you mean by "address". Can you give an example?
comment on: http://stackoverflow.com/q/50948003

http://stackoverflow.com/comment/88779252
comment on: http://stackoverflow.com/a/50887854
score: 0
type: AnswerComment
has text: My bad, so it is. I didn't find it the first time around. I have updated my answer. Thank you Bryan.
type: Comment

http://stackoverflow.com/comment/88790180
score: 0
type: Comment
type: QuestionComment
has text: I already read the CSV file, I want to call my function to be applicable on it
comment on: http://stackoverflow.com/q/50895070

http://stackoverflow.com/comment/88945724
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50974369
has text: There is no parameter that would prevent axis labels from overlapping.
score: 0

http://stackoverflow.com/comment/88939422
comment on: http://stackoverflow.com/a/50970560
type: Comment
has text: @CHaworth Running the Python script with `python stack.py` (as the shell script does) overrides the shebang and uses the default version of Python instead of python3. You need to run it with something like `./stack.py` Instead.
score: 0
type: AnswerComment

http://stackoverflow.com/a/50880534
has body: A bytes object is already a sequence of 8-bit integers: &gt;&gt;&gt; b = b'abc' &gt;&gt;&gt; for byte in b: print(byte) 97 98 99 If you want to convert it to a different kind of sequence, like a list, just call the constructor: &gt;&gt;&gt; lst = list(b) &gt;&gt;&gt; lst [97, 98, 99] &gt;&gt;&gt; arr = array.array('b', a) &gt;&gt;&gt; arr array('b', [97, 98, 99]) Or, if you need to do it a chunk at a time for some reason, just pass the whole chunk to extend: &gt;&gt;&gt; arr = list(b'abc') &gt;&gt;&gt; arr.extend(b'def') &gt;&gt;&gt; arr [97, 98, 99, 100, 101, 102] However, the most efficient thing to do is just leave it in a bytes: with open(filename, 'rb') as f: arr = f.read() … or, if you need it to be mutable, use bytearray:1 pagesize=4096 arr = bytearray() with open(filename, 'rb') as f: arr.extend(f.read(4096)) … or, if there's any chance you could benefit from speeding up elementwise operations over the whole array, use NumPy: with open(filename, 'rb') as f: arr = np.fromfile(f, dtype=np.uint8) Or, don't even read the file in the first place and instead mmap it, then use the mmap as your sequence of integers.2 with open(filename, 'rb') as f: arr = mmap.mmap(f, 0) For comparison, under the covers (at least in CPython): A bytes (or bytearray, or array.array('b'), or np.array(dtype=np.int8), etc.) is stored as an array of 8-bit integers. So, 1M bytes takes 1MB. A bytearray will have a bit of extra slack at the end, increasing the size by about 6%. So, 1M bytes takes 1.06MB. A general-purpose sequence like a tuple or list is stored as an array of pointers to objects wrapping the 8-bit integers. The objects don't matter (there's only going to be one copy for each of the 256 values, no matter how many references there are to each), but the pointers are 8 bytes (4 bytes in 32-bit builds). So, 1M bytes takes 8MB. A list has the same extra slack as bytearray, so it's 8.48MB. A mmap is like a bytes or array.array('b') as far as virtual memory goes, but any pages that y…
type: Answer
downvote count: 0
score: 7
accepted answer of: http://stackoverflow.com/q/50880504
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50880504
upvote count: 7

http://stackoverflow.com/a/69449441
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50988763
has body: While this was asked a long time ago, I wanted to share the fix that worked for me. The error occurred when I used the host with the protocol httplib2.ProxyInfo( proxy_type=httplib2.socks.PROXY_TYPE_HTTP, proxy_host='https://proxy.prod.com', ) Removing the protocol solved the problem: httplib2.ProxyInfo( proxy_type=httplib2.socks.PROXY_TYPE_HTTP, proxy_host='proxy.prod.com', )

http://stackoverflow.com/q/50896844
type: UnansweredQuestion
has body: The code intends to print a frequency table for a random input discrete data. Here's the code : from math import log10 from random import randint N = int(input("Enter number of observations:\n")) l = [ randint(1,100) for var in range (N) ] print(l) l.sort() print(l) k = 1 + (3.332*log10(N)) k1 = round(k) print ("Number of intervals should be = ",k1) x = N//k1 + 1 print("S.No\t\tIntervals\t\tFrequency") c = 1 #count while c &lt;= k: a = (c-1)*x b = c*x count = 0 for v in range(a,b) in l: count += 1 print(c,"\t\t","{}-{}".format(a,b),"\t\t",count) c += 1 This shows the above cited error, how to resolve this?
has title: Eradicate the error - 'bool' obj can't be iterated
type: Question
answer count: 1
score: 0
has comment: http://stackoverflow.com/comment/88793486
tagged with: python
has answer: http://stackoverflow.com/a/50897183
tagged with: list

http://stackoverflow.com/q/50974639
has comment: http://stackoverflow.com/comment/88945818
score: 0
answer count: 2
tagged with: selenium
linked to: http://stackoverflow.com/q/27112731
has answer: http://stackoverflow.com/a/50975155
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50975344
has body: I'm writing a python-selenium script to send emails automatically using mail.google.com. HTML Page : What I tried : from selenium import webdriver from time import sleep 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() #Open URL driver.get("https://mail.google.com/") #Enter username driver.find_element_by_id("identifierId").send_keys("test@gmail.com") #click next button in username page driver.find_element_by_xpath("/html/body/div[1]/div[1]/div[2]/div[2]/div/div/div[2]/div/div/div[1]/div/content/span").click() sleep(4) #Enter password password_xpath="/html/body/div[1]/div[1]/div[2]/div[2]/div/div/div[2]/div/content/form/div[1]/div/div[1]/div/div[1]/input" driver.find_element_by_xpath(password_xpath).send_keys("test") #click next button in password page driver.find_element_by_xpath("/html/body/div[1]/div[1]/div[2]/div[2]/div/div/div[2]/div/div/div[1]/div/content/span").click() sleep(2) #Compose new mail driver.get("https://mail.google.com/mail/u/0/#inbox?compose=new") sleep(6) #Type Recipient's email address #The following code is to enter the Recipient's email address in Compose Window #---------------------------------------------------------------------------- driver.find_element_by_id(":125").send_keys("abc@gmail.com") #driver.find_element_by_name("to").send_keys("abc@gmail.com") #driver.find_element_by_xpath("//*[@id=':125']").send_keys("abc@gmail.com") #driver.find_element_by_link_text("To").send_keys("abc@gmail.com") #driver.find_element_by_partial_link_text("To").send_keys("abc@gmail.com") #driver.find_element_by_link_text("Recipients").send_keys("abc@gmail.com") #driver.find_element_by_partial_link_text("Recipients").send_keys("abc@gmail.com") #driver.find_element_by_tag_name("textarea").send_keys("abc@gmail.com") #driver.find_element_by_class_name("v0").send_keys("abc@gmail.com") #driver.find_element_by_class_name("w…
has title: Python & Selenium :: Unable to locate element as the webpage is not loaded/displayed completely
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/88946093

http://stackoverflow.com/comment/89025276
type: Comment
has text: Thanks for your answer. I just could not undertand why you've user a "gamma correction" here, since almost the same result can be obtained without raising the pixels values to any power.
comment on: http://stackoverflow.com/a/50918535
type: AnswerComment
score: 0

http://stackoverflow.com/q/50882680
answer count: 1
has title: Python list elements in
tagged with: flask
favorite count: 0
has comment: http://stackoverflow.com/comment/88767924
duplicate of: http://stackoverflow.com/q/3389574
has comment: http://stackoverflow.com/comment/88767662
tagged with: python
has comment: http://stackoverflow.com/comment/88767715
has body: I have a Flask controller action with the following input validation routine, is there a way to write it more succinctly? if 'firstName' and \ 'lastName' and \ 'age' \ not in request.json: return flask.abort(400) Perhaps something like this, although I'm not sure how to get the and operators to work: mandatory_fields = ['firstName', 'lastName', 'age'] if mandatory_fields not in request.json: return flask.abort(400) Is the second code snippet possible?
has answer: http://stackoverflow.com/a/50882728
has comment: http://stackoverflow.com/comment/88767637
upvote count: 1
downvote count: 1
type: Question
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/50882728

http://stackoverflow.com/q/50871526
tagged with: django
tagged with: python
score: 2
answer count: 0
downvote count: 0
tagged with: django-orm
has title: Doing a MySQL REPLACE INTO in Django?
tagged with: mysql
has comment: http://stackoverflow.com/comment/88745038
type: Question
has comment: http://stackoverflow.com/comment/88744916
has body: Suppose i have more than 180k user object, and some of them are already present in table, and the table has email Id unique index, So i want to update the existing records and insert the new records, In MySQl i came to know that there is option called REPLACE INTO, Is there any way to run the REPLACE INTO in django ORM object, and also i want run the query as bulk like below Entry.objects.**bulk_replace**([ ... Entry(headline='This is a test'), ... Entry(headline='This is only a test'), ... ])
tagged with: django-models
has comment: http://stackoverflow.com/comment/88746043
upvote count: 2
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/88832731
has text: The first part would be to read the file in to some data structure. Have you made an attempt to read your files? What specific issues are you facing?
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50916364
type: QuestionComment

http://stackoverflow.com/q/50991487
has title: how to populate django model with a foreign key from a csv
type: Question
has comment: http://stackoverflow.com/comment/88977620
tagged with: django-models
answer count: 1
has body: my model.py: # Riders models ---------------------------------------- class CategoryTeam(models.Model): name = models.CharField(max_length = 256) def __str__(self): return self.name class Teams(models.Model): name = models.CharField(max_length = 256) code = models.CharField(max_length = 10) nation = models.CharField(max_length = 10) continent = models.CharField(max_length = 10) category = models.ForeignKey(CategoryTeam, on_delete=models.CASCADE,) def __str__(self): return self.name #-----------------------------------------------------# my script to populate from basic_app.models import CategoryTeam,Teams def populateCat(): f = open('CategoryCSV.csv') reader = csv.reader(f) next(reader) for row in reader: # Create new User Entry category = CategoryTeam.objects.get_or_create(name=row[0])[0] def populateTeamat(): f = open('FantaDS Project - Teams.csv') reader = csv.reader(f) next(reader) for row in reader: # Create new User Entry team = Teams.objects.get_or_create( name = row[0], code = row[1], nation = row[2], continent = row[3], category = row[4] )[0] if __name__ == '__main__': print("Populating the databases Cat...Please Wait") populateCat() print('Populating Complete') print("Populating the databases Team...Please Wait") populateTeamat() print('Populating Complete') the exeption generated: File "C:\Users\Wynt\AppData\Local\conda\conda\envs\DjangoEnv\lib\site-packages\django\db\backends\utils.py",line 85, in _execute return self.cursor.execute(sql, params) File "C:\Users\Wynt\AppData\Local\conda\conda\envs\DjangoEnv\lib\site-packages\django\db\utils.py", line 89, in __exit__raise ndj_exc_value.with_traceback(traceback) from exc_value File "C:\Users\Wynt\AppData\Local\conda\conda\envs\DjangoEnv\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "C:\Users\Wynt\AppData\Local\conda\conda\envs\DjangoEnv\lib\site-packages\django\db\backends\sqlite3\base.py",line 303, in execute return Database.Cursor.execute(…
has answer: http://stackoverflow.com/a/50992192
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/88978271
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50992192
score: 0

http://stackoverflow.com/q/50865860
has title: get total by groups for all rows, selected rows and percent of total pandas
answer count: 2
tagged with: pandas
downvote count: 0
accepted answer: http://stackoverflow.com/a/50866243
favorite count: 0
possible better answer: http://stackoverflow.com/a/50866072
tagged with: python
has answer: http://stackoverflow.com/a/50866072
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
has body: let us say I have a pandas dataframe called mydf. I.e., import pandas as pd mydf = pd.DataFrame({ 'type':['A','A','A', 'B','B','B', 'C'], 'state':['NY','CA','NY', 'NY','CA','CA', 'WY'], 'date':['2018-01-02','2018-01-04','2018-02-06', '2018-01-01','2018-01-24','2018-02-10','2018-01-24'] }) Out[28]: date state type 0 2018-01-02 NY A 1 2018-01-04 CA A 2 2018-02-06 NY A 3 2018-01-01 NY B 4 2018-01-24 CA B 5 2018-02-10 CA B 6 2018-01-24 WY C I'd want a table that count total number of records per state and date (year-month only not per daily date) for all records of type A, for all records (type A,B,C) and then the percentage of A within each group to the total. I.e., the final output would be another pandas dataframe with following columns and values: date_ym state total_count total_type_A percentage 20181 CA 2 1 50 20181 NY 2 1 50 20181 WY 1 0 0 20182 CA 1 0 0 20182 NY 1 1 50 I could create two tables, then merge them and then count but I was looking for a simpler one-liner code...
has answer: http://stackoverflow.com/a/50866243

http://stackoverflow.com/q/50878337
tagged with: docker
score: 0
tagged with: python
has answer: http://stackoverflow.com/a/50878538
type: Question
has body: I have a mysql database running in a docker container which in itself runs on an ubuntu server. My wish is now to be able to, from an external computer on the same network, access the mysql database. As far as I've understood docker is running its own environment within the ubuntu server. Within this docker environment the MySQL database is running. So accessing the MySQL database from the localhost (the server) with mysql goes fine. I'm now trying to access the MySQL from the external computer with MySQL, Toad(https://www.quest.com/toad/) and python. And I get the following errors. From MySQL: ERROR 2005 (HY000): Unknown MySQL server host '130.235.168.214;' (0) From Toad: Attempted to read past the end of the stream. From Python: Traceback (most recent call last): File "", line 1, in File "C:\Anaconda\lib\site-packages\MySQLdb__init__.py", line 86, in Connect return Connection(*args, **kwargs) File "C:\Anaconda\lib\site-packages\MySQLdb\connections.py", line 204, in in it super(Connection, self).init(*args, **kwargs2) _mysql_exceptions.OperationalError: (2013, "Lost connection to MySQL server at ' reading initial communication packet', system error: 0") So I'm now wondering if I need to forward MySQLs "standard port" 3306 to a port which I then can use to access the MySQL inside docker inside the server? How do I go from here? Thanks a lot!
type: AnsweredQuestion
has title: Accessing a MySQL running on docker running on ubuntu server
accepted answer: http://stackoverflow.com/a/50878538
tagged with: mysql
answer count: 1

http://stackoverflow.com/comment/88839022
comment on: http://stackoverflow.com/a/50919417
type: AnswerComment
type: Comment
score: 1
has text: Super awesome! Thank you!

http://stackoverflow.com/q/50989813
tagged with: python-2.7
linked to: http://stackoverflow.com/q/30669474
answer count: 3
has comment: http://stackoverflow.com/comment/89164343
has answer: http://stackoverflow.com/a/51115893
favorite count: 0
linked to: http://stackoverflow.com/q/67631
score: 6
tagged with: python
accepted answer: http://stackoverflow.com/a/51031880
upvote count: 7
has comment: http://stackoverflow.com/comment/101369945
possible better answer: http://stackoverflow.com/a/51052048
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51052048
has comment: http://stackoverflow.com/comment/88974402
linked to: http://stackoverflow.com/q/17211078
downvote count: 1
type: Question
linked to: http://stackoverflow.com/q/4383571
has comment: http://stackoverflow.com/comment/89036832
has title: Import binary package from different directory
has answer: http://stackoverflow.com/a/51031880
has body: I have the following directory structure: root /src file1.py file2.py /libs __init__.py package.so I wish to import package.so within file1.py. I've tried the following import statements to no avail: from .libs.package import func from libs.package import func from .libs import package from libs import package I want to avoid having to set PYTHONPATH / sys.path. Is there a simple way to do this? I assume the issue is due to the package being a shared object and not just a Python file - I don't have access to the source code for it. Thanks, Adam

http://stackoverflow.com/comment/88782263
type: Comment
has text: You can follow the [program execution on Python tutor](http://pythontutor.com/visualize.html#mode=edit). Maybe this will convince you that you should restructure your input routine. Hint: You call getchoice() more than necessary.
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/50890381

http://stackoverflow.com/comment/88800132
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50899986
has text: don't remove it. I didn't see the "clean" stuff. But your answer would be better if it explained _why_ the typo doesn't trigger an error.
type: AnswerComment

http://stackoverflow.com/comment/89148937
type: Comment
has text: the JSON data you passed to the view
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50924550

http://stackoverflow.com/q/50935019
type: Question
linked to: http://stackoverflow.com/q/2829329
tagged with: testing
has comment: http://stackoverflow.com/comment/127298734
answer count: 2
upvote count: 7
favorite count: 0
possible better answer: http://stackoverflow.com/a/61868725
has title: PyTest test-suite passing when asserts should fail when testing another thread's results in Python?
tagged with: python-multithreading
linked to: http://stackoverflow.com/q/43791360
tagged with: python
has body: I'm currently using pytest to test an existing (unittest test-suite per the documentation). I'm currently writing a thread that waits for an IP address to be assigned and then returns it to a callback function, and I'm writing unittests to accompany it. Here's the Test Case class I wrote. class TestGetIpAddressOnNewThread(unittest.TestCase): def test_get_existing_ip(self): def func(ip): assert ip == "192.168.0.1" # Not the real IP # Even when I introduce an assert statement that should fail, test still passes assert ip == "shouldn't be the ip" ip_check = GetInstanceIpThread(instance, func) ip_check.start() ip_check.join() if __name__ == '__main__': pytest.main() And here's the GetInstanceIpThread pseudo-definition: class GetInstanceIpThread(threading.Thread): def __init__(self, instance, callback): threading.Thread.__init__(self) self.event = threading.Event() self.instance = instance self.callback = callback def run(self): self.instance.wait_until_running() ip = self.instance.ip_address self.callback(ip) When I run this test case using pytest path_to_file.py::TestGetIpAddressOnNewThread, it passes (yay!) but even when I introduce assert statements that should 100% fail (boo!). What's going wrong, how do I write tests that actually fail?
linked to: http://stackoverflow.com/q/14405063
has answer: http://stackoverflow.com/a/61868725
type: AnsweredQuestion
downvote count: 0
tagged with: pytest
has answer: http://stackoverflow.com/a/50935020
score: 7
accepted answer: http://stackoverflow.com/a/50935020
tagged with: multithreading

http://stackoverflow.com/q/50951651
tagged with: tfrecord
has comment: http://stackoverflow.com/comment/88908791
type: UnansweredQuestion
tagged with: python
has title: TF.RECORDS IMAGES TENSORFLOW
tagged with: conv-neural-network
has comment: http://stackoverflow.com/comment/88913152
answer count: 0
tagged with: tensorflow
type: Question
tagged with: decode
has comment: http://stackoverflow.com/comment/88913187
has body: I'm doing a Tensorflow CNN. At the time of reading my tf.records I do not know what type of data is appropriate when I decode my images. I saw in multiple tutorials that a reshape should be done before entering the model. I'd like to know if I'm doing it the right way. This is my code: def read_file(filename_queue): #Funcion para leer el archivo tf.record, y retornamos el next recrod reader=tf.TFRecordReader() _,serialized_example=reader.read(filename_queue) #Se decodifica el tf.record retornando un diccionario feature={'train/image':tf.FixedLenFeature([],tf.string), 'train/label':tf.FixedLenFeature([],tf.int64)} features=tf.parse_single_example(serialized_example,features=feature) #Convertimos el string a numeros de los decodificados features image=tf.decode_raw(features['train/image'],tf.float32)* (1 / 255.0) #Convertimos a datos label=tf.cast(features['train/label'],dtype=tf.int32) #Reshape data image=tf.reshape(image,[224,224,3]) return image,label
score: 0

http://stackoverflow.com/comment/88974022
has text: @HunBurry on closer look, I found myList grew when each player played but the initial output is not retained. Output of the code looks like:[[0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0]] Player 2 chose cup 7 [[0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]] Player 1 chose cup 2 [[0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]]...
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50977879

http://stackoverflow.com/comment/89000699
comment on: http://stackoverflow.com/a/51000404
type: Comment
has text: Both answers for fine :D. Since you are all about answering I have posted another question in the original post. It's 'creating archieves' related. Please check if you want and have time. :D thanks to everyone
type: AnswerComment
score: 0

http://stackoverflow.com/comment/89047469
comment on: http://stackoverflow.com/q/50885739
has text: Your suggestion of using Python to poll the API and using (for example) the Cloud Storage client libraries to get the JSON to a bucket seems reasonable. From there you could use either a pubsub notification and a cloud function or, as you've said, Dataflow (Apache Beam) to process the data. Do you have any specific doubts about doing it in one of those ways?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/50924526
has body: Using list comprehension: import pandas as pd num_cols = 3 clean_data = [] data = [["Near Wagheshwar Temple", "Wagholi", "Pune", "Maharashtra", None, None], ["Magarpatta", "Pune", "Magarpatta", "Pune", "Maharashtra", None], ["Manikbaug Sinhgad Road Pune", "Sinhgad Road", "Pune", "Maharashtra", None, None], ["Kothrud", "Pune", "Maharashtra", None, None, None], ["Pimple Nilakh", "Pune", "Maharashtra", None, None, None], ["Opposite To D Mart And Next To Cybage It", "Kalyani Nagar", "Pune", "Maharashtra", None, None], ["Pune", "Pimple Nilakh", "Pune", "Maharashtra", None, None], ["Flat No15 ", "2nd Floor", "Near Jakat Naka,Pune", "Bekrai Nagar", "Pune", "Maharashtra"], ["Wagholi", "Pune", "Maharashtra", None, None, None], ["Wakad Near Euro School", "Shankar Kalat Nagar", "Pune", "Maharashtra", None, None]] for row in data: y = [a for a in row if a is not None] clean_data.append(y[-num_cols:]) labels = ["Locality", "City", "State"] df = pd.DataFrame.from_records(clean_data, columns=labels) print(df) Locality City State 0 Wagholi Pune Maharashtra 1 Magarpatta Pune Maharashtra 2 Sinhgad Road Pune Maharashtra 3 Kothrud Pune Maharashtra 4 Pimple Nilakh Pune Maharashtra 5 Kalyani Nagar Pune Maharashtra 6 Pimple Nilakh Pune Maharashtra 7 Bekrai Nagar Pune Maharashtra 8 Wagholi Pune Maharashtra 9 Shankar Kalat Nagar Pune Maharashtra
has comment: http://stackoverflow.com/comment/88852104
type: Answer
has comment: http://stackoverflow.com/comment/88852346
has comment: http://stackoverflow.com/comment/88851772
answers question: http://stackoverflow.com/q/50922326
has comment: http://stackoverflow.com/comment/88851583
score: 0
has comment: http://stackoverflow.com/comment/88850096

strftime
type: Tag
tags question: http://stackoverflow.com/q/50929237
tags question: http://stackoverflow.com/q/50994144
tag name: strftime
tags question: http://stackoverflow.com/q/50953736

http://stackoverflow.com/a/50990330
type: Answer
answers question: http://stackoverflow.com/q/50990122
upvote count: 1
has body: Hey you can do that using pandas aggregate sum like df.groupby(['user_id'])"points".sum() df.groupby(['user_id'])"list_of_attribute".sum() And its also possible to pass multiple columns in list_of_attributes but that would have to subset of columns otherwise KeyError.
score: 1
downvote count: 0

http://stackoverflow.com/comment/88737049
score: 1
comment on: http://stackoverflow.com/q/50866805
has text: Rather than putting the plot into a try except, make sure to only call a plot with valid data.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88950287
score: 0
comment on: http://stackoverflow.com/q/50977078
type: Comment
type: QuestionComment
has text: are you using python2.7 or you are using python 3?

http://stackoverflow.com/q/50908267
has comment: http://stackoverflow.com/comment/88830134
has comment: http://stackoverflow.com/comment/90187864
has answer: http://stackoverflow.com/a/50959413
downvote count: 0
has comment: http://stackoverflow.com/comment/88891026
answer count: 1
has comment: http://stackoverflow.com/comment/88864571
has comment: http://stackoverflow.com/comment/88830307
has comment: http://stackoverflow.com/comment/88864518
score: 8
tagged with: bipartite
favorite count: 0
upvote count: 8
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88829487
has title: Solving a Maximum weight bipartite b-matching
tagged with: pulp
tagged with: python
linked to: http://stackoverflow.com/q/37144423
has body: My question is regarding the Maximum Weight B-Matching problem. Bipartite matching problems pair two sets of vertices in a bipartite graph. A maximum weighted bipartite matching (MWM) is defined as a matching where the sum of the values of the edges in the matching have a maximal value. A famous polynomial time algorithm for MWM is the Hungarian algorithm. What I am interested in is a specific maximum weighted bipartite matching known as weight bipartite B-matching problem. A weight bipartite B-matching problem (WBM) seeks to match vertices so that each vertex is matched with no more vertices than its capacity b allows. This figure (from Chen et al.) shows the WBM problem. The input graph has score 2.2, the sum of all its edge weights. The blue edges of the solution H yield the highest score, 1.6, of all sub-graphs satisfying the red degree constraints. Although there are a few recent works addressing the WBM problem (this and this), I cannot find any implementation of the algorithm. Does anybody know if the WBM problem already exists in any library like networkX?
has comment: http://stackoverflow.com/comment/88829587
has comment: http://stackoverflow.com/comment/88890047
tagged with: networkx
type: Question
tagged with: graph

http://stackoverflow.com/q/50990123
upvote count: 3
tagged with: http://stackoverflow.com/tag/json
type: Question
score: 3
has body: I have a huge CSV file (3.5GB and getting bigger everyday) which has normal values and one column called 'Metadata' with nested JSON values. My script is as below and the intention is simply to convert the JSON column into normal columns for each of its key-value pairs. I am using Python3 (Anaconda; Windows). import pandas as pd import numpy as np import csv import datetime as dt from pandas.io.json import json_normalize for df in pd.read_csv("source.csv", engine='c', dayfirst=True, encoding='utf-8', header=0, nrows=10, chunksize=2, converters={'Metadata':json.loads}): ## parsing code comes here with open("output.csv", 'a', encoding='utf-8') as ofile: df.to_csv(ofile, index=False, encoding='utf-8') And the column has JSON in the following format: { "content_id":"xxxx", "parental":"F", "my_custom_data":{ "GroupId":"NA", "group":null, "userGuid":"xxxxxxxxxxxxxx", "deviceGuid":"xxxxxxxxxxxxx", "connType":"WIFI", "channelName":"VOD", "assetId":"xxxxxxxxxxxxx", "GroupName":"NA", "playType":"VOD", "appVersion":"2.1.0", "userEnvironmentContext":"", "vodEncode":"H.264", "language":"English" } } The desired output is to have all the above key-value pairs as columns. The dataframe will have other non-JSON columns to which I need to add the columns parsed from the above JSON. I tried json_normalize but I am not sure how to apply json_normalize to a Series object and then convert it (or explode it) into multiple columns.
tagged with: pandas
has answer: http://stackoverflow.com/a/50990220
answer count: 1
downvote count: 0
has title: Using Pandas to parse a JSON column w/nested values in a huge CSV
favorite count: 0
tagged with: python-3.x
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50990220

http://stackoverflow.com/comment/88910405
has text: no I didn't think that; I exhausted all the python2/python3 combinations; i.e. pip3 (lists both boto3/botocore as installed) should run python3 and therefore tried the task with python3; pip (lists both boto3/botocore as installed) should run python2 and therefore tried the task with python(2); there is no other python executable on the system left to try and run the task with **either way**;
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50953465

http://stackoverflow.com/a/51007211
has comment: http://stackoverflow.com/comment/89007644
answers question: http://stackoverflow.com/q/51007155
type: Answer
has body: By calling b.start(), you let the program go into the infinite loop of listening Ctrl+S event. The event of key combination, once obtained in the background thread, will not be released back into the event queue. and the foreground function won't be able to capture and process it. If you want your program to be able to process different key combination. You should let one function to listen to key press event, and dispatch the event to different processing functions.
score: 0

http://stackoverflow.com/comment/88767100
comment on: http://stackoverflow.com/a/50882310
type: Comment
has text: Technically, it isn't arbitrary. It's written somewhere. It may be as simple as timedelta having a safe casting priority over string /shrug
score: 0
type: AnswerComment

http://stackoverflow.com/a/50911002
type: Answer
has body: Sounds like you are talking about recursion: https://www.programiz.com/python-programming/recursion Basically you just do another call to the same method, inside of that method: def calc_factorial(x): """This is a recursive function to find the factorial of an integer""" if x == 1: return 1 else: return x * calc_factorial(x - 1) num = 4 print("The factorial of {} is {}".format(num, calc_factorial(num)))
downvote count: 1
has comment: http://stackoverflow.com/comment/88822951
score: -1
answers question: http://stackoverflow.com/q/50910900
upvote count: 0

http://stackoverflow.com/a/50892203
answers question: http://stackoverflow.com/q/50891399
downvote count: 0
type: Answer
upvote count: 3
score: 3
has body: The following code makes use of matplotlib's plot markers and ticks customization: import matplotlib.pyplot as plt import numpy as np x_ticks = ("Thing 1", "Thing 2", "Other thing", "Yet another thing") x_1 = np.arange(1, 5) x_2 = x_1 + 0.1 y_1 = np.random.choice(np.arange(1, 7, 0.1), 4) y_2 = np.random.choice(np.arange(1, 7, 0.1), 4) err_1 = np.random.choice(np.arange(0.5, 3, 0.1), 4) err_2 = np.random.choice(np.arange(0.5, 3, 0.1), 4) plt.errorbar(x=x_1, y=y_1, yerr=err_1, color="black", capsize=3, linestyle="None", marker="s", markersize=7, mfc="black", mec="black") plt.errorbar(x=x_2, y=y_2, yerr=err_2, color="gray", capsize=3, linestyle="None", marker="s", markersize=7, mfc="gray", mec="gray") plt.xticks(x_1, x_ticks, rotation=90) plt.tight_layout() plt.show() The output image will look something like this:

http://stackoverflow.com/comment/88875251
type: AnswerComment
has text: I've tried this, but I get an error message: AttributeError: 'DataFrame' object has no attribute 'A'. Any idea why?
score: 0
comment on: http://stackoverflow.com/a/50938087
type: Comment

http://stackoverflow.com/comment/88753782
has text: Example update. I had %f in there which was not recognised. and %Z gives a textual zone description not the numeric offset.
score: 0
comment on: http://stackoverflow.com/q/50873446
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88894371
score: 1
has text: check: https://github.com/hay/xml2json
comment on: http://stackoverflow.com/q/50948320
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50980675
has title: How to merge data efficiently in pandas?
type: Question
has body: I want to copy some data from dfb to dfa to replace some rows in dfa. Below is the code. The code has no problems except using a for loop, which is slow. Any other faster and more efficient methods? Thank you. import pandas as pd dfa = pd.read_csv('data1.csv') dfb = pd.read_csv('data2.csv') id = dfa.loc[(dfa['sex'] == 'M') &amp; (dfa['info'] == 'None'), 'id'] id_copy = dfb.loc[(dfb['id'].isin(id))&amp;(dfb['info']!='None'), 'id'] for i in id_copy.values: dfa.loc[dfa['id']==i, 'info'] = dfb.loc[dfb['id']==i, 'info']
score: 0
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/88956868
has answer: http://stackoverflow.com/a/50980718
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/88859676
score: 0
type: Comment
has text: let m e try by removing it.
type: AnswerComment
comment on: http://stackoverflow.com/a/50930250

http://stackoverflow.com/q/50938207
tagged with: python
type: AnsweredQuestion
has body: I'm trying to make a game and I want to update the rungame() only after the mouseClickHandler was used. and this is what I did in runGame(): def runGame(): global i,update,scoreDraw,questionA setInitialValues() drawObjects() if update == True: questionAsk() canvas.update() i += 1 updateObjects() checkForCollisions() canvas.delete(scoreDraw,questionA) canvas.update() and this is what runGame() does: def setInitialValues(): global score, time, update, worldGIF score = 0 time = 0 update = True worldGIF = PhotoImage(file = "WorldMap.gif") def drawObjects(): global worldMap,scoreStart,questionAA worldMap = canvas.create_image(650, 400, image = worldGIF) scoreStart = canvas.create_text(500,600,text=score, font= 'Times 24', anchor = W, fill = "white") questionAA = canvas.create_text(400,700, text="Hello!", font= "Times 20", anchor = W,fill = "white") canvas.update() def questionAsk(): global x_coord, y_coord, country, question, i global question question = "Where is", country[i],"?" def updateObjects(): global scoreDraw, questionA roundScore = round(score) scoreDraw = canvas.create_text(500,600,text=roundScore, font= 'Times 24', anchor = W, fill = "white") questionA = canvas.create_text(400,700, text=question, font= "Times 20", anchor = W,fill = "white") canvas.update() def mouseClickHandler( event ): global i, xMouse,yMouse,answerx,answery,score,distance,update canvas.delete(scoreStart,questionAA) xMouse = event.x yMouse = event.y answerx = x_coord[i] answery = y_coord[i] delta_x = abs(xMouse - answerx) delta_y = abs(yMouse - answery) distance = sqrt((delta_x)**2+(delta_y)**2) score = score + distance update = True But it never updates, for some reason, it just doesn't detect the update = True statement in the mouseClickHandler. Extras: x_coord, y_coord, country are all numpy arrays which I have made earlier and imported into here. worldGIF is just a picture of a map. So tldr; I can't find a way to trigger the if update == True part in runGame() only where there is a Clic…
has title: How can I update my tkinter game only when there is a click event?
has answer: http://stackoverflow.com/a/50938520
type: Question
tagged with: mouseevent
score: 0
has comment: http://stackoverflow.com/comment/88874990
has comment: http://stackoverflow.com/comment/88875480
answer count: 1
tagged with: events
tagged with: python-3.x
tagged with: tkinter
accepted answer: http://stackoverflow.com/a/50938520
has comment: http://stackoverflow.com/comment/88874981

http://stackoverflow.com/q/50919412
downvote count: 0
type: UnansweredQuestion
tagged with: couchdb
has comment: http://stackoverflow.com/comment/88851507
tagged with: linux-kernel
has comment: http://stackoverflow.com/comment/88838875
type: Question
favorite count: 0
has body: I took a function for python that I have found online def sh_escape(s): return s.replace("(","\\(").replace(")","\\)").replace(" ","\\ ") And I used it with os.system (). It looks like this: os.system(sh_escape('curl -X PUT http://admin:admin@127.0.0.1:5984/test/')+file+sh_escape(' -d @/home/user/Downloads/') +file) file is the name he reads with os.walk() When I run it, I am becoming sh: 1: curl -X PUT http://admin:admin@127.0.0.1:5984/test/file -d @/home/user/Downloads/file: not found Do you know, where my mistake is ? if I run the command directly in the terminal it works. Python 3 used
upvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/88838879
answer count: 1
has comment: http://stackoverflow.com/comment/88838735
linked to: http://stackoverflow.com/q/4813238
has title: how to fix sh: 1 curl not found
has answer: http://stackoverflow.com/a/50919538
score: 2

http://stackoverflow.com/comment/88876409
comment on: http://stackoverflow.com/q/50939078
score: 1
has text: It would be helpful if you gave us more here. How about a small sample dataset from 'before' and then a small sample of the desired 'after' dataset.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88947444
score: 0
type: Comment
type: QuestionComment
has text: Oh I see your problem now. Sorry. I believe you can just write the text without a background. Let me look into it. Look into `create_text` for canvas.
comment on: http://stackoverflow.com/q/50973137

http://stackoverflow.com/q/50906943
tagged with: datetime
tagged with: python
has comment: http://stackoverflow.com/comment/88815219
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50910132
type: Question
has title: How to specify base date in dateparser library python?
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/50910132
tagged with: date-parsing
has body: I was using dateparser to parse date in various patterns. 1) Apr 22, 2011 2) 8. März 2018 3) 5 hours ago It was working very fine, but the issue came when I ran the same script on the same data on other day because in the pattern like this '5 hours ago', it takes today's date as the base date. So I even went through the source code of dateparser, checked the docs but didn't found any substantial thing to go forward. Can someone suggest how can we specify the base date in dateparser? Also please suggest me if there any other library better then dateparse to tackle this problem. Code :- res['snippet'] = '''Apr 22, 2011 ... Ingen Technologies Inc.'s (OTC:IGNT) former CEO''' date = res['snippet'].split('...')[0].strip() try: datee = dateparser.parse(date) if not datee &gt; datetime.datetime.now(): dataDict['date'] = datee.strftime('%d/%m/%Y') else: continue except: continue

http://stackoverflow.com/q/50951606
has body: I'm trying to create a blog where one category may have some subcategory. I did this in my models.py class Category(models.Model): title = models.CharField(max_length=50, unique=True) def __str__(self): return f"{self.title}" class SubCategory(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) title = models.CharField(max_length=50, unique=True) def __str__(self): return f"{self.title}" But I think It's not right to create two different class for the same task. So is there any other way to do it? Thank you.
has answer: http://stackoverflow.com/a/50951719
duplicate of: http://stackoverflow.com/q/48262544
downvote count: 0
has title: How to add sub category in models.py django
has answer: http://stackoverflow.com/a/50951829
tagged with: python
favorite count: 0
type: UnansweredQuestion
tagged with: django
upvote count: 1
type: Question
score: 1
linked to: http://stackoverflow.com/q/48262544
answer count: 2

http://stackoverflow.com/a/50886997
downvote count: 0
score: 1
has body: The following error TabError: inconsistent use of tabs and spaces in indentation just means that the indentations are not correct. so, use a text editor and check if the indentations are correct. Coming to previous, current = current, [i]+[0]*n which is in the following for loop in the code given for i in range(1,m+1): previous, current = current, [i]+[0]*n so, i is the index(or a counter variable) and what he is doing is making a list which will have first element as index and n number of zeros followed. here n is the length of the first string which is evaluated in the following code n, m = len(a), len(b) so, for example if n = 10 and i = 1, then [i] + [0]*n will be [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] So, he is just trying to make a list as shown above
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50886949
answers question: http://stackoverflow.com/q/50886949
type: Answer

logging
tags question: http://stackoverflow.com/q/50923061
tag name: logging
tags question: http://stackoverflow.com/q/50995965
tags question: http://stackoverflow.com/q/50947000
tags question: http://stackoverflow.com/q/50955451
tags question: http://stackoverflow.com/q/50864135
tags question: http://stackoverflow.com/q/50906439
tags question: http://stackoverflow.com/q/50993174
tags question: http://stackoverflow.com/q/50906254
tags question: http://stackoverflow.com/q/50981906
tags question: http://stackoverflow.com/q/50927618
tags question: http://stackoverflow.com/q/50935904
tags question: http://stackoverflow.com/q/50886506
tags question: http://stackoverflow.com/q/50872479
tags question: http://stackoverflow.com/q/50865985
tags question: http://stackoverflow.com/q/50999364
tags question: http://stackoverflow.com/q/50865739
tags question: http://stackoverflow.com/q/50978756
tags question: http://stackoverflow.com/q/50867953
tags question: http://stackoverflow.com/q/50859599
tags question: http://stackoverflow.com/q/50869663
tags question: http://stackoverflow.com/q/50950266
tags question: http://stackoverflow.com/q/50976330
tags question: http://stackoverflow.com/q/50909824
tags question: http://stackoverflow.com/q/50877387
type: Tag
tags question: http://stackoverflow.com/q/50948223

http://stackoverflow.com/q/50930792
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/50935922
tagged with: python
score: 2
type: AnsweredQuestion
upvote count: 2
type: Question
has body: I have a PyQt window that calls multiple executables as QProcess. How can I list the outputs of each process after the last one has finished? (something like process_result = ["result1", "result2",..]) Let us say it looks like this: for i in list_of_processes: process = QtCore.QProcess() process.start(i) I can read with process.readyReadStandardOutput() somehow but it is quite chaotic because processes run parallel. process.waitForFinished() does not work because the GUI will freeze. Also, I checked following page about multithreading: Multithreading PyQt applications with QThreadPool. Another question is similar but did not help me either: Pyside: Multiple QProcess output to TextEdit.
has answer: http://stackoverflow.com/a/50935922
tagged with: pyqt4
linked to: http://stackoverflow.com/q/27314571
has title: PyQt: Multiple QProcess and output
tagged with: qprocess
tagged with: pyqt
answer count: 1

http://stackoverflow.com/a/50961217
has body: I have already solve the problem.I made a stupid mistake that the buffersize I set for socket.recv is too short. I set a longer buffersize like 100000000, and saving the image is easy like: f = open('D:\\2.jpg', 'wb') f.write(data) f.close()
type: Answer
upvote count: 4
downvote count: 0
score: 4
answers question: http://stackoverflow.com/q/50960490

http://stackoverflow.com/q/50910522
has comment: http://stackoverflow.com/comment/88824063
tagged with: http://stackoverflow.com/tag/json
type: Question
has comment: http://stackoverflow.com/comment/88822475
has comment: http://stackoverflow.com/comment/88823985
downvote count: 0
has comment: http://stackoverflow.com/comment/88823198
has comment: http://stackoverflow.com/comment/88824216
has title: Creating a visual tree from JSON file
tagged with: python
favorite count: 0
answer count: 0
upvote count: 2
type: UnansweredQuestion
has body: There is a lot of info how to create a tree inside JSON file, but is there any way to visualise dependencies from JSON file to any visual interface, picture or terminal as tree ( like on pictures ) ? Stole this pictures from another post There is my code to generate JSON from database ( Im generating parentID with Radom module ) : emp = [] for item in root.iter('empl'): name_tag = {'name': '', 'dep': '', 'Title': '', 'email': '', 'id': int(item.attrib['id'])} for data in item.iter('field'): if data.attrib['id'] == 'displayName': name_tag['name'] = data.text elif data.attrib['id'] == 'dep': name_tag['dep'] = data.text elif data.attrib['id'] == 'Title': name_tag['Title'] = data.text elif data.attrib['id'] == 'Email': name_tag['email'] = data.text elif data.attrib['id'] == 'id': name_tag['id'] = data.text else: continue emp.append(name_tag) session_factory = sessionmaker(engine) session = session_factory() emp_list = [TableName(name=item['name'], department=item['dep'], Title=item['Title'], email=item['email'], id=item['id']) for item in employees] avoid_duplicates = list(connection.execute('select * from TableName')) for i in emp_list: if i.name not in [j[1] for j in avoid_duplicates]: session.add(i) session.commit() write_list = [{'id': i[0], 'name': i[1], 'dep': i[2], 'Title': i[3], 'email': i[4]} for i in list(connection.execute('select * from TableName'))] session.close() connection.close() for randomID in write_list: randomID['parentId'] = random.randrange(0, 487, 2) with open('data.json', 'w') as file: json.dump(write_list, file) Afther this JSONs looks like : { "id": 9, "name": "Name1", "dep": "dep", "Title": "title", "email": "email", "parentId": 408 }, { "id": 10, "name": "Name2", "dep": "dep", "Title": "title", "email": "email", "parentId": 316 }, { "id": 12, "name": "Name3", "dep": "dep", "Title": "title", "email": "email", "parentId": 160 } Is there any way how I can visualize 'id - parentID' relations to a visual tree ?
tagged with: tree
score: 2

sqlalchemy
tags question: http://stackoverflow.com/q/50911335
tags question: http://stackoverflow.com/q/50913464
tags question: http://stackoverflow.com/q/50913589
tags question: http://stackoverflow.com/q/50937477
tags question: http://stackoverflow.com/q/50879900
tags question: http://stackoverflow.com/q/50937058
tags question: http://stackoverflow.com/q/50940145
tags question: http://stackoverflow.com/q/50927740
tags question: http://stackoverflow.com/q/50865599
tags question: http://stackoverflow.com/q/50865795
tags question: http://stackoverflow.com/q/50998456
tags question: http://stackoverflow.com/q/50938216
tags question: http://stackoverflow.com/q/50861943
tags question: http://stackoverflow.com/q/50862609
tags question: http://stackoverflow.com/q/50902512
tags question: http://stackoverflow.com/q/50959095
tags question: http://stackoverflow.com/q/50950404
tags question: http://stackoverflow.com/q/50893314
tags question: http://stackoverflow.com/q/50976041
tags question: http://stackoverflow.com/q/50892275
tags question: http://stackoverflow.com/q/50899707
tag name: sqlalchemy
tags question: http://stackoverflow.com/q/50960258
tags question: http://stackoverflow.com/q/50924057
tags question: http://stackoverflow.com/q/50884857
tags question: http://stackoverflow.com/q/50996321
tags question: http://stackoverflow.com/q/50972149
tags question: http://stackoverflow.com/q/50889452
tags question: http://stackoverflow.com/q/50895722
tags question: http://stackoverflow.com/q/50984899
tags question: http://stackoverflow.com/q/50918939
tags question: http://stackoverflow.com/q/50881639
tags question: http://stackoverflow.com/q/50906128
tags question: http://stackoverflow.com/q/50974354
tags question: http://stackoverflow.com/q/50905932
tags question: http://stackoverflow.com/q/50995345
tags question: http://stackoverflow.com/q/50974904
type: Tag

http://stackoverflow.com/comment/89010407
comment on: http://stackoverflow.com/q/51008334
type: Comment
type: QuestionComment
has text: I have marked this as a duplicate of a detailed thread on "Indentation Error". If the instructions there are followed, the error should be resolved. If it is not, a question should note specifically what part of the method described fails and why.
score: 1

http://stackoverflow.com/q/50877656
type: Question
tagged with: physics
has comment: http://stackoverflow.com/comment/88779231
tagged with: python
tagged with: python-3.x
score: 0
has body: I am creating a simulation of earth and a satellite in orbit and trying to make it follow the rules of physics but don't know how to integrate the various variables with respect to time. I tried something but feel like it is wrong. The complete code is large so some part of it is: tend=time.time() startTime=time.time() #loop starts here t = time.time() - tend r = (x**(2) + y**(2))**(1/2) if r&gt;6371000: g = -((6.67408*10**(-11))*(5.972*10**(24)))/(r**(2)) else: g = -((6.67408*10**(-11))*(5.972*10**(24))*r)/((6371000)**(3)) gx = g*x/r gy = g*y/r vx += gx*t vy += gy*t x += vx*t y += vy*t tend=time.time() So basically what i did is take the dt element (usually taken in physics) to be equal to the time taken in processing one loop of my code. Also, this is a graphical simulation in pygame but if you believe that there is some other module that can do the display job better than please tell.
has comment: http://stackoverflow.com/comment/88757995
has comment: http://stackoverflow.com/comment/88758108
has title: How to integrate(maths, physics) in python3
tagged with: math
has comment: http://stackoverflow.com/comment/88758144
answer count: 0
linked to: http://stackoverflow.com/q/44978638
has comment: http://stackoverflow.com/comment/88773123
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88776749
has comment: http://stackoverflow.com/comment/88758187

http://stackoverflow.com/comment/88789533
score: 1
type: Comment
comment on: http://stackoverflow.com/q/50894723
type: QuestionComment
has text: It's not the same thing here it's with a button and by the way nobody help me solve the search bar problem so before saying that's a duplicate could you help me solve it and like that i can edit the other one

http://stackoverflow.com/comment/88905889
comment on: http://stackoverflow.com/q/50954029
has text: You shouldn't use regex to parse something like this. You should use an actual parser
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/a/50875986
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50859599
accepted answer of: http://stackoverflow.com/q/50859599
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88775455
has body: Logging objects operate in a hierarchy, and log messages 'bubble up' the hierarchy chain and are passed to any handlers along the way (provided the log level of the message is at or exceeds the minimal threshold of the logger object you are logging on). Ignoring filtering and global log-level configurations, in pseudo code this is what happens: if record.level &lt; current_logger.level: return for logger_object in (current_logger + current_logger.parents_reversed): for handler in logger_object.handlers: if record.level &gt;= handler.level: handler.handle(record) if not logger_object.propagate: # propagation disabled, the buck stops here. break Where handlers are actually responsible for putting a log message into a file or write it to the console, etc. The problem you have is that you added your log handlers to the __name__ logger, where __name__ is the current package identifier. The . separator in the package name are hierarchy separators, so if you run this in, say, acme.tests then only the loggers in acme.tests and contained modules are being sent to this handler. Any code outside of acme.tests will never reach these handlers. Your log object hierarchy is something akin to this: - acme - frobnars - tests # logger object - test1 - test2 - widgets then only log objects in test1 and test2 will see the same handlers. You can move your logger to the root logger instead, with logging.root or logger.getLogger() (no name argument or the name set to None). All loggers are child nodes of the root logger, and as long as they don't set the propagate attribute to False, log messages will reach the root handlers. The other options are to get the acme logger object explicitly, with logging.getLogger('acme'), or always use a single, explicit logger name throughout your code that is the same in your tests and in your library. Do take into account that Nose also configures handlers on the root logger.
has comment: http://stackoverflow.com/comment/88816431
has comment: http://stackoverflow.com/comment/88809448
type: Answer

http://stackoverflow.com/q/50951335
has comment: http://stackoverflow.com/comment/88901231
type: UnansweredQuestion
tagged with: python
tagged with: namedtuple
score: 2
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/88901404
has comment: http://stackoverflow.com/comment/88901584
type: Question
has comment: http://stackoverflow.com/comment/88900687
has body: I was browsing through the source code of namedtuple (see collections/__init__.py) to see how to inherit from tuple. I noticed in the __new__ method, it doesn't call super(): def __new__(_cls, {arg_list}): 'Create new instance of {typename}({arg_list})' return _tuple.__new__(_cls, ({arg_list})) Why does it call _tuple.__new__? Isn't the correct way to call a base class method from the subclass to use super()? Like so: return super().__new__(cls, ({arg_list}))
has comment: http://stackoverflow.com/comment/88901663
has comment: http://stackoverflow.com/comment/88900737
upvote count: 2
has comment: http://stackoverflow.com/comment/88900709
has title: Why doesn't namedtuple use super()?
favorite count: 0
tagged with: python-3.x
tagged with: tuples

http://stackoverflow.com/comment/88931620
comment on: http://stackoverflow.com/a/50967570
score: 0
type: AnswerComment
has text: I tried to put hit in the "try" block but it did'nt change anything
type: Comment

http://stackoverflow.com/q/50887252
has title: python cannot import name 'is_list_like'
score: 0
has answer: http://stackoverflow.com/a/50887576
has comment: http://stackoverflow.com/comment/88786427
type: Question
linked to: http://stackoverflow.com/q/50394873
duplicate of: http://stackoverflow.com/q/50394873
tagged with: pandas
answer count: 1
has body: I am trying to run the following code using pandas_datareader on PYTHON 3.6.5 IDLE(WIN 10 SYS). #import our Python libraries import os import sys import pandas as pd import pandas_datareader.data as web import numpy as np import statsmodels.formula.api as smf import statsmodels.tsa.api as smt #tsa为Time Series analysis缩写 import statsmodels.api as sm import scipy.stats as scs from arch import arch_model import matplotlib.pyplot as plt import matplotlib as mpl %matplotlib inline It seems work on IDE eclipse, but when I try to run it on jupyter notebook, although i have installed the pandas_datareader package, jupyter continues to stop with the following errors. I have checked that it is not concerned with any circular references or any file name conflicts.Why does it happen? ImportError Traceback (most recent call last) &lt;ipython-input-4-4b149e7cab54&gt; in &lt;module&gt;() 4 5 import pandas as pd ----&gt; 6 import pandas_datareader.data as web 7 import numpy as np 8 d:\programs\python\python36\lib\site-packages\pandas_datareader\__init__.py in &lt;module&gt;() 1 from ._version import get_versions ----&gt; 2 from .data import (DataReader, Options, get_components_yahoo, 3 get_dailysummary_iex, get_data_enigma, get_data_famafrench, 4 get_data_fred, get_data_google, get_data_moex, 5 get_data_morningstar, get_data_quandl, get_data_stooq, d:\programs\python\python36\lib\site-packages\pandas_datareader\data.py in &lt;module&gt;() 12 ImmediateDeprecationError 13 from pandas_datareader.famafrench import FamaFrenchReader ---&gt; 14 from pandas_datareader.fred import FredReader 15 from pandas_datareader.google.daily import GoogleDailyReader 16 from pandas_datareader.google.options import Options as GoogleOptions d:\programs\python\python36\lib\site-packages\pandas_datareader\fred.py in &lt;module&gt;() ----&gt; 1 from pandas.core.common import is_list_like 2 from pandas import concat, read_csv 3 4 from pandas_datareader.base import _BaseReader 5 ImportError: cannot import name…
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88775879

http://stackoverflow.com/a/50921025
type: Answer
has body: urllib.request is a module. You are calling the module on line 22... req = urllib.request(url) To fix do following: 1) Import at the top: from urllib.request import urlopen 2) then pass the url to urlopen(url) # remove this line req = urllib.request(url) response = urlopen(url) data = json.loads(response.read()) 3) See similar error here TypeError: 'module' object is not callable
answers question: http://stackoverflow.com/q/50920516
score: 0

http://stackoverflow.com/q/50981207
tagged with: python
has title: Vector subtraction python 3 without using the built in functions sum, min, max and zip
has answer: http://stackoverflow.com/a/52213183
type: Question
tagged with: vector
has body: I'm fairly new to coding in the python 3 language. I am writing a code that, first, it will check the dimensions of two vectors, then if the dimensions match, it will compute the subtraction of the two vectors. I'm not sure where I'm going wrong with my code any help would be great. Thank you in advance. def vecSubtract(vector01,vector02): if len(vector01) != len(vector02): raise ValueError result = [] total = 0 for i in range(len(vector01)): total += vector01[i] - vector02[i] result.append(total) return result vector01 = [2, 3, 4] vector02 = [4, 2, 1] print(vecSubtract(vector01,vector02))
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/50981687
tagged with: python-3.x
type: UnansweredQuestion

pybind11
tags question: http://stackoverflow.com/q/50878901
type: Tag
tag name: pybind11
tags question: http://stackoverflow.com/q/50883703

http://stackoverflow.com/a/50925543
downvote count: 0
score: 1
has body: You can use ^\w{3}\s\d{2}\s\d{2}:\d{2}:\d{2} to match your dates. Live regex here. import re dates = [] with open("internet.test","r") as content_file: for line in content_file: m = re.search('^\w{3}\s\d{2}\s\d{2}:\d{2}:\d{2}',line) dates.append(m.group(0)) dates = ['Jun 15 16:26:33', 'Jun 15 16:27:13', 'Jun 15 16:27:45']
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/50924879

http://stackoverflow.com/comment/88733687
comment on: http://stackoverflow.com/q/50865611
score: 1
type: Comment
type: QuestionComment
has text: What happened when you tested it? What did you find when you researched the truth values of numbers?

http://stackoverflow.com/a/50928242
score: 6
accepted answer of: http://stackoverflow.com/q/50927890
answers question: http://stackoverflow.com/q/50927890
upvote count: 7
type: AcceptedAnswer
downvote count: 1
has body: It looks to me as if you have not evaluated the tensor. You can call tensor.eval() to evaluate the result, or use session.run(tensor). import tensorflow as tf a = tf.constant(3.5) b = tf.constant(4.5) c = a * b with tf.Session() as sess: result = c.eval() # Or use sess.run: # result = sess.run(c) print(result) # out: 15.75 print(type(result)) # out: &lt;class 'numpy.float32'&gt;
type: Answer

http://stackoverflow.com/q/50892788
type: AnsweredQuestion
has title: python/Pandas merge two data frames and return on the rows containing NaN
has answer: http://stackoverflow.com/a/50892965
accepted answer: http://stackoverflow.com/a/50892965
type: Question
tagged with: dataframe
score: 0
has comment: http://stackoverflow.com/comment/88786152
answer count: 1
has body: Is it possible to use merge to df's, df1 and df2, to return only the rows that are Nan in df2? an example: import pandas as pd import numpy as np data = {'X1': ['A', 'B', 'C', 'D', 'E'], 'X2': ['meow', 'bark', 'moo', 'squeak', 'cheep']} data2 = {'X1': ['A', 'B', 'F', 'D', 'E'], 'X3': ['cat', 'dog', 'frog', 'mouse', 'chick']} #df = pd.DataFrame(data, columns = ['name', 'age', 'preTestScore', 'postTestScore']) df = pd.DataFrame(data) df2 = pd.DataFrame(data2) pd.merge(df, df2, how ='left', on = 'X1') This returns X1 X2 X3 A meow cat B bark dog C moo NaN D squeak mouse E cheep chick I want a result that looks like: X1 X2 X3 C moo NaN I have tried every combination of merge that I can think of but I can't get it. I know I can achieve the result with lots of manipulations to the merged df, but i was hoping there was a simple efficient answer
has comment: http://stackoverflow.com/comment/88786148
tagged with: pandas
has comment: http://stackoverflow.com/comment/88786127
tagged with: python
tagged with: merge

http://stackoverflow.com/comment/88768268
comment on: http://stackoverflow.com/a/50883030
type: AnswerComment
has text: it throws an error `AttributeError: 'int' object has no attribute 'decode'`
score: 0
type: Comment

http://stackoverflow.com/a/50891549
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50891521
type: Answer
upvote count: 4
accepted answer of: http://stackoverflow.com/q/50891521
downvote count: 0
has body: As you only want to apply a single method, you can use apply instead of aggregate. The argument has to be a Python callable to be applied to each of the groups, so in your case that would look like data.groupby('model').apply(lambda group: sklearn.metrics.auc(group.FPR, group.TPR)) For example: y = np.array([1, 1, 2, 2]) pred = np.array([0.1, 0.4, 0.35, 0.8]) fpr, tpr, _ = sklearn.metrics.roc_curve(y, pred, pos_label=2) df_a = pd.DataFrame({'model': 'a', 'FPR': fpr, 'TPR': tpr}) df_b = pd.DataFrame({'model': 'b', 'FPR': fpr, 'TPR': tpr}) data = df_a.append(df_b) data.groupby('model').apply(lambda group: sklearn.metrics.auc(group.FPR, group.TPR)) Output: model a 0.75 b 0.75 dtype: float64
score: 4

http://stackoverflow.com/a/50975952
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/50975669
answers question: http://stackoverflow.com/q/50975669
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88948110
upvote count: 2
has body: You need to use fillna. Let's consider this dataframe were some age are in column currentAge and other in currentAge2: df = pd.DataFrame({'currentAge':[np.nan, 12, 15, 16, np.nan], 'currentAge2':[8, np.nan, np.nan, np.nan, 24]}) currentAge currentAge2 0 NaN 8.0 1 12.0 NaN 2 15.0 NaN 3 16.0 NaN 4 NaN 24.0 what you can do is then: df['currentAge'] = df['currentAge'].fillna(df['currentAge2']) to fill all nan in the first column by the values from the second, and then you get: currentAge currentAge2 0 8.0 8.0 1 12.0 NaN 2 15.0 NaN 3 16.0 NaN 4 24.0 24.0 To remove the column currentAge2, then do df = df.drop('currentAge2',1) and you will have a simple column currentAge filled.

http://stackoverflow.com/q/50978862
upvote count: 2
score: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/88953545
type: Question
has comment: http://stackoverflow.com/comment/88953747
has answer: http://stackoverflow.com/a/50978905
has title: Python reduce function
accepted answer: http://stackoverflow.com/a/50978905
answer count: 1
has comment: http://stackoverflow.com/comment/88953769
favorite count: 0
has comment: http://stackoverflow.com/comment/88953614
has body: I'm just learning Python, and do not understand the behavior I am getting from my reduce function. I have seen many examples where you can use reduce to perform an equivalent function to sum when you want to multiply: f = [2,3,4] reduce(lambda x,y: x*y,f) That gives me the value I expect. But I need to multiply by all the reciprocals instead. I thought I could do this: reduce(lambda x,y: 1/x * 1/y, f) But it comes out as 1.5 instead of some much smaller decimal answer. What am I doing wrong?
tagged with: python
tagged with: lambda
type: AnsweredQuestion
tagged with: reduce

http://stackoverflow.com/comment/88930626
type: AnswerComment
score: 0
type: Comment
has text: pip and pip3 configured with python2.7 and python3.5 respectively. But have project which requires python3.6 . So how to configure pip3 with python3.6 instead of python3.5. I can't remove python 3.5. I am using ubuntu 16.0.4
comment on: http://stackoverflow.com/a/50967064

http://stackoverflow.com/a/50978083
score: 7
type: Answer
upvote count: 11
answers question: http://stackoverflow.com/q/50977743
has comment: http://stackoverflow.com/comment/132799431
has body: Not the best solution really. This totally works if you already familiar with npm, but like others have suggested, use makefiles. Well, this is a work around, but apparently you can just use npm if you have it installed. I created a file package.json in root directory of python app. { "name": "fff-connectors", "version": "1.0.0", "description": "fff project to UC Davis", "directories": { "test": "tests" }, "scripts": { "install": "pip install -r requirements.txt", "test": "python -m unittest discover -v" }, "keywords": [], "author": "Leo Qiu", "license": "ISC" } then I can just use npm install or yarn install to install all dependencies, and yarn test or npm test to run test scripts. You can also do preinstall and postinstall hooks. For example, you may need to remove files or create folder structures. Another benefit is this setup allows you to use any npm libraries like concurrently, so you can run multiple files together and etc.
has comment: http://stackoverflow.com/comment/117925302
downvote count: 4

http://stackoverflow.com/q/51001899
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51002151
tagged with: python
tagged with: regex
downvote count: 2
has answer: http://stackoverflow.com/a/51003789
type: Question
has body: I have tried many regex expressions but unable to get the desired output. My string is Ms.Evalyn J Hobbs AND Mr.Jan K Hir sch AND Ms.Gale D Bannister 3611 I need to extract the digits group which come after Mr or Mrs that is 3611
score: -2
tagged with: javascript
answer count: 2
has comment: http://stackoverflow.com/comment/88997798
has comment: http://stackoverflow.com/comment/88997650
upvote count: 0
has title: Regex to find digits group after a text match
favorite count: 0

http://stackoverflow.com/a/50892687
upvote count: 1
downvote count: 0
has body: If l is your nested list, then map(func, *l) will contain the list of all o/p from the function func with required args and {e:func(*e) for e in zip(*l)} will contain the results in dict format &gt;&gt;&gt; def func(*args): &gt;&gt;&gt; return f'O/P of func: {args}' &gt;&gt;&gt; &gt;&gt;&gt; l = [['x1min','x1max'],['x2min','x2max'],['xnmin','xnmax']] &gt;&gt;&gt; [*map(func, *l)] ["O/P of func: ('x1min', 'x2min', 'xnmin')", "O/P of func: ('x1max', 'x2max', 'xnmax')"] &gt;&gt;&gt; &gt;&gt;&gt; {e:func(*e) for e in zip(*l)} {('x1min', 'x2min', 'xnmin'): "O/P of func: ('x1min', 'x2min', 'xnmin')", ('x1max', 'x2max', 'xnmax'): "O/P of func: ('x1max', 'x2max', 'xnmax')"} &gt;&gt;&gt;
answers question: http://stackoverflow.com/q/50892564
type: Answer
has comment: http://stackoverflow.com/comment/88785975
score: 1
has comment: http://stackoverflow.com/comment/88786029
has comment: http://stackoverflow.com/comment/88786087

http://stackoverflow.com/comment/88987198
comment on: http://stackoverflow.com/q/50995404
has text: the model is.(def neural_network_model(data): l1 = tf.add(tf.matmul(data,hidden_1_layer['weight']), hidden_1_layer['bias']) l1 = tf.nn.relu(l1) l2 = tf.add(tf.matmul(l1,hidden_2_layer['weight']), hidden_2_layer['bias']) l2 = tf.nn.relu(l2) l3 = tf.add(tf.matmul(l2,hidden_3_layer['weight']), hidden_3_layer['bias']) l3 = tf.nn.relu(l3) output = tf.matmul(l3,output_layer['weight']) + output_layer['bias'] return output)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88913852
score: 0
type: Comment
type: QuestionComment
has text: _"The following code works on the given Xml"_ - What version of Python and lxml? I can't get your example to run without modifications using Python 3.6 and lxml 4.2.1.
comment on: http://stackoverflow.com/q/50957772

http://stackoverflow.com/q/50901790
score: 1
linked to: http://stackoverflow.com/q/37096225
tagged with: tensorflow
type: Question
has title: Sampling in tensorflow
has comment: http://stackoverflow.com/comment/88804401
has comment: http://stackoverflow.com/comment/88804441
has comment: http://stackoverflow.com/comment/88805671
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/88804378
has body: I am sampling points in each image using the following function. tf.range gives an error if batch_size is None. How do I sample in tensorflow def sampling(binary_selection,num_points, points): """ binary_selection: tensor of size (batch_size, points) with values 1.0 or 0.0. Indicating positive and negative points. We want to sample num_points from positive points of each image points: tensor of size (batch_size, num_points_in_image) num_points: number of points to sample for each image """ batch_size = points.get_shape()[0] indices = tf.multinomial((tf.log(binary_selection)), num_points) indices = tf.cast(tf.expand_dims(indices, axis=2), tf.int32) batch_seq = tf.expand_dims(tf.range(batch_size), axis=1) im_indices = tf.expand_dims(tf.tile(batch_seq, [1, num_points]), axis=2) indices = tf.concat([im_indices, indices], axis=2) return tf.gather_nd(points, indices) I get the following error _dimension_tensor_conversion_function raise ValueError("Cannot convert an unknown Dimension to a Tensor: %s" % d) ValueError: Cannot convert an unknown Dimension to a Tensor: ? During the test and training time I will have batch_size an integer but when I initialize I want to give None as input so that batch size can be varied during test and training time.
has answer: http://stackoverflow.com/a/50901811
accepted answer: http://stackoverflow.com/a/50901811
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/88803622
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88804411
downvote count: 0

http://stackoverflow.com/a/50931444
has body: Though you don't say that explicitly, the fact that you said "As a first step...", makes me think you are heading towards a greyscale palette image: import numpy as np from PIL import Image labels=[[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,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,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,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,1,1,0,0,3,3,0,0,0,4,4,0,0,0,5,5,5,5,0,0,2,2,2,2,2,0,2,2,2,2,2,0,0,0,6,6,6,6,6,6,0,6,6,6,6], [0,1,1,0,0,0,0,0,0,0,0,0,0,3,3,0,0,0,4,4,0,0,5,5,5,5,5,5,0,2,2,2,2,2,2,2,2,2,2,2,2,0,0,6,6,6,6,6,6,6,6,6,6,6], [1,1,1,0,0,0,0,0,0,0,0,0,0,3,3,0,0,0,4,4,0,5,5,5,0,0,5,5,5,0,2,2,0,0,2,2,0,0,0,2,2,0,0,6,6,0,0,6,6,6,0,0,6,6], [1,1,1,0,0,0,0,0,0,0,0,0,0,3,3,0,0,0,4,4,0,5,5,5,5,0,0,0,0,0,2,2,0,2,2,2,0,0,0,2,2,2,0,6,6,0,0,0,6,6,0,0,6,6], [1,1,1,0,0,0,0,0,0,0,0,0,0,3,3,0,0,0,4,4,0,0,5,5,5,5,5,5,0,0,2,2,0,2,2,2,0,0,0,2,2,2,0,6,6,0,0,0,6,6,0,0,6,6], [0,1,1,0,0,0,0,0,0,7,0,0,0,3,3,0,0,0,4,4,0,0,0,0,5,5,5,5,5,0,2,2,0,2,2,2,0,0,0,2,2,2,0,6,6,0,0,0,6,6,0,0,6,6]] binary_transform = np.array(labels).astype(np.uint8) img = Image.fromarray(binary_transform, 'P') img.save('image.png') Note that I have resized and contrast-stretched the image for display purposes. If you really only want a true binary, black and white image, use: binary_transform = np.array(labels).astype(np.uint8) binary_transform[binary_transform&gt;0] = 255 img = Image.fromarray(binary_transform, 'L') img.save('image.png')
answers question: http://stackoverflow.com/q/50930832
has comment: http://stackoverflow.com/comment/88861940
accepted answer of: http://stackoverflow.com/q/50930832
upvote count: 3
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88861854
type: Answer
score: 3
downvote count: 0

http://stackoverflow.com/q/50882971
type: Question
tagged with: opencv
has comment: http://stackoverflow.com/comment/93792445
upvote count: 1
has body: When I run this code in the Linux system with python virtualenv and OpenCV: import glob as gb import cv2 import random import os img_path_htc=gb.glob("/home/project/venv/data/train/new/*.jpg") counter= 1 for path in img_path_htc: img = cv2.imread(path) cv2.imshow("img",img) cv2.waitKey(1000) for i in range(10): x = random.randint(300, img.shape[1] - 300 - 256 ) y = random.randint(300, img.shape[0] - 300 - 256 ) crop_img = img[y:y+256,x:x+256] save_path = "/home/project/venv/data/train/new/patch" filename='img'+str(counter)+'.jpg' counter=counter+1 savepath = os.path.join(save_path,filename) cv2.imshow("crop_img"+str(i),crop_img) cv2.imwrite(savepath, crop_img) cv2.waitKey(1000) I got this error: QObject::moveToThread: Current thread (0x128e5e0) is not the object's thread (0x193bf70). Cannot move to target thread (0x128e5e0) Thanks.
tagged with: virtualenv
has title: linux with python using OpenCV got QObject moveToThread
favorite count: 0
tagged with: linux
tagged with: python
answer count: 0
downvote count: 0
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/93772459

pypdf
tags question: http://stackoverflow.com/q/51010644
tags question: http://stackoverflow.com/q/50938913
type: Tag
tag name: pypdf
tags question: http://stackoverflow.com/q/50858615

http://stackoverflow.com/comment/88879514
has text: Please send a snapshot of your command prompt if possible. NameError is coming from an undefined variable or a library not available. Have a keen look at it.
type: Comment
comment on: http://stackoverflow.com/a/50940784
type: AnswerComment
score: 0

http://stackoverflow.com/comment/89008771
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51007255
has text: [aravind@aravind05 /]$ alias python python3 bash: alias: python: not found bash: alias: python3: not found
score: 0

http://stackoverflow.com/q/50992946
has body: This is from a Custom Keras Callback casted=K.cast((yPred), K.tf.int32) I absolutely need to cast yPred, which is a Tensor, to the type int32 (The cast is applied to the Tensor content, I know that) Still, K.cast allow only a conversion to float. How can I solve the problem?
tagged with: tensor
accepted answer: http://stackoverflow.com/a/50993354
has comment: http://stackoverflow.com/comment/88980696
has comment: http://stackoverflow.com/comment/88981208
possible better answer: http://stackoverflow.com/a/57676677
has comment: http://stackoverflow.com/comment/88981229
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/57676677
score: 4
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/88980721
type: Question
upvote count: 4
answer count: 2
tagged with: casting
has answer: http://stackoverflow.com/a/50993354
downvote count: 0
tagged with: keras
favorite count: 0
tagged with: python
has title: Cast KERAS Tensor to K.tf.int32

http://stackoverflow.com/comment/88865794
has text: And what is the question exactly?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50933190
score: 0

http://stackoverflow.com/q/50867573
has comment: http://stackoverflow.com/comment/88738993
has comment: http://stackoverflow.com/comment/88738431
score: 0
tagged with: python
has body: I'm trying to learn some TensorFlow (Python) basics from Google's Crash Course online. However, I'm finding the explanations a little light and am confused how to use this beyond the examples / tasks they set. For example, there is a basic task to predict housing prices in California using Linear Regression with Gradient Descent (see: https://colab.research.google.com/notebooks/mlcc/validation.ipynb) The tasks are all about training and then testing a model using an existing dataset. This works well, but I'm struggling to use the code to predict house prices for arbitrary input values (i.e. not from the test/training set). The problem arises because the input function to the LinearRegressor requires you to enter the target values, which of course are unknown if you want to make predictions: e.g. predict_test_input_fn = lambda: my_input_fn( test_examples, test_targets["median_house_value"], num_epochs=1, shuffle=False) where the my_input_func is defined within the Crash Course notebook (see link above). If anyone is familiar with TensorFlow / the Google ML Crash Course, could you perhaps please explain what should be entered as a target value, when the point of using a trained model is to find unknown values? Thank you very much for any help!
answer count: 0
type: UnansweredQuestion
tagged with: machine-learning
tagged with: tensorflow
has title: How to predict using LinearRegressor in TensorFlow (without being forced to enter the solution)?
tagged with: linear-regression
type: Question

http://stackoverflow.com/q/50937824
has title: Click on link using selenium webdriver
answer count: 3
has answer: http://stackoverflow.com/a/51732204
has answer: http://stackoverflow.com/a/50940637
tagged with: python
has body: I am trying to click on a link and can't seem to get it to work. I click all the way up to the page I need, but then it won't click the last link. The code is as follows: from selenium import webdriver from selenium.webdriver.support.ui import Select from selenium.webdriver.common.keys import Keys import time from bs4 import BeautifulSoup import requests import pandas as pd import openpyxl from password import DKpassword #import SendKeys beginningTime = time.time() browser = webdriver.Chrome() browser.get('https://www.draftkings.com/lobby') browser.maximize_window() time.sleep(5) signinLink = browser.find_element_by_xpath("""//*[@id="react-mobile-home"]/section/section[2]/div[2]/div[3]/div/input""") signinLink.click() signinLink.send_keys("abcdefg") signinLink.send_keys(Keys.TAB) passwordLink = browser.find_element_by_xpath("""//*[@id="react-mobile-home"]/section/section[2]/div[2]/div[4]/div/input""") passwordLink.send_keys(DKpassword) passwordLink.send_keys(Keys.ENTER) time.sleep(5) if browser.current_url == "https://www.draftkings.com/account/sitelogin/false?returnurl=%2Flobby1": signin = browser.find_element_by_partial_link_text("SIGN IN") signin.click() elif browser.current_url == "https://www.draftkings.com/lobby#/featured": mlbLink = browser.find_element_by_partial_link_text("MLB") mlbLink.click() else: print("error") time.sleep(5) featuredGame = browser.find_element_by_class_name("GameSetTile_tag") featuredGame.click() time.sleep(5) firstContest = browser.find_element_by_partial_link_text("Enter") firstContest.click() I receive the error message that the element is not clickable at point... and another element would receive the click. Any help would be greatly appreciated. I don't care which contest is clicked on as long as it is on the featured page which the previous code directs it too.
accepted answer: http://stackoverflow.com/a/50941600
favorite count: 0
type: AnsweredQuestion
downvote count: 0
tagged with: selenium
has comment: http://stackoverflow.com/comment/88878335
has answer: http://stackoverflow.com/a/50941600
type: Question
has comment: http://stackoverflow.com/comment/88876693
score: 1
tagged with: webdriver
upvote count: 1
possible better answer: http://stackoverflow.com/a/50940637

http://stackoverflow.com/a/51007777
has comment: http://stackoverflow.com/comment/89513765
has comment: http://stackoverflow.com/comment/89012157
answers question: http://stackoverflow.com/q/50999577
has body: First of all, your if statement is not reachable. Because you had a return before it. When you call return in a function, the next lines of function those are after the return will not execute. So you should change the index function. Also, you should send an identifier of the product with your post request. Identifier could be the id or any other unique field in your model. So your code should be something like this: def index(request): if request.method == 'POST': # Request is post and you want to update a product. try: product = Product.objects.get(unique_field=request.POST.get("identifier")) # You should chnage `unique_field` with your unique filed name in the model and change `identifier` with the product identifier name in your form. product.in_cart = True product.save() return HttpResponse('', status=200) except Product.DoesNotExist: # There is no product with that identifier in your database. So a 404 response should return. return HttpResponse('Product not found', status=404) except Exception: # Other exceptions happened while you trying saving your model. you can add mor specific exception handeling codes here. return HttpResponse('Internal Error', status=500) elif request.method == "GET": # Request is get and you want to render template. products_list = Product.objects.all() template = loader.get_template('products/index.html') context = {'products_list': products_list} return HttpResponse(template.render(context, request)) return HttpResponse('Method not allowed', status=405) # Request is not POST or GET, So we should not allow it. I added all information you need in the comments of the code. I think you should spend more time on python and django documents. But if you still have any questions, you can ask in comments. After question edit If you don't want to use a readonly field in your form, you should make two changes in your code. First of all, you should add a url with product_id parameter in your urls.py file. Something like this: url(r'^add_to_car…
type: Answer
has comment: http://stackoverflow.com/comment/89034662
has comment: http://stackoverflow.com/comment/89534693
has comment: http://stackoverflow.com/comment/89062023
has comment: http://stackoverflow.com/comment/89526469
upvote count: 1
has comment: http://stackoverflow.com/comment/89016318
has comment: http://stackoverflow.com/comment/89478930
has comment: http://stackoverflow.com/comment/89021115
score: 1
has comment: http://stackoverflow.com/comment/89477529
has comment: http://stackoverflow.com/comment/89473904
accepted answer of: http://stackoverflow.com/q/50999577
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/50881917
has comment: http://stackoverflow.com/comment/88766877
has answer: http://stackoverflow.com/a/50883362
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/72279089
has answer: http://stackoverflow.com/a/50882709
has body: I have a data frame with all categorical variables and when I apply df.isnull().sum(axis=0). or even df.isna gives 0. to get all the nans column wise I get an output which shows 0 for all columns however I can see many missing values when I do df.head(50). I think it is because it is obj types it is not getting identified. Is there a workaround?
accepted answer: http://stackoverflow.com/a/50883362
favorite count: 0
possible better answer: http://stackoverflow.com/a/72279089
upvote count: 2
tagged with: python
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/88766292
has title: How do I identify nan values in pandas data frame where all variables are categorical?
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88766506

http://stackoverflow.com/comment/88755293
comment on: http://stackoverflow.com/a/50876688
has text: Or 'f.write("".join(newlines))' instead of the last two lines. Or alternatively just append to a string instead of a list.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/88760829
comment on: http://stackoverflow.com/q/50878441
score: 0
type: Comment
type: QuestionComment
has text: Two questions spring to mind: (1) do you have any firewalls enabled and (2) how do you know that this other device is correctly connected to the network? (See https://superuser.com/questions/614600/tcp-syn-does-not-reach-tcp-server for an example of a possibly related case...)

http://stackoverflow.com/comment/88751497
type: Comment
score: 0
has text: Well, OP didn't say anything regarding the list size, so I assumed it is not large enough to make the difference between O(n) and O(n^2). Definitely, using `Counter` is more efficient approach but I intended to give a quick-and-dirty solution that works well in most cases.
comment on: http://stackoverflow.com/a/50871791
type: AnswerComment

http://stackoverflow.com/comment/88740593
has text: If you just need to return a boolean you can use regex to match any digit in the string `\d`
score: 1
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50869465

http://stackoverflow.com/a/52180363
score: 2
downvote count: 0
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/50940180
has body: You can also go to your launch.json and set "internalConsoleOptions": "openOnSessionStart". This attribute should go in the configuration that you're currently using for debug, it's listed next to the green play button when debugging mode is selected. The attribute was specifically created for the purpose of displaying the debug console by default after debugging. My launch.json display: That's also where you'll put the "console": "none" attribute if you go that route. You could do both for good measure: My launch.json display with both attributes:

http://stackoverflow.com/comment/88951223
comment on: http://stackoverflow.com/q/50977031
type: QuestionComment
has text: I wanted to use with to handle the connection to the db but I did so many searches for help on the syntax and came up short, so I had to abandon that method. I have seen people refer to WAL before, but I am completely unfamiliar with that at the moment. As for the whitespace, that was more for readability for myself. As I get more proficient with Python and can trust my code more, I'll probably make some changes to how I write a lot of things.
score: 0
type: Comment

http://stackoverflow.com/comment/88963924
comment on: http://stackoverflow.com/q/50983559
has text: @Spangen Is it should be like `curl -K "aaa.txt"` ???
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88873012
type: Comment
type: QuestionComment
score: 1
has text: Please post reproducible data. Also the specific desired output: do you want a dataframe? table? dict?
comment on: http://stackoverflow.com/q/50937231

http://stackoverflow.com/comment/88851519
type: AnswerComment
comment on: http://stackoverflow.com/a/50926034
has text: Will you please give me an example?
type: Comment
score: 0

http://stackoverflow.com/comment/117763373
score: 1
has text: Does this answer your question? [How to run PyTorch on GPU by default?](https://stackoverflow.com/questions/43806326/how-to-run-pytorch-on-gpu-by-default)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50954479

http://stackoverflow.com/q/50900038
favorite count: 0
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/88800057
has body: The parameter is a string. Check whether it forms a secure password. A password is safe if there is at least a lowercase letter in it, and there is at least one capital letter in it, and there is at least one digit in it, and there is at least one special character (+, -, *, /,. or @) in it, and it counts at least 8 characters, and it has a maximum of 20 characters, and there are no three equal consecutive characters in it (eg 'a7XXX @ fda' is invalid because of the XXX), and no group of three characters occurs multiple times (eg 'XYZ.1a.XYZ' is invalid because XYZ appears twice). I tried: regex = [r'^.{8,20}$', r'[a-z]+', r'[A-Z]+', r'\d+', r'[-+*/.@]', r'(.)(.)(.)(\1\2\3)'] return all(re.search(pas, password) for pas in regex)
upvote count: 2
accepted answer: http://stackoverflow.com/a/50900991
has comment: http://stackoverflow.com/comment/88800272
has title: Password validation in python with regex without duplicate chars
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88801048
has comment: http://stackoverflow.com/comment/88800046
score: -2
has comment: http://stackoverflow.com/comment/88800222
has answer: http://stackoverflow.com/a/50900991
has comment: http://stackoverflow.com/comment/88800044
type: Question
has comment: http://stackoverflow.com/comment/88800086
downvote count: 4
answer count: 1

http://stackoverflow.com/comment/88952995
score: 0
comment on: http://stackoverflow.com/q/50977031
type: QuestionComment
has text: Well again, your help guided me to not just one problem I had but two and hopefully I won't make the mistake again. Thanks!
type: Comment

http://stackoverflow.com/comment/88996163
type: Comment
has text: Ok, I tried it but it's throwing `a bytes-like object is required, not 'int'` Is it possible error? or Did I something wrong?
comment on: http://stackoverflow.com/a/51000934
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88918798
score: 1
has text: A simpler solution compared to the one I was working on.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50960975

http://stackoverflow.com/comment/88908771
has text: It stops and shows the message but when I correct the capitalization it still stops me from continuing
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50955069

http://stackoverflow.com/a/51396975
upvote count: 13
score: 12
downvote count: 1
answers question: http://stackoverflow.com/q/50951955
type: Answer
has body: From https://pypi.org/project/pytesseract/ : pytesseract.pytesseract.tesseract_cmd = '&lt;full_path_to_your_tesseract_executable&gt;' # Include the above line, if you don't have tesseract executable in your PATH # Example tesseract_cmd: 'C:\\Program Files (x86)\\Tesseract-OCR\\tesseract'

http://stackoverflow.com/comment/88926608
has text: I couldn't move it because I don't have enough reputation.
type: Comment
comment on: http://stackoverflow.com/a/50942380
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88946649
score: 1
type: AnswerComment
type: Comment
has text: records = numpy.rec.fromarrays((a, b), names=('keys', 'data')) ||| this code will help you create "Record Array", FYI, variable "a" is a single numpy array, and variable "b" is a single numpy array. And was concatenated within a single numpy array called records. You can call numpy array A by calling it "records.keys", and call number array B by calling it "records.data". (Sorry, but as much as I want to give a better explaination, the mobile version of StackOverflow doesn't help me to create a more tidy explaination)
comment on: http://stackoverflow.com/a/50975149

http://stackoverflow.com/q/50985232
type: Question
tagged with: python
has title: How string concatenation works in python?
has comment: http://stackoverflow.com/comment/88965306
upvote count: 2
duplicate of: http://stackoverflow.com/q/40996801
has body: Why does f work much faster than g? def f(n): s = '' for i in range(n): s = s + 'x' return s def g(n): s, t = '', '' for i in range(n // 2): s = t + 'x' t = s + 'x' return t print(len(f(500000))) - 0.1s print(len(g(500000))) - 7.684s Return values are the same. Why f has linear complexity, but g quadratic?
tagged with: performance
tagged with: algorithm
linked to: http://stackoverflow.com/q/25503703
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/25503703
has comment: http://stackoverflow.com/comment/88968237
score: 2
downvote count: 0
answer count: 0
has comment: http://stackoverflow.com/comment/88985836
tagged with: string
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88968271
linked to: http://stackoverflow.com/q/40996801

http://stackoverflow.com/comment/88814403
comment on: http://stackoverflow.com/q/50907206
type: Comment
type: QuestionComment
has text: What isn't working with your code above? And did you see this [how to write to a new cell in python using openpyxl](https://stackoverflow.com/questions/31395058/how-to-write-to-a-new-cell-in-python-using-openpyxl) ?
score: 1

http://stackoverflow.com/a/50855264
answers question: http://stackoverflow.com/q/50855155
has body: You can use Pandas and the purpose-built method pd.DataFrame.pivot_table: import pandas as pd # read data df = pd.read_csv('file.csv') # extract month df['Month'] = pd.to_datetime(df['disbursementdate']).apply(lambda x: x.replace(day=1)) # pivot results res = df.pivot_table(index='Month', columns='product', values='amount', aggfunc='sum', fill_value=0).reset_index() # reformat month res['Month'] = res['Month'].dt.strftime('%B %Y') print(res) product Month HL PL 0 January 2017 1000 0 1 February 2018 0 1000
score: 0
type: Answer

http://stackoverflow.com/comment/88736869
has text: I want to print them apart from other items and return them back to use in other functions.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50867244

http://stackoverflow.com/comment/88826828
type: Comment
comment on: http://stackoverflow.com/q/50913292
score: 1
has text: Can you show more code to illustrate your problem?
type: QuestionComment

http://stackoverflow.com/q/51009185
has answer: http://stackoverflow.com/a/51021008
tagged with: postgis
upvote count: 4
answer count: 1
downvote count: 0
has title: Convert a shapefile of polygons to numpy array
favorite count: 0
type: UnansweredQuestion
tagged with: python
type: Question
has body: I have a shapefile of polygons with their geometry, a column of time and a column a value. The data looks like this: | TIME | AVG | geometry ---- ----+-----+-------------------------------- 0 | NaN | NaN | POLYGON((-0.1599375 51.3977, ... The Nan value means that this specific polygon does not have value. I want to transform this to a 3D numpy array (according to time) where each cell will be labelled with the value of the grid. I have tried this one but I am getting 0 everywhere. source_ds = ogr.Open("C:/Users/Nathan/Desktop/pl.shp") source_layer = source_ds.GetLayer() pixelWidth = pixelHeight = 0.001 x_min, x_max, y_min, y_max = source_layer.GetExtent() cols = int((x_max - x_min) / pixelHeight) rows = int((y_max - y_min) / pixelWidth) target_ds = gdal.GetDriverByName('GTiff').Create('temp.tif', cols, rows, 1, gdal.GDT_Byte) target_ds.SetGeoTransform((x_min, pixelWidth, 0, y_min, 0, pixelHeight)) band = target_ds.GetRasterBand(1) NoData_value = 0 band.SetNoDataValue(NoData_value) band.FlushCache() gdal.RasterizeLayer(target_ds, [1], source_layer, options = ["ATTRIBUTE=VALUE"]) target_dsSRS = osr.SpatialReference() target_dsSRS.ImportFromEPSG(4326) target_ds.SetProjection(target_dsSRS.ExportToWkt()) k=gdal.Open('temp.tif').ReadAsArray() Any idea how to do it? Thank you
score: 4

http://stackoverflow.com/q/50968896
score: 0
has comment: http://stackoverflow.com/comment/88934377
type: Question
has answer: http://stackoverflow.com/a/50969505
tagged with: python-2.7
answer count: 1
has comment: http://stackoverflow.com/comment/88934874
has comment: http://stackoverflow.com/comment/88934162
has body: I currently have a data frame that looks like this Temp1 Temp2 Pattern Errors 307.858K 303.197K F0's 0 297.960K 282.329K F1's 0 277K 260K CA 0 262K 238K C5 0 228K 168K DATA==ADDR 0 192K 140K PRBS 0 197K 77K F0's 0 199.9K 77.3K F1's 0 199K 773K CA 0 C5 0 DATA==ADDR 0 PRBS 0 F0's 0 F1's 0 CA 0 C5 0 DATA==ADDR 0 PRBS 0 F0's 0 F1's 0 CA 0 C5 0 DATA==ADDR 0 PRBS 0 . . . . . . Expected output table Temp1 Temp2 Pattern Errors F0's 0 F1's 0 CA 0 C5 0 DATA==ADDR 0 PRBS 0 307.858K 303.197K F0's 0 F1's 0 CA 0 C5 0 DATA==ADDR 0 PRBS 0 297.960K 282.329K F0's 0 F1's 0 CA 0 C5 0 DATA==ADDR 0 PRBS 0 277K 260K F0's 0 F1's 0 CA 0 C5 0 DATA==ADDR 0 PRBS 0 262K 238K . . . . . . I want to change it to where the temperature column is split up to have a value for each section. ie. the first 2 temperature values correspond to the values from the second F0's to PRBS, then the second 2 temperature values correspond to the next set of 6 patterns. I thought the best way to do this would be adding 6 blank spaces before each entry but I don't know if that is the best way to do it and if it is, I'm not really sure how to go around doing it, any help will be appreciated. EDIT: This data frame is created by concatenating 3 different dataframes I created earlier by parsing through a log file. results = pd.concat([tempFrame, patternFrame, errorsFrame], axis = 1, sort = False) The tempFrame contains the first 2 columns, the patternFrame contains the Pattern column and errorsFrame contains the Errors column. tempFrame: tempFrame = tempFrame.assign(newIndex = tempFrame.groupby('Extra').cumcount()) tempFrame= tempFrame.set_index(['newIndex', 'Extra']).unstack().swaplevel(0, axis = 1).sort_index(axis = 1, level = 0)
tagged with: pandas
has comment: http://stackoverflow.com/comment/88934943
accepted answer: http://stackoverflow.com/a/50969505
tagged with: python
has title: Adding empty spaces in a dataframe in one column?
type: AnsweredQuestion

http://stackoverflow.com/q/51009135
tagged with: opencv
type: AnsweredQuestion
tagged with: hough-transform
tagged with: image-processing
has answer: http://stackoverflow.com/a/51046128
type: Question
upvote count: 4
linked to: http://stackoverflow.com/q/3684484
answer count: 2
has body: I am trying to detect the lines within an image using the Hough Transformation. Therefore I first create the accumulator like this: from math import hypot, pi, cos, sin from PIL import Image import numpy as np import cv2 as cv import math def hough(img): thetaAxisSize = 460 #Width of the hough space image rAxisSize = 360 #Height of the hough space image rAxisSize= int(rAxisSize/2)*2 #we make sure that this number is even img = im.load() w, h = im.size houghed_img = Image.new("L", (thetaAxisSize, rAxisSize), 0) #legt Bildgroesse fest pixel_houghed_img = houghed_img.load() max_radius = hypot(w, h) d_theta = pi / thetaAxisSize d_rho = max_radius / (rAxisSize/2) #Accumulator for x in range(0, w): for y in range(0, h): treshold = 255 col = img[x, y] if col &gt;= treshold: #determines for each pixel at (x,y) if there is enough evidence of a straight line at that pixel. for vx in range(0, thetaAxisSize): theta = d_theta * vx #angle between the x axis and the line connecting the origin with that closest point. rho = x*cos(theta) + y*sin(theta) #distance from the origin to the closest point on the straight line vy = rAxisSize/2 + int(rho/d_rho+0.5) #Berechne Y-Werte im hough space image pixel_houghed_img[vx, vy] += 1 #voting return houghed_imgcode here And then call the function like this: im = Image.open("img3.pgm").convert("L") houghed_img = hough(im) houghed_img.save("ho.bmp") houghed_img.show() The result seems to be okay: So here comes the problem. I know want to find the top 3 highest values in the hough space and transform it back to 3 lines. The highest values should be the strongest lines. Therefore I am first looking for the highest values within the pixel array and take the X and Y values of the maxima I found. From my understading this X and Y values are my rho and theta. I finding the maxima like this: def find_maxima(houghed_img): w, h = houghed_img.size max_radius = hypot(w, h) pixel_houghed_img = houghed_img.load() max1, max2, max3 = 0, 0, 0 x1position, x2pos…
downvote count: 0
score: 4
favorite count: 0
has comment: http://stackoverflow.com/comment/89028347
accepted answer: http://stackoverflow.com/a/51046128
has title: How do I transform the values of an accumulator [Hough Transformation] back to a line on a canvas?
tagged with: python
has comment: http://stackoverflow.com/comment/89021086
possible better answer: http://stackoverflow.com/a/51012347
has answer: http://stackoverflow.com/a/51012347
tagged with: computer-vision

http://stackoverflow.com/q/50861642
upvote count: 2
type: UnansweredQuestion
tagged with: python
tagged with: kivy
has title: Python Kivy recycle view prints extra button
type: Question
has body: I'm attempting to implement a recycle view widget in my kivy program. Its working fine, responding to the on press event etc but when it draws it adds an extra row that does not fit the formatting of the others. Here is the relevant part of my code, there is a lot so I only included this but I'll post more if needed. Any help is appreciated. I like kivy but this is def the strangest widget I have used in it. Output py file class MessageBox(Popup): def popup_dismiss(self): self.dismiss() class SelectableButton(RecycleDataViewBehavior, Button): index = None def refresh_view_attrs(self, rv, index, data): """ Catch and handle the view changes """ self.index = index return super(SelectableButton, self).refresh_view_attrs(rv, index, data) def on_press(self): self.parent.selected_value = 'Selected: {}'.format(self.parent.btn_info[int(self.id)]) def on_release(self): MessageBox().open() class SelectableRecycleBoxLayout(FocusBehavior, LayoutSelectionBehavior, RecycleBoxLayout): selected_value = StringProperty('') btn_info = ListProperty(["ButtonText" for x in range(0,2)]) class MainScreen(RecycleView): rv_layout = ObjectProperty(None) def __init__(self, **kwargs): super(MainScreen, self).__init__(**kwargs) self.data = [{'text': "Button" + str(x), 'id': str(x)} for x in range(0,2)] kv file &lt;MessageBox&gt;: title: 'Popup Message Box' size_hint: None, None size: 400, 400 BoxLayout: orientation: 'vertical' #Label: #text: app.root.rv_layout.selected_value Button: size_hint: 1, 0.2 text: 'OK' on_press: root.dismiss() &lt;SelectableButton&gt;: orientation: 'horizontal' Button: size_hint_x: .10 text: '+' #font_size: 50 texture_size: self.width, self.height size: self.texture_size Button: size_hint_x: .90 text: root.text #font_size: 50 texture_size: self.width, self.height size: self.texture_size &lt;MainScreen&gt;: pos_hint: {'x': 0, 'y': .11} size_hint: 1, .70 viewclass: 'SelectableButton' SelectableRecycleBoxLayout: id: layout default_size_hint: 1, 1 #size_hint_y: None height: …
score: 2
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/50862346
favorite count: 0

http://stackoverflow.com/comment/88967623
type: Comment
comment on: http://stackoverflow.com/q/50984623
has text: You're welcome, good to know it works now.
score: 0
type: QuestionComment

http://stackoverflow.com/a/50922946
has comment: http://stackoverflow.com/comment/88845406
type: Answer
has comment: http://stackoverflow.com/comment/88845491
has comment: http://stackoverflow.com/comment/88845158
has comment: http://stackoverflow.com/comment/88845309
upvote count: 3
has body: Using pandas. Try a groupby, sum, and agg. import pandas as pd df = pd.read_excel('C:\\Users\\a593977\\Desktop\\ExcelTest.xlsx', header=None) res = (df .groupby(df.columns[0], as_index=False, sort=False)[df.columns[1]] .sum() .astype(str) .agg(':'.join, 1) .tolist() ) print(res) ['1:6', '2:3', '3:4', '4:5', '5:6']
answers question: http://stackoverflow.com/q/50922779
score: 3
has comment: http://stackoverflow.com/comment/88845515
accepted answer of: http://stackoverflow.com/q/50922779
has comment: http://stackoverflow.com/comment/88845325
has comment: http://stackoverflow.com/comment/88845594
has comment: http://stackoverflow.com/comment/88845379
has comment: http://stackoverflow.com/comment/88845182
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/88979925
comment on: http://stackoverflow.com/q/50991338
score: 0
type: QuestionComment
type: Comment
has text: Thank for taking at look at this guys. I guess I may be a bug, I'll look into it. It still does not work as expected for me. Im on Python 3.6

http://stackoverflow.com/a/50878045
has comment: http://stackoverflow.com/comment/88759482
type: Answer
score: 1
has body: You can zip the outputs together, but you will need to populate n and function with a loop. Why strings? n = [0,1,2,3,4,5,6,7,8,9,10] function = [1.35335283e-01,2.70670566e-01,2.70670566e-01, 1.80447044e-01,9.02235222e-02,3.60894089e-02, 1.20298030e-02,3.43708656e-03,8.59271640e-04, 1.90949253e-04,3.81898506e-05] zipped = list(zip(n,function)) zipped Out[ ]: [(0, 0.135335283), (1, 0.270670566), (2, 0.270670566), (3, 0.180447044), (4, 0.0902235222), (5, 0.0360894089), (6, 0.012029803), (7, 0.00343708656), (8, 0.00085927164), (9, 0.000190949253), (10, 3.81898506e-05)] And I agree that not allowing you to print with a loop is a pointless requirement. for a,b in zipped: print('n =',a,', function =',b) Out[ ]: n = 0 , function = 0.135335283 n = 1 , function = 0.270670566 n = 2 , function = 0.270670566 n = 3 , function = 0.180447044 n = 4 , function = 0.0902235222 n = 5 , function = 0.0360894089 n = 6 , function = 0.012029803 n = 7 , function = 0.00343708656 n = 8 , function = 0.00085927164 n = 9 , function = 0.000190949253 n = 10 , function = 3.81898506e-05
upvote count: 1
has comment: http://stackoverflow.com/comment/88759591
has comment: http://stackoverflow.com/comment/88759391
answers question: http://stackoverflow.com/q/50877893
downvote count: 0

http://stackoverflow.com/comment/88877712
has text: Sorry, but what do you mean about capturing only a fraction of the observations? I group the data points into the bins, and then would like to normalize the bins themselves.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50939792
type: Comment

http://stackoverflow.com/comment/112115196
type: AnswerComment
type: Comment
has text: Shouldn't the `defaults` in your example be a dictionary?
comment on: http://stackoverflow.com/a/50916087
score: 1

http://stackoverflow.com/comment/88784233
score: 1
has text: If you're going to cut and paste code from github, you could at least provide attribution to the author.
comment on: http://stackoverflow.com/q/50891737
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51009254
tagged with: pandas
has body: I have a dataframe that looks like below Index Batch Name 0 1 Jon 1 2 2 Adam 3 4 3 Voges 5 6 4 Jon I want to create another dataframe from this dataframe clubbing the batch numbers Batch Name/Batches 1 Jon(1,4) 2 Adam(2) 3 Voges(3) 4 Jon(1,4) How can i do this, should i create a new list or ordereddict from the existing DF and then convert that to another DF or this can be done on the fly. UPDATE: Edited with Spaces in between them
has answer: http://stackoverflow.com/a/51009293
tagged with: python
type: AnsweredQuestion
score: 3
downvote count: 0
has title: Create Dataframe from another Dataframe
has answer: http://stackoverflow.com/a/51009311
accepted answer: http://stackoverflow.com/a/51009311
type: Question
possible better answer: http://stackoverflow.com/a/51009293
answer count: 2
favorite count: 0
upvote count: 3

http://stackoverflow.com/comment/88976318
has text: I believe you are replacing the literal letter `i` with a blank. You aren't using the variable that you called `i`, you are using the string `"i"`.
score: 2
comment on: http://stackoverflow.com/q/50990854
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88735222
has text: Side note: putting lists in dataframes is not recommended. You will lose all vectorised functionality for the series in question.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50866340

http://stackoverflow.com/comment/88937229
comment on: http://stackoverflow.com/a/50963246
type: Comment
score: 0
type: AnswerComment
has text: I don't know how to do this, but I don't want to change the letters to capital, etc. I just want the error message to stay until the address is fixed.

http://stackoverflow.com/comment/88996131
score: 0
type: Comment
has text: @beeloo Please post sample text file content in the question itself as it would be readable and would allow testing the code locally.
comment on: http://stackoverflow.com/a/51000977
type: AnswerComment

http://stackoverflow.com/comment/88773575
type: QuestionComment
has text: @PM2Ring and also if the function x is class function so if i now assign it to y can the y handle the data that is held by x or will it be a fresh copy of it
score: 0
comment on: http://stackoverflow.com/q/50885421
type: Comment

http://stackoverflow.com/q/50874618
accepted answer: http://stackoverflow.com/a/50875034
favorite count: 0
tagged with: python-3.x
tagged with: python
tagged with: normal-distribution
type: AnsweredQuestion
has body: I have a pandas DataFrame which contain probabilities of each sample belonging to each class (columns). It such happened that almost 99 % of classes have &lt; 0.01 probability and very few have &gt; 0.5 probabilities. For some reason, I want the probabilities to be distributed in Gaussian distribution between 0 and 1. I guess the mean should be 0.5 in such case, but I would also like to be able to modify the mean of such distribution if that is possible. I want this operation for each row separately, how can I do it using pandas dataframe?
score: 1
has comment: http://stackoverflow.com/comment/88750713
upvote count: 1
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/50875034
tagged with: pandas
has comment: http://stackoverflow.com/comment/88750677
downvote count: 0
answer count: 1
has title: redistribute data in Gaussian distribution with pd.DataFrame

http://stackoverflow.com/comment/88946905
comment on: http://stackoverflow.com/q/50975346
score: 2
type: Comment
type: QuestionComment
has text: Does it actually have to modify in-place? Couldn't you just return the new `board` variable, and assign it back to whatever variable held the original?

http://stackoverflow.com/q/50992705
has body: I'm trying to install gcloud on my EC2 server running Amazon Linux 4.14.47-56.37 64bits, in interactive mode running the following command : curl https://sdk.cloud.google.com | bash The files download correctly, but the install then fails with the following Traceback : File "/home/ec2-user/google-cloud-sdk/bin/bootstrapping/install.py", line 12, in &lt;module&gt; import bootstrapping File "/home/ec2-user/google-cloud-sdk/bin/bootstrapping/bootstrapping.py", line 32, in &lt;module&gt; import setup # pylint:disable=g-import-not-at-top File "/home/ec2-user/google-cloud-sdk/bin/bootstrapping/setup.py", line 55, in &lt;module&gt; from googlecloudsdk.core import properties File "/home/ec2-user/google-cloud-sdk/lib/googlecloudsdk/core/properties.py", line 291 self.__sections = {section.name: section for section in sections} ^ SyntaxError: invalid syntax Any idea why this for is causing issues? I am running python 2.7 (2.7.14) as recommended by Google.
has comment: http://stackoverflow.com/comment/88983967
upvote count: 3
has comment: http://stackoverflow.com/comment/88980631
accepted answer: http://stackoverflow.com/a/50994787
has comment: http://stackoverflow.com/comment/88984422
tagged with: gcloud
has title: Can't install gcloud on Amazon Linux : invalid syntax
favorite count: 0
tagged with: amazon-linux
has comment: http://stackoverflow.com/comment/88983964
tagged with: linux
answer count: 5
has answer: http://stackoverflow.com/a/50994787
has answer: http://stackoverflow.com/a/52337631
tagged with: python
has comment: http://stackoverflow.com/comment/88982260
score: 2
type: AnsweredQuestion
tagged with: installation
has answer: http://stackoverflow.com/a/54419633
has answer: http://stackoverflow.com/a/64321785
has answer: http://stackoverflow.com/a/61800372
downvote count: 1
type: Question
possible better answer: http://stackoverflow.com/a/52337631
has comment: http://stackoverflow.com/comment/88980408
has comment: http://stackoverflow.com/comment/88985212

http://stackoverflow.com/q/50990154
tagged with: python
has title: PLOTLY: TypeError: Object of type 'complex' is not JSON serializable
answer count: 0
tagged with: plotly
type: Question
has body: # Now plot tot = sum(eig_vals) var_exp = [(i / tot)*100 for i in sorted(eig_vals, reverse=True)] cum_var_exp = np.cumsum(var_exp) trace1 = Bar( x=['PC %s' %i for i in range(1,5)], y=var_exp, showlegend=False) trace2 = Scatter( x=['PC %s' %i for i in range(1,5)], y=cum_var_exp, name='cumulative explained variance') data = Data([trace1, trace2]) layout=Layout( yaxis=YAxis(title='Explained variance in percent'), title='Explained variance by different principal components') fig = Figure(data=data, layout=layout) #display(data) py.iplot(fig) Gives me this error: ---> 25 py.iplot(fig) TypeError: Object of type 'complex' is not JSON serializable Any help on how to fix?
has comment: http://stackoverflow.com/comment/88975810
tagged with: linear-algebra
has comment: http://stackoverflow.com/comment/88982500
score: 0
has comment: http://stackoverflow.com/comment/88975451
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/29473953

http://stackoverflow.com/comment/88835202
type: Comment
has text: What have you tried so far? If you show us your current code and what the problem is in it, we can help better. What does the expected input and output look like? It would be helpful to include an example.
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/50917535

http://stackoverflow.com/q/50923929
answer count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/88848128
has title: Extracting YYYY-MM from datetime column
upvote count: 1
downvote count: 1
has body: I've a dataframe of this format - var1 date A 2017/01/01 A 2017/01/02 ... I want the date to be converted into YYYY-MM format but the df['date'].dtype is object. How can I remove the day part from date while keeping the data type as datetime? Expected Output - A - 2017/01 Thanks
favorite count: 0
tagged with: jupyter-notebook
type: UnansweredQuestion
tagged with: datetime
tagged with: python
linked to: http://stackoverflow.com/q/38060172
type: Question
has answer: http://stackoverflow.com/a/50924566
has comment: http://stackoverflow.com/comment/88847153
tagged with: dataframe
has comment: http://stackoverflow.com/comment/88848395
has comment: http://stackoverflow.com/comment/88848418
has answer: http://stackoverflow.com/a/50924031
score: 0

http://stackoverflow.com/comment/92028029
score: 2
comment on: http://stackoverflow.com/q/50895110
has text: Did you discover anything related to your question? I'm trying to find the same answers. The 1 answer provided doesn't quite clear up my thoughts.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/88786428
comment on: http://stackoverflow.com/q/50887202
has text: I wouldn't call it an NP hard problem, the final implementation is targeted for c anyways I am using a sorting tree to sort (i.e log(n)) but since my words are 7-10 digits longs that means 13-22 comparison operation for sorting these are proving to be a bottle neck,, also I need to take advantage of the controlled collisions since rank(x,y,z) = rank(y,z,x)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50949124
tagged with: python
downvote count: 2
tagged with: openpyxl
type: Question
possible better answer: http://stackoverflow.com/a/50949725
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/36582460
score: -2
answer count: 2
accepted answer: http://stackoverflow.com/a/50949918
upvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/50949725
has title: Python openpyxl dataframe data writing in excel and clearing the sheet content
has answer: http://stackoverflow.com/a/50949918
has body: The following is the code that supports appending the data in xlsx sheet. import pandas as pd from openpyxl import load_workbook from openpyxl.utils.dataframe import dataframe_to_rows wb = load_workbook('./test.xlsx') ws = wb['Sheet1'] df = pd.DataFrame({'Data': [11, 20, 30, 20, 15, 30, 45]}) for r in dataframe_to_rows(df): ws.append(r) wb.save("test.xlsx") This is appending data everytime I run the code, also the data is placed from Row number 2; Why the excel data not starting from (0,0) cell.My requirement is to update the data from (0,0) Since append is used it is appending the data every time when the function is called.My requirement is to clean this sheet(erase the content of this sheet1 alone) and add the data frame data starting from 0,0 cells.W hat shall be the code to achieve 1 and 2 requirements. (I do not want to overwrite sheet2 and other sheet content during this operation) Any help is highly appreciated .
tagged with: pandas

http://stackoverflow.com/comment/88914131
comment on: http://stackoverflow.com/a/50958090
score: 2
type: AnswerComment
has text: You could use the original `shift` pattern instead of the diff trick, e.g. `keys = df"category", "value"; (keys != keys.shift()).any(axis=1).cumsum()`.
type: Comment

http://stackoverflow.com/comment/88999232
type: Comment
type: QuestionComment
has text: Why read it at all? How do you plan to use `PLAID_CLIENT_ID` later? Is it needed by a subprocess?
comment on: http://stackoverflow.com/q/51002694
score: 0

http://stackoverflow.com/a/50895173
type: Answer
score: 1
has body: FIXED. The issue is with the files, not Picard. Rewrapping them with ffmpeg (no need to reencode) does the trick: ffmpeg -i *.mp4 -c copy -y
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/50893018

http://stackoverflow.com/comment/88946880
score: 0
comment on: http://stackoverflow.com/a/50975149
type: AnswerComment
has text: If your answer is just "see the answer to this other equivalent question", don't write an answer, just vote to close as a dup (or flag, if you don't have enough rep for voting).
type: Comment

http://stackoverflow.com/comment/88772885
score: 0
has text: @Evgeny Pogrebnyak I don't get why common sense things like this blow over me sometimes, thanks
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50884818

http://stackoverflow.com/q/50897523
type: AnsweredQuestion
tagged with: python-2.7
tagged with: instagram
type: Question
has answer: http://stackoverflow.com/a/50897613
tagged with: python
has body: I've written a small Python program to scrape Instagram profiles to extract data and display various stats. I am able to gather data from the first 9 photos on a profile (or however many appear on initial load), but I haven't been able to load the additional photos (due to the infinite scroll mechanism). I have read online about web scraping with infinite scrolling and people have said that you need to replicate the request made to load additional images. I've been unable to replicate the request so far, is anyone able to help? Thanks!
has title: How do you mimic the infinite scroll on Instagram with Python?
score: 0
tagged with: web-scraping
answer count: 1
accepted answer: http://stackoverflow.com/a/50897613

http://stackoverflow.com/comment/88915681
comment on: http://stackoverflow.com/a/50959198
score: 0
type: AnswerComment
has text: Probably. Sets can't contain lists.
type: Comment

http://stackoverflow.com/a/50997881
has body: For simple application as this, I wouldn't link the python headers to your programm, but as a more easy solution I would trigger the system() command of C++ and process the output. Here a example from this question: #include &lt;cstdio&gt; #include &lt;iostream&gt; #include &lt;memory&gt; #include &lt;stdexcept&gt; #include &lt;string&gt; #include &lt;array&gt; std::string exec() { std::array&lt;char, 128&gt; buffer; std::string result; const char* cmd = "./python script.py"; std::shared_ptr&lt;FILE&gt; pipe(popen(cmd, "r"), pclose); if (!pipe) throw std::runtime_error("popen() failed!"); while (!feof(pipe.get())) { if (fgets(buffer.data(), 128, pipe.get()) != nullptr) result += buffer.data(); } return result; } You would then have to change the infinite loop in your python code, so that the python programm terminates and the rest of your C++ code executes, then you could probe the arduino with your python script from you C++ program.
has comment: http://stackoverflow.com/comment/88989967
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/88989876
has comment: http://stackoverflow.com/comment/88990045
has comment: http://stackoverflow.com/comment/88990311
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50997744
type: Answer
accepted answer of: http://stackoverflow.com/q/50997744

http://stackoverflow.com/a/64041087
downvote count: 0
type: Answer
has body: To Solve this, add a blank line after the first line of the Docstring. According to PEP 257 -- Docstring Conventions, a Multi-line docstring consists of a Summary line(1st line) just like a one-line docstring, followed by a blank line and then a more Elaborate description follows. It is important that the summary line fits on one line and is separated from the rest of the docstring by a blank line. def func(input): """Function that does something interesting. Args: - input - Input of the function Returns: - output - Output of the function """ data = words + sentences corpus = somefunction(data) Note The Summary line can begin on the same line as the opening quotes or on the next line, preferably, the former. There should be no blank lines after the opening quotes or before the closing quotes. Read More...
answers question: http://stackoverflow.com/q/50924700
upvote count: 5
score: 5

http://stackoverflow.com/a/50861682
answers question: http://stackoverflow.com/q/50861098
downvote count: 0
type: Answer
score: 7
upvote count: 7
has body: a way to improve my use of joblib ? joblib can help and will help, but only a code, which can benefit from distributed execution, split across some pool of resources if costs of doing so are less than an effective-speedup. Tweaking the joblib's pre-load and batch size parameters only starts to make any sense only after the to-be-distributed code gets performance polished. Some efforts on this, as demonstrated below, have shown the core-speedup of ~ 8x on achieving still pure-[SERIAL] run-times of ~ 217,000 [us] per one Random Walk ( instead of ~ 1,640,000 [us] per item, as was reported above ). Only after this there may come some harder work on Cluster-resources related optimisation ( performance devastation avoidance efforts ) for the ab-definitio postulated intention to organise a distributed work-flow of the above defined 400 repetitions thereof. That makes sense if and only if: if possible to avoid CPU-starvation, and if not having to pay any excessive add-on costs of distributed job-scheduling. Perhaps a long, but important story about where the performance gets saved or lost: Executive summary There could be hardly a better reward to Dr. Gene AMDAHL's argument. The inner structure of the above defined task is heavily [SERIAL]: random number genesis is principally a pure-[SERIAL] process, due to PRNG-design 1E6 iterator atop a 1D-vector of pre-calc'd drunken-sailor-steps is pure-[SERIAL] Yes, the "outer"-scope-of-work ( the 400 repetitions of the same process ) can be easily converted to a "just"-[CONCURRENT] ( not a true-[PARALLEL], even if professors and wannabe gurus try to tell you ) process scheduling, but the add-on costs of doing so get worse than linearly added to the run-time, and given the [SERIAL] part was not performance re-engineered, the net-effect of such efforts could easily devastate the original good intentions ( Q.E.D. above, as the posted run-times grew up, from 10:52, for K == 1, towards ~ 13 minutes for even small number of K-s ). A brief …

http://stackoverflow.com/q/50961327
has answer: http://stackoverflow.com/a/52968656
answer count: 1
tagged with: powerset
type: UnansweredQuestion
tagged with: python
has title: python - custom power set function
type: Question
has comment: http://stackoverflow.com/comment/88919472
score: 0
has body: I am trying to execute this code in python and it compiles without error. However, I do not see the variable z in the variable explorer. I am trying to create a function that gives all the subsets of an input set. import numpy as np import itertools as itt def powerset(iterable): "powerset([1,2,3]) --&gt; () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)" s = list(iterable) return itt.chain.from_iterable(itt.combinations(s, r) for r in range(len(s)+1)) def powerset_generator(i): for subset in itt.chain.from_iterable(itt.combinations(i, r) for r in range(len(i)+1)): yield set(subset) z=powerset({1,2,3})

http://stackoverflow.com/q/50895144
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/88790393
answer count: 1
has comment: http://stackoverflow.com/comment/88790323
has answer: http://stackoverflow.com/a/50895303
has comment: http://stackoverflow.com/comment/88790459
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88790416
has comment: http://stackoverflow.com/comment/88790481
tagged with: python
has title: Generating ip address by randomising last byte in each row in pandas dataframe
has body: I am taking an input of an ip address. I want to randomise the last byte between the range 0 to 254 of the ip address and print the ip address in each row of the pandas dataframe. For Example: The given input ip address is : '10.10.10.0' Expected output: &gt;&gt; 10.10.10.5 &gt;&gt; 10.10.10.173 &gt;&gt; 10.10.10.34 and so on... Here is the sample code I used : import pandas as pd import numpy as np import random from random import randint df_header="IPV4_SRC_ADDR" def func(IPV4_SRC_ADDR= "253.253.253.253", filename=None): df = pd.DataFrame(0, index=np.arange(1000), columns=df_header) #generating a dataframe with all initial values as 0 if(IPV4_SRC_ADDR!="253.253.253.253"): IPV4_SRC_ADDR = IPV4_SRC_ADDR.rsplit('.', 1)[0] df['IPV4_SRC_ADDR']=IPV4_SRC_ADDR + '.' + str(np.random.randint(0, 254, df.shape[0])) else: df['IPV4_SRC_ADDR']=IPV4_SRC_ADDR if(filename is not None): df.to_csv(filename, mode='a', header=False) else: df.to_csv('output.csv') if __name__== "__main__": generate_netflow(IPV4_SRC_ADDR="10.10.10.0") where, IPV4_SRC_ADDR is the variable and 'IPV4_SRC_ADDR' is the column name. However, my result using this code is like this: "10.10.10.[118 139 117 39 127 11 228 116 15 118 132 217 41 202 99 241 168 240]" And each column has this value. I know I am doing something wrong in str(np.random.randint(0, 254, df.shape[0])). I think the problem is when I am converting an array to string.
has comment: http://stackoverflow.com/comment/88791248
type: Question
score: 0

http://stackoverflow.com/comment/88802540
has text: if you create a dict with `False` and `True` they will not be parsed unless converted to strings "False" and "True". My file is large and I don't want to make any changes. The json is valid and can easily be loaded into a json file for further file operations(read) and then to solve this problem. I don't think that's a pressing issue.
comment on: http://stackoverflow.com/q/50900340
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/50908826
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50908455
upvote count: 2
type: Answer
has body: Try this: import re variable_refs = re.compile(r"\b(?&lt;!N)([0-9])+") exp_template = re.sub(variable_refs, r'{key_\1}', exp)

http://stackoverflow.com/a/50892944
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88832800
has comment: http://stackoverflow.com/comment/88786439
has comment: http://stackoverflow.com/comment/88786451
type: Answer
has comment: http://stackoverflow.com/comment/88830311
has comment: http://stackoverflow.com/comment/88829543
has comment: http://stackoverflow.com/comment/88835578
accepted answer of: http://stackoverflow.com/q/50891937
upvote count: 1
answers question: http://stackoverflow.com/q/50891937
has body: The link your provided does not disallow itertools, what it means is that you are not allowed to change the order of the provided numbers. That being said, you will need to use itertools.product or your own implementation of product as getting the solution requires testing all possible combinations of operators. The function find_operations returns a generator of all solutions. This allows to recover either the first solution with next or to unpack all of them. Code from itertools import product, chain from operator import add, sub, mul def apply(numbers, operations): """Return the result of applying a list of operations to the list of numbers""" ans, *numbers = numbers for num, op in zip(numbers, operations): ans = op(ans, num) return ans def find_operations(numbers): """Return the equation as string that satisfies the res % 101 == 0""" # Pair operations and their symbol to later format the result operations = {add: '+', sub: '-', mul: '*'} # Loop over all combinations of operations and break when one satisfies for ops in product(operations, repeat=len(numbers) - 1): if apply(numbers, ops) % 101 == 0: # The following lines are just formatting and are not the main focus ops = [operations[op] for op in ops] nums = [str(x) for x in numbers] yield ' '.join(chain(*zip(nums, ops), nums[-1:])) Example solutions = find_operations([22, 79, 21]) print(next(solutions)) Output 22 + 79 * 21
has comment: http://stackoverflow.com/comment/88786422
has comment: http://stackoverflow.com/comment/88786497
score: 1
has comment: http://stackoverflow.com/comment/88786455

http://stackoverflow.com/comment/88792331
type: Comment
has text: I've read about futures, and now I understand how I can do it with them. But I have a further question: in terms of scheduling/performance, what is better? Defining all tasks as futures (and using client.submit), or using delayed to define the graph? If I understand correctly, delayed is lazy, so the entire graph (with ~500 nodes) will be built before the computation, and client.submit is not lazy.
type: AnswerComment
comment on: http://stackoverflow.com/a/50881081
score: 0

http://stackoverflow.com/comment/88821129
comment on: http://stackoverflow.com/q/50910334
score: 0
type: Comment
type: QuestionComment
has text: @Dillon it means that he drived the same car two days.

http://stackoverflow.com/comment/88813865
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50905320
type: QuestionComment
has text: Can you update your question to show the code that is trying to display the cards and possibly an illustration if what is/isn't working?

http://stackoverflow.com/q/50932527
tagged with: cython
has comment: http://stackoverflow.com/comment/88864068
type: Question
accepted answer: http://stackoverflow.com/a/50933292
has comment: http://stackoverflow.com/comment/88864115
answer count: 1
downvote count: 0
tagged with: flask
favorite count: 0
has comment: http://stackoverflow.com/comment/88865256
tagged with: python
has comment: http://stackoverflow.com/comment/88864014
upvote count: 6
has title: How do you compile a flask app with cython?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50933292
has body: I have a Python flask app that I need to compile using cython. Following this guide, I can compile a simple python application, but when I do the same thing to a simple flask app: #!/usr/bin/env python2 from flask import Flask app = Flask(__name__) @app.route("/") def index(): return "hello" if __name__ == "__main__": app.run(host='0.0.0.0', port=8000) It seems to compile fine, but when I try to run it, I get this: Traceback (most recent call last): File "./run.py", line 3, in &lt;module&gt; from app import main ImportError: cannot import name main When I try to run main.py. My compile.py looks like this: #!/usr/bin/env python2 from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext ext_modules = [ Extension("app", ["app.py"]), ] setup( name = 'My Test Website', cmdclass = {'build_ext': build_ext}, ext_modules = ext_modules ) My main.py looks like this: #!/usr/bin/env python2 from app import main main() Does flask use some features that can't be compiled? Or am I doing it wrong?
score: 6

http://stackoverflow.com/comment/88760895
has text: @BramV No worries. You can try my solution. Since, your response came late, I had worked out a solution that can fit even files with different number of values. You can try.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50862015
score: 0

http://stackoverflow.com/a/50918931
has comment: http://stackoverflow.com/comment/88839180
type: Answer
has comment: http://stackoverflow.com/comment/88838593
has comment: http://stackoverflow.com/comment/88838663
upvote count: 2
has comment: http://stackoverflow.com/comment/88839120
has comment: http://stackoverflow.com/comment/88838218
has comment: http://stackoverflow.com/comment/88838904
has comment: http://stackoverflow.com/comment/88838600
accepted answer of: http://stackoverflow.com/q/50918912
has comment: http://stackoverflow.com/comment/88839174
score: 2
has comment: http://stackoverflow.com/comment/88838165
has body: You can use re.sub: import re strdirList = {'W':['WEST', 'WES', 'WE'], 'E': ['EAST', 'EA'], 'N':'NORTH', 'S':'SOUTH'} direction = 'WES EXAMPLE NORTH' new_direction = re.sub('\w+', lambda x:(lambda c:x.group() if not c else c[0])([a for a, b in strdirList.items() if x.group() in b]), direction) Output: 'W EXAMPLE N' Edit: def get_direction(direction): flag = False for i in direction.split(): if any(i in c for c in strdirList.values()) and not flag: yield [a for a, b in strdirList.items() if i in b][0] flag = True else: yield i direction = ['WES EXAMPLE NORTH', 'EXAMPLE WES NORTH', 'EXAMPLE NORTH WES'] print(list(map(lambda x:' '.join(get_direction(x)), direction))) Output: ['W EXAMPLE NORTH', 'EXAMPLE W NORTH', 'EXAMPLE N WES']
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50918912
has comment: http://stackoverflow.com/comment/88839087
has comment: http://stackoverflow.com/comment/88838183

http://stackoverflow.com/comment/88909854
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50955963
has text: @MauroBaraldi It never goes in `IF`, that's one problem
score: 0

http://stackoverflow.com/comment/88872116
has text: What processing exactly? Good chance no splitting is needed.
score: 5
comment on: http://stackoverflow.com/q/50936802
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50870823
upvote count: 8
score: 8
has answer: http://stackoverflow.com/a/71677873
type: UnansweredQuestion
tagged with: multithreading
tagged with: python
has answer: http://stackoverflow.com/a/50871035
linked to: http://stackoverflow.com/q/323972
type: Question
tagged with: testing
answer count: 2
downvote count: 0
has body: this thread discusses at great length why it is not a good idea to kill threads. And I agree when we are talking about an actual program. I am writing unit tests for several components as well as some integration tests between them. Some require threading. When tests fail, some threads stay open, locked in a .get() call of a queue. This causes the whole test suite to get stuck and not complete. I am running either ptw (pytest watch) or a custom loop of pytest with inotifywait to watch for changes in my files to rerun the suite. When all tests have completed, I want the suite to kill any remaining threads to complete the loop and not be stuck on a thread somewhere that is just open because of a test failure. Is this possible?
favorite count: 0
has title: Tearing down any open Threads after completing all Python Unittests

http://stackoverflow.com/a/50953654
accepted answer of: http://stackoverflow.com/q/50951632
score: 3
answers question: http://stackoverflow.com/q/50951632
type: Answer
upvote count: 3
has body: Given CoAP's nature of working both as a server and a client, an aiocoap Context is prepared to react to packages even when no request is currently active, and persists until it gets shut down using the .shutdown() coroutine. Depending on the platform, that often means creation of at least a server socket per context, which can lead to file descriptor exhaustion when too many are created. With very few exceptions, there is no reason why an application should ever create more than one context. As this appears to be a common misunderstanding, the documentation is being updated to make this point more explicit.
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/50961081
has comment: http://stackoverflow.com/comment/88919254
has title: if statement within for loop running time
type: Question
has comment: http://stackoverflow.com/comment/88919329
downvote count: 0
has comment: http://stackoverflow.com/comment/88919156
answer count: 1
score: 1
has answer: http://stackoverflow.com/a/50961371
favorite count: 0
has comment: http://stackoverflow.com/comment/88919150
tagged with: big-o
has comment: http://stackoverflow.com/comment/88919148
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88919408
has body: I have a for loop iterating through a list with n elements, and within the list, I have an if statement, like so: for item in list: if item == match: item = 'found' My teacher says that this code is in ϴ(1). How is it not ϴ(n)? The loop is forced to iterate through n elements, why is the code in ϴ(1)? Is it perhaps an error on my teacher's part?
tagged with: asymptotic-complexity
upvote count: 1
has comment: http://stackoverflow.com/comment/88919062

http://stackoverflow.com/a/50900488
type: Answer
has comment: http://stackoverflow.com/comment/88901722
accepted answer of: http://stackoverflow.com/q/50899707
has comment: http://stackoverflow.com/comment/88909903
answers question: http://stackoverflow.com/q/50899707
has comment: http://stackoverflow.com/comment/88802053
score: 0
has comment: http://stackoverflow.com/comment/88909958
has comment: http://stackoverflow.com/comment/88882426
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88908777
has comment: http://stackoverflow.com/comment/88875457
has body: Demo: parse URL into a DF: In [263]: df = pd.read_html(url, header=1)[11] show problematic columns: In [264]: df[df.columns[df.columns.str.contains('%')]] Out[264]: BB% K% 0 18.5 % 19.2 % 1 12.8 % 11.5 % 2 11.0 % 13.1 % 3 8.7 % 18.3 % 4 13.5 % 16.0 % .. ... ... 26 7.0 % 20.2 % 27 13.5 % 12.5 % 28 9.4 % 16.1 % 29 8.6 % 21.5 % 30 NaN NaN [31 rows x 2 columns] converting them to numeric columns: In [265]: df[df.columns[df.columns.str.contains('%')]] = \ (df.filter(regex='%') .apply(lambda x: pd.to_numeric(x.str.replace(r'[\s%]',''), errors='coerce'))) result: In [266]: df[df.columns[df.columns.str.contains('%')]] Out[266]: BB% K% 0 18.5 19.2 1 12.8 11.5 2 11.0 13.1 3 8.7 18.3 4 13.5 16.0 .. ... ... 26 7.0 20.2 27 13.5 12.5 28 9.4 16.1 29 8.6 21.5 30 NaN NaN [31 rows x 2 columns] In [267]: df[df.columns[df.columns.str.contains('%')]].dtypes Out[267]: BB% float64 K% float64 dtype: object

http://stackoverflow.com/comment/88765563
has text: you are right. this is bit annoying but it works. thanks
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50881356

set-difference
tags question: http://stackoverflow.com/q/50871370
type: Tag
tags question: http://stackoverflow.com/q/50942619
tag name: set-difference

http://stackoverflow.com/a/50949335
upvote count: 4
downvote count: 0
has body: You can do something like this. UPDATED: df = pd.read_csv("your_csv_file") '''df = pd.DataFrame({'Used CPU':['1','0','2','2','0','51550m'], \ 'Used Memory':['4Gi','0','4Gi','4Gi','0', '39528Mi'], \ 'Hard CPU':['50','0','4','4','100m','56'], \ 'Hard Memory':['24Gi','0','8Gi', '8Gi', '128Mi', '47Gi']})''' units = {'m':0.001,'Mi':0.00104858,'Gi':1.0737425} def conversion(x): for key in units.keys(): if key in str(x): x = x.split(key)[0] x = (int(x)*units[key]) return x return str(x) df = df.applymap(conversion) df = df.apply(lambda x: x.astype(np.float64), axis=1) print(df) INPUT: Hard CPU Hard Memory Used CPU Used Memory 0 50 24Gi 1 4Gi 1 0 0 0 0 2 4 8Gi 2 4Gi 3 4 8Gi 2 4Gi 4 100m 128Mi 0 0 5 56 47Gi 51550m 39528Mi OUTPUT: Hard CPU Hard Memory Used CPU Used Memory 0 50.0 25.76980 1.00 4.29497 1 0.0 0.000000 0.00 0.00000 2 4.0 8.589940 2.00 4.29497 3 4.0 8.589940 2.00 4.29497 4 0.1 0.134218 0.00 0.00000 5 56.0 50.465898 51.55 41.44827 They are in Float64. Now you can use df['Hard Memory'] + df['Used Memory']
has comment: http://stackoverflow.com/comment/88898336
score: 4
has comment: http://stackoverflow.com/comment/88897149
has comment: http://stackoverflow.com/comment/88898548
has comment: http://stackoverflow.com/comment/88897371
answers question: http://stackoverflow.com/q/50947447
has comment: http://stackoverflow.com/comment/88896199
type: Answer

http://stackoverflow.com/comment/89046608
has text: Thanks , the solution worked like a charm and helped me a lot
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51011418

http://stackoverflow.com/q/50880762
has answer: http://stackoverflow.com/a/50880787
upvote count: 0
tagged with: list
has comment: http://stackoverflow.com/comment/88763881
type: UnansweredQuestion
has title: How to remove characters from each element in a list
has comment: http://stackoverflow.com/comment/88763772
type: Question
has answer: http://stackoverflow.com/a/50880879
has answer: http://stackoverflow.com/a/50880859
score: -2
linked to: http://stackoverflow.com/q/41664806
has answer: http://stackoverflow.com/a/50880800
downvote count: 2
favorite count: 0
has comment: http://stackoverflow.com/comment/88764560
has body: I would like to remove the first two characters from each element (which are currently ints) that i have in a list. This is what i have: lst = [2011,2012,3013] I would like to get this lst= [11,12,13] I do not want a solution with some sort of replace 20 or 30 with '' however.
has comment: http://stackoverflow.com/comment/88763811
tagged with: python
answer count: 4

http://stackoverflow.com/comment/88802073
type: QuestionComment
has text: What is the point of `f_new =open ('data_out.c','w')`?
comment on: http://stackoverflow.com/q/50901034
type: Comment
score: 0

http://stackoverflow.com/comment/88866398
score: 1
has text: This would be so much easier if you didn't have apostrophes inside your inner strings. Also, what have you tried?
comment on: http://stackoverflow.com/q/50933895
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52066446
downvote count: 0
has body: Run: sudo apt-get install python-2.7 You might have to reinstall any extra packages you installed from pip
type: Answer
upvote count: 3
score: 3
answers question: http://stackoverflow.com/q/50935439

http://stackoverflow.com/comment/89149059
has text: Also add output of `print(serializer.errors)` . (add that print() after `validation = serializer.is_valid()` this statement)
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50924550

http://stackoverflow.com/comment/88848407
has text: you might wanna override some function inside the allauth.account.views.SignupView, as in the above code you are overriding some signal which is sent/called after the user has been signed up successfully.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50924482
score: 0

http://stackoverflow.com/comment/88721418
comment on: http://stackoverflow.com/a/50859340
type: Comment
has text: No, this BlinkerLabel will blink constantly, every 3500 milliseconds.
score: 1
type: AnswerComment

http://stackoverflow.com/comment/88835400
type: Comment
has text: What do you mean by running between requests? That it hooks into random requests and adding more data [to the response](https://docs.djangoproject.com/en/2.0/topics/http/middleware/)? Or [scheduled tasks](https://medium.com/@bencleary/django-scheduled-tasks-queues-part-1-62d6b6dc24f8)?
comment on: http://stackoverflow.com/q/50917614
score: 0
type: QuestionComment

http://stackoverflow.com/q/50930889
tagged with: matplotlib
score: 0
has title: How to plot paired data with different colors considering their labels
answer count: 1
tagged with: scatter
tagged with: colors
has body: I have two lists, the first one is a list of paired data (data contains 76 pairs) and the second one is the corresponding label (label contains 76 numbers between 0 to 11).I need 11 different colors. I need to plot each of these paired data with a specific color considering its label. The two lists are like these: data=[[2,6],[1,7],[3,8],[4,6],[7,9]] labels=[1,0,0,2,2] I'm beginner to python. any help would be appreciated
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50931104
tagged with: plot
type: Question

http://stackoverflow.com/comment/88982344
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/50993566
has text: I'm on Mac OS X, latest version, and I'm using a Python 3.6 installed via Homebrew that definitely has pip. I can even access pip from inside the terminal I can spin up inside VSCode. I was able to update my User Settings to get it to work: ``` "python.formatting.autopep8Path": "/usr/local/bin/autopep8", "python.linting.pylintPath": "/usr/local/bin/pylint" } ``` but I'm not a huge fan of that...

http://stackoverflow.com/a/50931688
upvote count: 2
type: Answer
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50931448
has body: I assume you are talking about class-based views. In that case, if you do not change the routing mechanism, the answer is yes. Let us look at the source code of the View class [GitHub]. Usually class-based views subclass from this class, and thus inherit the behavior of this class: class View: # ... http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace'] # ... @classonlymethod def as_view(cls, **initkwargs): # ... def view(request, *args, **kwargs): self = cls(**initkwargs) if hasattr(self, 'get') and not hasattr(self, 'head'): self.head = self.get self.request = request self.args = args self.kwargs = kwargs return self.dispatch(request, *args, **kwargs) # ... return view def dispatch(self, request, *args, **kwargs): # ... if request.method.lower() in self.http_method_names: handler = getattr(self, request.method.lower(), self.http_method_not_allowed) else: handler = self.http_method_not_allowed return handler(request, *args, **kwargs) # ... I here stripped away parts that are more or less irrelevant, and fixed the formatting a bit to make it more convenient to read. As you can see, if you call the as_view() function (when you declare a url(..) or path(..), then it basically constructs a function def view(..) that, and a reference to that function is linked with this URL. Now the view(..) function, performs some operations (for example if the head (...) function is not implemented, it will later fallback on the get (..) function. The most important part is however that it calls the self.dispatch(..) function. This dispatch function looks to the request.method. It converts this method to a lowercase variant, and then checks if that method is declared in the view. If it is, it will call the corresponding method (so in case request.method == 'POST', it will call post (...) with request, *args, and **kwargs), and if the method is missing, it will basically return a "HTTP method not allowed response". Note however that you can subclass t…

http://stackoverflow.com/q/50877776
type: Question
has answer: http://stackoverflow.com/a/50878210
has body: I have below String. a = "/root/LOAD/LOGS/2018-06-15_13:54/" How can I get the output: "/root/LOAD/LOGS/"
answer count: 3
has title: How to strip pattern in the string?
tagged with: string
favorite count: 0
type: UnansweredQuestion
downvote count: 2
has answer: http://stackoverflow.com/a/50877975
tagged with: python
upvote count: 3
score: 1
has answer: http://stackoverflow.com/a/50877814

http://stackoverflow.com/comment/106488148
type: Comment
type: QuestionComment
has text: Agreed, not a duplicate. I believe it can be solved with something like that: `import pkg_resources; pkg_resources.get_distribution('requests').get_metadata('INSTALLER')`.
comment on: http://stackoverflow.com/q/50872490
score: 0

http://stackoverflow.com/comment/88804512
comment on: http://stackoverflow.com/q/50901109
has text: @RenatoByrro yeah, of course. That's how I know to do the try/except in the first place. This is the exception: AttributeError Traceback (most recent call last) <ipython-input-2-26b8e7fa2688> in <module>() ----> 1 my_package.m1 AttributeError: module 'my_package' has no attribute 'm1'
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/a/50976931
has body: Based on the fact that you pass an array and I guess you want this: q = np.arange(0,mt.pi,0.01) q = q.tolist() def qprime(q,qc): for x in q: if x &lt; qc: a = cmt.sqrt(x**2-qc**2) yield a.real else: yield cmt.sqrt(x**2-qc**2) qp = [v for v in qprime(q, 0.8509)]
answers question: http://stackoverflow.com/q/50976855
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/88949875

http://stackoverflow.com/q/50891514
tagged with: import
type: Question
type: AnsweredQuestion
has body: I made a class in a single file and it looks like below: class Robot(): def __init__(self, name, desc, color, owner): # initializes our robot self.name = name self.desc = desc self.color = color self.owner = owner def drive_forward(self): #simulates driving forward print(self.name.title() + " is driving" + " forward " + str(self.duration)+ " milliseconds") def drive_backwards(self): print(self.name.title() + " is driving" + " backwards " + str(self.duration) + " milliseconds") def turn_left(self): print(self.name.title() + " is turning " + " left " + str(self.duration) + " milliseconds") def turn_right(self): print(self.name.title() + " is turning " + " right " + str(self.duration) + " milliseconds") and I was trying to import this file to another file, so I can instantiate it and see how OOP works like. And the other file that I was trying to import the class and instantiate looks like below: from robot_sample_class import Robot my_robot = Robot("Nomad", "Autonomous rover", "Black", "JAY") print("My robot is a " + my_robot.desc + " called " + my_robot.name) my_robot.drive_forward() my_robot.drive_backwards() my_robot.turn_left() my_robot.turn_right() This code works well on the Python Shell; however, if I just write import "robot_sample_class" alone rather than "from robot_sample_class import Robot" It doesn't work and it spits out an error message such as: my_robot = Robot("Nomad", "Autonomous rover", "Black", "JAY") NameError: name 'Robot' is not defined Why is this the case? I thought importing the entire file will allow me to access everything in that file?
tagged with: class
score: 0
answer count: 1
has title: Why does "from file import class work", and not "import file"?
tagged with: python
has answer: http://stackoverflow.com/a/50891532
accepted answer: http://stackoverflow.com/a/50891532

http://stackoverflow.com/comment/88803211
type: Comment
has text: Got it, in fact we have already consume the SI when it throws the exception, so to remove it we need remove it from the end. Great explantation!
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/50901610

http://stackoverflow.com/q/50895256
has body: I have a set up where a controller (or the experiment file, which is a Python file) invokes two different Python scripts repeatedly. Let us call the controller C, the two scripts A and B. A provides the logic and B is the simulator. Each time the controller invokes A, I need to create a gameObject. previous code for A: # global object gameObject = Game() # dummy initialization to make the object "known" class A(object): def __init__(self, **parameters): # rest of the code def method_start(self): # invoked at the start of each "run" global gameObject gameObject = Game() # reinitialize the object for the current run # some code # other methods related to the logic def method_end(self): global gameObject del gameObject # destroy the object at the end of this run Objective: I now want to make gameObject a part of the class A. So I made the following changes. Current code for A: class A(object): def __init__(self, **parameters): self.gameObject = Game() # no more global object # rest of the code def method_start(self): # invoked at the start of each "run" self. gameObject = Game() # reinitialize the object for the current run # some code # other methods related to the logic def method_end(self): del self.gameObject # destroy the object at the end of this run After the change above, at the end of the first "run", the gameObject is deleted and I end up with the following error in method_start(): AttributeError: 'A' object has no attribute 'gameObject' The workaround I have for now is to make self.gameObject = None in method_end(). However, there seems to be a steady increase in the memory consumption after every run due to this change. How to achieve my objective without a memory leak? === Edit 1: Added sample code === Edit 2: Deleted sample code I realized within the setup I gave here, the issue doesn't surface! My actual setup has a protocol server running in between A, B, and C through which the communication happens. Both A and B are separate processes and C controls t…
has comment: http://stackoverflow.com/comment/88790906
score: 0
has comment: http://stackoverflow.com/comment/88790702
tagged with: initialization
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/88791084
answer count: 0
has comment: http://stackoverflow.com/comment/88790863
has comment: http://stackoverflow.com/comment/88790836
has title: Python reinitialize object
downvote count: 1
type: Question

http://stackoverflow.com/comment/88817199
type: Comment
type: QuestionComment
has text: another thing, your image looks pixelated but each little square/rectangle actually contains multiple pixels, it that desired? I mean the image you posted has got the proper shape or has it been rescaled by mistake?
comment on: http://stackoverflow.com/q/50907540
score: 0

http://stackoverflow.com/q/50902846
tagged with: django
tagged with: python
linked to: http://stackoverflow.com/q/44203397
downvote count: 0
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/88858036
type: Question
has comment: http://stackoverflow.com/comment/88805461
tagged with: python-2.7
has title: I am not getting data in proper language of html by request package
tagged with: django-1.8
upvote count: 1
has comment: http://stackoverflow.com/comment/88805462
has comment: http://stackoverflow.com/comment/88805483
has comment: http://stackoverflow.com/comment/88857839
favorite count: 0
has comment: http://stackoverflow.com/comment/88857691
has body: I am trying to scrape a Japanese website (a trimmed down sample below): 不審者の出没 I am trying to get data of this html by request package using: response = requests.get(url) I am getting data from h3 field in as: '¡ÊÂçÊ¬' and unicode value of it is like this: '\xa4\xaa\xa4\xaa\xa4\xa4\xa4\xbf\' but when I load this html from a file or from a local wsgi server (tried with Django to serve a static html page) then I get: 不審者の出没. It's actual data. Now I am not understanding how to resolve this issue?
type: UnansweredQuestion

multiclass-classification
tags question: http://stackoverflow.com/q/50920908
tags question: http://stackoverflow.com/q/50941223
tag name: multiclass-classification
tags question: http://stackoverflow.com/q/51004261
type: Tag

http://stackoverflow.com/a/50992745
has body: Your question seems to indicate that there is anything wrong here. This is not the case. As per the Python database specification, a concrete database library is free to use one of several placeholders for the parameters of a (real or pseudo) prepared statement. Normally, the choice is made with respect to the most simple way to solve the task. Libraries which use real prepared statements can use the ? placeholders. This allows them to pass the statement directly to the prepared statement engine of the interface, because these usually use ? for the data to be placed into the query. Other libraries, such as MySQLdb, don't use prepared statements, but another (more or less) safe method to create the queries resp. to embed the data into the statements. In this case, %s (and only %s and no other patterns) can be used. In these cases, the library transforms the given data into an appropriate replacement: strings are enclosed in ' characters and the content is treated appropriately, as would the C function mysql_real_escape_string() would do. Other data are transformed differently, such as numbers which are transformed into their respective string representation. In all cases, strings are created out of these data and then inserted into the queries. That's why %s is used and nothing else (like %f, %d etc.).
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/88980278
accepted answer of: http://stackoverflow.com/q/50992334
answers question: http://stackoverflow.com/q/50992334
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89018967
has comment: http://stackoverflow.com/comment/88984642
type: AcceptedAnswer

http://stackoverflow.com/a/50884059
answers question: http://stackoverflow.com/q/50883192
score: 2
has comment: http://stackoverflow.com/comment/88770354
upvote count: 2
has comment: http://stackoverflow.com/comment/88770366
has comment: http://stackoverflow.com/comment/88770497
accepted answer of: http://stackoverflow.com/q/50883192
has body: The abstract behind what you want to accomplish is finding connected components in a graph of servers and states. We can implement a solution converting your dict to a graph, finding connected components and converting back to the desired format. First, let's define the helper functions that will allow us to treat my_dict as a graph. def get_cluster(x_to_y, y_to_x, x): # Implement a breadth-first search to recover all servers connected to x queue = [x] cluster = set() while queue: current = queue.pop() if current not in cluster: queue.extend({i for y in x_to_y[current] for i in y_to_x[y]}) cluster.add(current) return cluster def get_connected_parts(x_to_y): # We were provided a server -&gt; state representation of the graph # For efficiency, we will generate a state -&gt; server dict of edges y_to_x = {} for server, states in x_to_y.items(): for state in states: if state in y_to_x: y_to_x[state].add(server) else: y_to_x[state] = {server} # We now iterate over our servers and recover their clusters seen = set() clusters = [] for x in x_to_y: if x not in seen: cluster = get_cluster(x_to_y, y_to_x, x) seen |= cluster clusters.append(cluster) return clusters Most of the job has now been done, the function get_connected_parts can be used to retrieve sets of connected servers. All that remains is to format the data. But first, let's have a look at its output. my_dict = { 'server_name1': ['utah', 'california', 'idaho', 'texas'], 'server_name2': ['new york'], 'server_name3': ['idaho', 'new york', 'texas'], 'server_name4': ['florida'], 'server_name5': ['utah', 'california']} groups = get_connected_parts(my_dict) print(groups) Output: [{'server_name2', 'server_name1', 'server_name3', 'server_name5'}, {'server_name4'}] Note that it does not make much sense to have keys look like 'server1, server2, server3, server5', because that would require that the user knows which servers are connected whenever trying to access a key. Instead, we are going to output a new_dict which keys a…
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88770343
type: Answer
has comment: http://stackoverflow.com/comment/88770342

http://stackoverflow.com/comment/99173313
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50874914
has text: had wrap the first argument to concatenate in square brackets for this to work for me

http://stackoverflow.com/q/50900279
upvote count: 1
has comment: http://stackoverflow.com/comment/88800985
tagged with: distutils
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88800668
tagged with: python
has answer: http://stackoverflow.com/a/50900363
accepted answer: http://stackoverflow.com/a/50900363
has title: Extending Python with C Error: Segmentation Fault: 11 in Python [MacOS X]
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/88800774
has comment: http://stackoverflow.com/comment/88800579
has comment: http://stackoverflow.com/comment/88800508
type: Question
has comment: http://stackoverflow.com/comment/88800687
score: 1
has body: I have written an extension module in C with the name extmodule.c and the code for it is as follows: #include &lt;Python.h&gt; //Define a new exception object for our module static PyObject *extError; static PyObject* ext_cpu(PyObject* self, PyObject *args) { int pid; int sts=0; //We expect at least 1 argument to this function if(!PyArg_ParseTuple(args, "i", &amp;pid)) { return NULL; } printf("Hello, from C World! Pid: %i", pid); sts=pid; return Py_BuildValue("i", sts); } static PyMethodDef ext_methods[] = { //PythonName, C-FunctionName, argument_presentation, description {"cpu", ext_cpu, METH_VARARGS, "Print cpu consumption of a particular process with pid"} }; PyMODINIT_FUNC PyInit_ext(void) { PyObject *m; m = PyModule_Create(&amp;ext_methods); if (m == NULL) return NULL; extError = PyErr_NewException("spam.error", NULL, NULL); Py_INCREF(extError); PyModule_AddObject(m, "error", extError); return m; } After that I have created a setup.py to build and install the extension file in my python program and the code for the setup.py is as follows: from distutils.core import setup, Extension module1 = Extension('ext', include_dirs = ['/usr/local/include'], libraries = ['pthread'], sources = ['extmodule.c']) setup (name = 'ext', version = '1.0', description = 'This is a C extension for Python program', author = 'Somdip Dey', url = '', ext_modules = [module1]) Now on the command prompt I have built the setup.py using the following commands: &gt;&gt; python setup.py build running build running build_ext building 'ext' extension gcc -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I/Users/somdipdey/ anaconda3/include -arch x86_64 -I/Users/somdipdey/anaconda3/include -arch x86_64 -I/usr/local/include -I/Users/somdipdey/anaco nda3/include/python3.6m -c extmodule.c -o build/temp.macosx-10.7-x86_64-3.6/extmodule.o extmodule.c:34:25: warning: incompatible pointer types passing 'PyMethodDef (*)[1]' to parameter of type 'struct…

http://stackoverflow.com/q/50979589
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/31511997
score: 3
upvote count: 3
has title: KeyError in Python Pandas dataframe using .loc
type: Question
has body: I dont understand why I am receiving this error. KeyError: u'the label [ContractType] is not in the [index]' I have a simple csv file that is passed in by: df = pd.read_csv(filename, encoding="utf-8") My goal is to replace, empty cells in a column with another text, but whenever I try to use the .loc method i receive a key error. df = df.astype(object).where(df.loc['ContractType'] == "not available","non-specified") Resource: Similar solution What generates the error df.loc['ContractType'] Verifying that it is a valid key I have verified that the key is a valid key by using this code: for column in df.columns: print type(column),column print type('Id'),type(u'Id'),type(unicode('Id')),type('Id'.encode('utf-8')) df.keys() Output: &lt;type 'unicode'&gt; Id &lt;type 'unicode'&gt; xxx &lt;type 'unicode'&gt; xxx &lt;type 'unicode'&gt; ContractType &lt;type 'unicode'&gt; xxx &lt;type 'unicode'&gt; xxx &lt;type 'unicode'&gt; xxx &lt;type 'unicode'&gt; xxx &lt;type 'unicode'&gt; xxx &lt;type 'unicode'&gt; xxx &lt;type 'unicode'&gt; xxx &lt;type 'str'&gt; &lt;type 'unicode'&gt; &lt;type 'unicode'&gt; &lt;type 'str'&gt; Index([u'Id', u'xxx', u'xxx', u'ContractType', u'xxx', u'xxx', u'xxx', u'xxx', u'xxx', u'xxx', u'xxx'], dtype='object') I have even tried: print df.loc[df.keys()[3]] I don't know why I am getting this error, even when it is a valid key? Error Output KeyErrorTraceback (most recent call last) &lt;ipython-input-72-c852bdc72c73&gt; in &lt;module&gt;() 4 print type('Id'),type(u'Id'),type(unicode('Id')),type('Id'.encode('utf- 8')) 5 df.keys() ----&gt; 6 df.loc['ContractType'] 7 #print df.loc[df.keys()[3]] 8 #print df == "not available" C:\Users\xxx\AppData\Local\Continuum\anaconda2\lib\site- packages\pandas\core\indexing.pyc in __getitem__(self, key) 1371 1372 maybe_callable = com._apply_if_callable(key, self.obj) -&gt; 1373 return self._getitem_axis(maybe_callable, axis=axis) 1374 1375 def _is_scalar_access(self, key): C:\Users\xxx\AppData\Local\Continuum\anaconda2\…
downvote count: 0
has comment: http://stackoverflow.com/comment/88955206
tagged with: pandas
has comment: http://stackoverflow.com/comment/100443861
favorite count: 0
answer count: 0

http://stackoverflow.com/comment/88735551
has text: Have you run it on a development server?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50866421

http://stackoverflow.com/a/53914878
score: 2
answers question: http://stackoverflow.com/q/51010770
upvote count: 2
downvote count: 0
has body: Maybe quite late to the party but here's what I believe is the exact answer: # create pivot male_ratio = users.pivot_table(index='occupation', columns='gender', aggfunc='size', fill_value=0) # calculate male ratio sums = male_ratio'F', 'M'.sum(axis=1) male_ratio['MaleRatio'] = round(100 * male_ratio['M'] / sums , 1) # result male_ratio['MaleRatio'] occupation administrator 54.4 artist 53.6 doctor 100.0 educator 72.6 engineer 97.0 entertainment 88.9 executive 90.6 healthcare 31.2 homemaker 14.3 lawyer 83.3 librarian 43.1 marketing 61.5 none 55.6 other 65.7 programmer 90.9 retired 92.9 salesman 75.0 scientist 90.3 student 69.4 technician 96.3 writer 57.8 Name: MaleRatio, dtype: float64
type: Answer

http://stackoverflow.com/comment/89394421
score: 0
comment on: http://stackoverflow.com/a/50975188
type: Comment
has text: I don't know how I can post an example here if the file is so large (the question would become very long), but consider replacing all three occasions of "`*data*`" with, say, 20 MB worth of actual data – I presume it doesn't matter what data you enter here as long as the XML parser sees it as text – and you have the type of file I'm dealing with.
type: AnswerComment

http://stackoverflow.com/comment/89563842
has text: You can install tensorflow from the source to make it work with cuda 9.2.
score: 1
comment on: http://stackoverflow.com/q/51007380
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50968008
favorite count: 0
has body: I want to develop strategies for Bitmex. To do some testing I would like to have vectors of the OHCL and VOLUME vectors separately. I implemented the following code: import json from urllib.request import urlopen url1 = 'https://www.bitmex.com/api/v1/trade/bucketed?binSize=1h&amp;partial=false&amp;symbol=XBT&amp;count=150&amp;start=' url2 = '&amp;reverse=true' ohcl = url1 + '0' + url2 u = urlopen(ohcl) data = json.loads(u) print(type(data)) Unfortunately the data is stored as a list, I am unable to reference it like a dict (e.g. data[high]) . It is a hodgepodge of strings and numbers. Fields are not defined. How do I access the fields and/or convert them to separate vectors?
upvote count: 2
has answer: http://stackoverflow.com/a/50968720
tagged with: python
tagged with: dictionary
answer count: 1
tagged with: http://stackoverflow.com/tag/json
accepted answer: http://stackoverflow.com/a/50968720
score: 2
tagged with: api
has comment: http://stackoverflow.com/comment/88933872
has title: Reading price chart from Bitmex API json conversion issue
downvote count: 0
type: Question
type: AnsweredQuestion

http://stackoverflow.com/q/50913431
tagged with: module
accepted answer: http://stackoverflow.com/a/50913647
type: AnsweredQuestion
has title: Import module error but tree seems correct
has answer: http://stackoverflow.com/a/50913513
tagged with: import
type: Question
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/50913513
has answer: http://stackoverflow.com/a/50913647
has body: cambridge_loader ├── CambridgeLoader.py ├── CambridgeSample.csv ├── __init__.py ├── __main__.py I'm trying to run the __main__.py script but it seems to be running through some errors importing my class. Inside __main__.py I'm importing my class like this: from cambridge_loader.CambridgeLoader import CambridgeLoader and CambridgeLoader.py has a class called CambridgeLoader: class CambridgeLoader(object): """Parses an incoming Cambridge Benchmark CSV file and transforms/adds a few fields so that it can be consumed by RAP. """ When trying to run my __main__.py script and pass it a file to parse, I get the following error: from cambridge_loader.CambridgeLoader import CambridgeLoader ImportError: No module named 'cambridge_loader' Is the import of the module incorrect?
tagged with: python

http://stackoverflow.com/q/50992193
favorite count: 0
has answer: http://stackoverflow.com/a/50993341
tagged with: python
has comment: http://stackoverflow.com/comment/88979213
type: AnsweredQuestion
score: 3
upvote count: 3
linked to: http://stackoverflow.com/q/45964740
has comment: http://stackoverflow.com/comment/88979134
has title: Pandas dataframe forward-fill with decay
type: Question
has body: I am running Python 3.5, and Pandas v 0.19.2. I have a dataframe like below. Forward-filling the missing values is straight-forward. import pandas as pd import numpy as np d = {'A': np.array([10, np.nan, np.nan, -3, np.nan, 4, np.nan, 0]), 'B': np.array([np.nan, np.nan, 5, -3, np.nan, np.nan, 0, np.nan ])} df = pd.DataFrame(d) df_filled = df.fillna(axis='index', method='ffill') print(df_filled) Out[8]: A B 0 10.0 NaN 1 10.0 NaN 2 10.0 5.0 3 -3.0 -3.0 4 -3.0 -3.0 5 4.0 -3.0 6 4.0 0.0 7 0.0 0.0 My question is: what is the best way to implement a forward fill with decay? I understand the pd.ffill() and pd.fillna() do not support this. For instance, the output I am after is the below (in contrast with the regular ffill above), where the value carried over halves at each period: Out[5]: A B 0 10.0 NaN 1 5.0 NaN 2 2.5 5.0 3 -3.0 -3.0 4 -1.5 -1.5 5 4.0 -0.75 6 2.0 0.0 7 0.0 0.0
has answer: http://stackoverflow.com/a/50992422
accepted answer: http://stackoverflow.com/a/50992422
tagged with: missing-data
possible better answer: http://stackoverflow.com/a/50993341
tagged with: fillna
answer count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/88982222
downvote count: 0

http://stackoverflow.com/comment/89002029
type: Comment
comment on: http://stackoverflow.com/a/50995920
score: 0
type: AnswerComment
has text: Fantastic! It works perfectly, thank you. I realised I made a stupid mistake when copying your code the first time.

http://stackoverflow.com/a/50864479
answers question: http://stackoverflow.com/q/50864196
has comment: http://stackoverflow.com/comment/88764184
score: 5
type: AcceptedAnswer
has body: The best way would be to avoid using udf and use pyspark.sql.Column.rlike(). This will return True if the column matches the regular expression contained within the argument. In this case, you can use "|".join(list_of_terms) to create a regex pattern that will match any word in the list. ("|" is the OR operator) from pyspark.sql.functions import col, when df.select( "*", when(col("con").rlike("|".join(phone_list)), "phones").alias("cat"), when(col("con").rlike("|".join(pc_list)), "pc").alias("abc") ).show(truncate=False) #+---+---------------------+------+----+ #|id |con |cat |abc | #+---+---------------------+------+----+ #|3 |mac,mac pro |null |pc | #|1 |iphone5,iphone |phones|null| #|1 |android,android phone|phones|null| #|1 |windows,windows pc |null |pc | #|1 |spy camera,spy camera|null |null| #|2 |camera, |null |null| #|3 |cctv,cctv |null |null| #|2 |apple iphone,iphone |phones|null| #|3 |,spy camera |null |null| #+---+---------------------+------+----+ We're also using the fact that pyspark.sql.functions.when() will return null if no otherwise() condition is specified.
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/88763687
has comment: http://stackoverflow.com/comment/88732833
accepted answer of: http://stackoverflow.com/q/50864196
downvote count: 0

http://stackoverflow.com/comment/88847441
has text: Then use `res = res.drop_duplicates(subset=['Date'])` ? If this doesn't work, please ask as a [separate question](https://stackoverflow.com/questions/ask).
type: Comment
comment on: http://stackoverflow.com/a/50911946
type: AnswerComment
score: 0

timer
tag name: timer
tags question: http://stackoverflow.com/q/50945463
type: Tag

http://stackoverflow.com/q/50932217
type: Question
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/50932272
favorite count: 0
has body: I have a large data with 12 columns. Where MatchId is duplicated. df1.columns Out[569]: Index(['MatchId', 'Event_Id', 'EventCode', 'Team1', 'Team2', 'Team1_Goals', 'Team2_Goals', 'xG_Team1', 'xG_Team2', 'CurrentPlaytime', 'Home_Goal_Time', 'Away_Goal_Time'], dtype='object') For the condition, df1.loc[df1.Home_Goal_Time &gt;= 200, 'MatchId'], I want all the MatchId associated with this condition to be removed from df1.
tagged with: python
possible better answer: http://stackoverflow.com/a/50933952
has comment: http://stackoverflow.com/comment/88863230
has answer: http://stackoverflow.com/a/50933952
has comment: http://stackoverflow.com/comment/88864247
accepted answer: http://stackoverflow.com/a/50932272
upvote count: 1
type: AnsweredQuestion
score: 1
tagged with: dataframe
has title: How to remove a selected rows from dataframe under a condition

http://stackoverflow.com/q/50966593
favorite count: 0
tagged with: binary
has answer: http://stackoverflow.com/a/50966964
tagged with: python
type: AnsweredQuestion
score: 1
tagged with: predict
upvote count: 1
type: Question
tagged with: statsmodels
has body: I fitted a logistic model using statsmodel as below: import statsmodels.api as sm logit = sm.Logit(train1['resp'], train1[v]) result = logit.fit() result.summary() ================================================================================================= coef std err z P&gt;|z| [0.025 0.975] ------------------------------------------------------------------------------------------------- AGEINQ -0.0420 0.015 -2.782 0.005 -0.072 -0.012 BKROPN12 0.1048 0.067 1.572 0.116 -0.026 0.236 SCRG001 -0.1600 0.128 -1.251 0.211 -0.411 0.091 BKRATTH 0.0037 0.002 1.947 0.051 -2.42e-05 0.007 HET1001_HE -0.5102 0.178 -2.866 0.004 -0.859 -0.161 SCRS009 0.0167 0.010 1.614 0.107 -0.004 0.037 SCRPF33 -2.874e-06 7.5e-07 -3.834 0.000 -4.34e-06 -1.4e-06 CINS99 -0.0017 0.001 -2.872 0.004 -0.003 -0.001 SCRBI20 -0.0158 0.002 -6.365 0.000 -0.021 -0.011 HMP2N24 -0.1380 0.085 -1.629 0.103 -0.304 0.028 AGE 0.0326 0.005 6.511 0.000 0.023 0.042 SUB_PRIME_BANKCARD_PROPENSITY -0.0005 0.001 -1.019 0.308 -0.002 0.000 FINSCR -0.0043 0.000 -10.570 0.000 -0.005 -0.003 REVMOF -0.0007 0.000 -2.301 0.021 -0.001 -0.000 Now, I am trying to predict using result.predict() for a sample record below: AGEINQ BKROPN12 SCRG001 BKRATTH HET1001_HE SCRS009 SCRPF33 CINS99 \ 10 0 1 99 0 3 140000 380 SCRBI20 HMP2N24 AGE SUB_PRIME_BANKCARD_PROPENSITY FINSCR REVMOF 160.0 0 45 331 711 286 And probability produced is : 0.003365. However, if I use manual method: logit=sum(coeff*var) and prob=1/1+exp(-logit), then I get prob: 0.0000897386. How does statsmodel predict works?
accepted answer: http://stackoverflow.com/a/50966964
has title: how does statsmodel.api predict works
answer count: 1
downvote count: 0

http://stackoverflow.com/a/50881053
has comment: http://stackoverflow.com/comment/88766206
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/88773130
has body: Use simple python call and remove some of pandas call. def testTime(): df = pd.DataFrame.from_dict(d) #print(df) #print(d.keys()) lstOverdue = [] lstTeams = [team for team in df.HomeTeam.unique()] for team in lstTeams: mask = (df.HomeTeam == team) | (df.AwayTeam == team) overdue = 0 for row in df[mask].itertuples(): if row.GTOT &lt; 1: lstOverdue.append((row.League, team, overdue, row.Date)) overdue = 0 else: overdue += 1 def testTime2(): df = pd.DataFrame.from_dict(d) lstOverdue = [] for team in df.HomeTeam.unique(): overdue = 0 for row in df.itertuples(): if row.HomeTeam == team or team == row.AwayTeam: if row.GTOT &lt; 1: lstOverdue.append((row.League, team, overdue, row.Date)) overdue = 0 else: overdue += 1 if __name__ == '__main__': import timeit print(timeit.timeit("testTime2()", setup="from __main__ import testTime2", number=1000)) print(timeit.timeit("testTime()", setup="from __main__ import testTime", number=1000)) see function testTime2, after running this code I observed around half of running time on my system with the data you've provided, but it can vary on your system as well. $ python3.6 test.py 21.352469262998056 39.04840800600141 $ python3.6 test.py 22.977724283999123 39.568580347000534 $ python3.6 test.py 21.838805349998438 39.85868542999742 This can be further reduced to number of data rows but it requires some preprocessing as follows. Convert dictionary to list of namedtuples during conversion create set of HomeTown. Process the list similar to the function testTime2 process data frames.
downvote count: 0
has comment: http://stackoverflow.com/comment/88779490
type: Answer
answers question: http://stackoverflow.com/q/50875234

http://stackoverflow.com/a/50904285
has body: You're going to have issues with quoting as long as you're using a CSV writer to write raw text. Why not iterate and write to a text file directly? with open('output.txt', 'w') as f: for text in df['tokens'].tolist(): f.write(text + '\n') Or, in a single line, with open('output.txt', 'w') as f: f.write(df['tokens'].str.cat(sep='\n'))
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 16
answers question: http://stackoverflow.com/q/50904250
score: 16
accepted answer of: http://stackoverflow.com/q/50904250

http://stackoverflow.com/comment/88874876
comment on: http://stackoverflow.com/a/50937929
type: Comment
score: 2
has text: Add django_filters as INSTALLED_APPS for template rendering
type: AnswerComment

http://stackoverflow.com/a/50983809
type: Answer
answers question: http://stackoverflow.com/q/50971697
has body: Below is the entire script on how to Upload/Download in Drive API using both Python 2 and Python 3 from Wesley Chun's blogpost: #!/usr/bin/env python from __future__ import print_function import os from apiclient import discovery from httplib2 import Http from oauth2client import file, client, tools SCOPES = 'https://www.googleapis.com/auth/drive' store = file.Storage('storage.json') creds = store.get() if not creds or creds.invalid: flow = client.flow_from_clientsecrets('client_secret.json', SCOPES) creds = tools.run_flow(flow, store) DRIVE = discovery.build('drive', 'v2', http=creds.authorize(Http())) FILES = ( ('hello.txt', False), ('hello.txt', True), ) for filename, convert in FILES: metadata = {'title': filename} res = DRIVE.files().insert(convert=convert, body=metadata, media_body=filename, fields='mimeType,exportLinks').execute() if res: print('Uploaded "%s" (%s)' % (filename, res['mimeType'])) if res: MIMETYPE = 'application/pdf' res, data = DRIVE._http.request(res['exportLinks'][MIMETYPE]) if data: fn = '%s.pdf' % os.path.splitext(filename)[0] with open(fn, 'wb') as fh: fh.write(data) print('Downloaded "%s" (%s)' % (fn, MIMETYPE))
score: 0

http://stackoverflow.com/a/51049076
type: AcceptedAnswer
type: Answer
has body: This should perform the desired sorting/transformation on the input data. It will also provide an array of 1s that appear at the end of the data for reference. dataarray = numpy.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [20, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [30, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [50, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [60, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], [70, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0], [80, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [90, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) padded = numpy.pad(dataarray,((1,1),(0,0)), 'constant') colinds, rowinds = numpy.where((padded[:-1] != padded[1:]).T) lengths = rowinds[1::2] - rowinds[::2] colinds, rowinds, = colinds[::2], rowinds[::2] parsed = list(zip(colinds, rowinds, lengths)) lenind = [] d = {} for row in parsed: if(row[-1] not in lenind): lenind.append(row[-1]) for i in sorted(lenind): d[i] = 0 for row in parsed: d[row[-1]] += 1 od = collections.OrderedDict(sorted(d.items())) for line in parsed: if(line[1] + line[2] == len(dataarray)-1): print(line) parsedarray = numpy.array(parsed) endflips = [j for j in parsedarray if j[1] + j[2] &gt;= len(dataarray)] Data should come out in the format of "column #, row #, length", where length is the number of 1s in a row in that column.
accepted answer of: http://stackoverflow.com/q/50976947
answers question: http://stackoverflow.com/q/50976947
score: 0

http://stackoverflow.com/comment/88838525
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50919245
has text: what happens when you do this? what do you expect to happen? Comparing actual behavior to expected behavior is crucial in determining how others can help.

postman
tags question: http://stackoverflow.com/q/50929265
tags question: http://stackoverflow.com/q/50924750
tag name: postman
type: Tag
tags question: http://stackoverflow.com/q/50974535

http://stackoverflow.com/comment/88813861
score: 1
type: Comment
has text: Is this code on top-level, or within some function? My guess is that the image is being garbage-collected (yes, even though it's used in the Label). Try making the image `global`. See e.g. [this](https://stackoverflow.com/a/17761218/1639625) and many other related questions and answers.
type: QuestionComment
comment on: http://stackoverflow.com/q/50906964

http://stackoverflow.com/q/50918257
has comment: http://stackoverflow.com/comment/88836806
has answer: http://stackoverflow.com/a/50918541
has comment: http://stackoverflow.com/comment/88836736
score: 0
has comment: http://stackoverflow.com/comment/88837009
has body: I have the code chop_flag = True def decorator(func): def chop_num(num): num = str(num) num = num[:15] return float(num) return chop_num def decorator2(): return decorator if chop_flag else break And then before each function in my program I add @decorator2. This is producing a type error ("decorator2() takes 0 positional arguments but 1 was given") and I'm also pretty sure this is not a great way to do what I'm trying to do. To summarize: I'm trying to take the output of each function in my program and run it through the chop_num() function if chop_flag = True; if chop_flag = False, I want it to just ignore the decorator. I thought I'd do this by applying a decorator to each function. Any help would be appreciated. Updated code: chop_flag = True def decorator(func): if chop_flag == True: def chop_num(num, *args, **kwargs): num = func(*args, **kwargs) num = str(num) num = num[:15] return float(num) return chop_num else: return It now runs properly, but when I import my file into the interpreter (for example) and call the add function, it says "add() missing 1 required positional argument" even though I have put in two arguments.
upvote count: 1
downvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/88836815
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88836694
tagged with: python
tagged with: python-decorators
has title: Decorating all functions in a file if variable is set to true in python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50918541
has comment: http://stackoverflow.com/comment/88837094
type: Question

http://stackoverflow.com/comment/88969923
has text: if you want to loop through the rows you could ```for row in df.values: if row in dff.values: print row```. Could you show an example of both dataframes? print head or something similar.
comment on: http://stackoverflow.com/q/50987242
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50928054
upvote count: 1
downvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/50927994
has body: x | y | x and y ------|-------|--------- True | True | y True | False | y False | True | x False | False | x Since a non-empty list is evaulated as True in a boolean expression in python, x and y returns y. What you are looking for is: y3 = [a and b for a,b in zip(y1,y2)]
score: 0

http://stackoverflow.com/comment/88987134
comment on: http://stackoverflow.com/q/50995005
type: QuestionComment
has text: Let me know if that works.
score: 0
type: Comment

http://stackoverflow.com/comment/88779814
has text: PS. Don't ask me how I found that out. That's what I get for not reading over something carefully before running it.
comment on: http://stackoverflow.com/q/50888786
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50974361
score: 0
has answer: http://stackoverflow.com/a/50974664
answer count: 1
favorite count: 0
tagged with: python-3.x
has body: a= something iterable object in python del a[1] Is del a[1] always the same as a.__delitem__(1)? Is the Python del statement defined as a call to the __delitem__ method?
has comment: http://stackoverflow.com/comment/88944963
upvote count: 1
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88945036
downvote count: 1
has comment: http://stackoverflow.com/comment/88945129
type: Question
accepted answer: http://stackoverflow.com/a/50974664
has title: Is the del statement always 100% the same as calling __delitem__?
has comment: http://stackoverflow.com/comment/88945031

http://stackoverflow.com/comment/88874993
has text: `x` must be a matrix, not a vector. Try passing `x[:,np.newaxis]` instead of `x` to the function. `x.reshape(-1,1)` must have helped, too. How exactly "it doesn't help"?
score: 0
comment on: http://stackoverflow.com/q/50934409
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50935922
has comment: http://stackoverflow.com/comment/88890052
answers question: http://stackoverflow.com/q/50930792
type: Answer
upvote count: 1
has body: A possible solution is to create a class that manages the processes, and that emits a single signal when all the processes finish as you require. import sys from functools import partial from PyQt4 import QtCore, QtGui class TaskManager(QtCore.QObject): resultsChanged = QtCore.pyqtSignal(list) def __init__(self, parent=None): QtCore.QObject.__init__(self, parent) self.results = [] self.m_processes = [] self.number_process_running = 0 def start_process(self, programs): for i, program in enumerate(programs): process = QtCore.QProcess(self) process.readyReadStandardOutput.connect(partial(self.onReadyReadStandardOutput, i)) process.start(program) self.m_processes.append(process) self.results.append("") self.number_process_running += 1 def onReadyReadStandardOutput(self, i): process = self.sender() self.results[i] = process.readAllStandardOutput() self.number_process_running -= 1 if self.number_process_running &lt;= 0: self.resultsChanged.emit(self.results) def on_finished(results): print(results) QtCore.QCoreApplication.quit() if __name__ == '__main__': app = QtCore.QCoreApplication(sys.argv) manager = TaskManager() manager.start_process(["ls", "ls"]) manager.resultsChanged.connect(on_finished) sys.exit(app.exec_())
has comment: http://stackoverflow.com/comment/88890465
type: AcceptedAnswer
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/50930792

http://stackoverflow.com/q/50856325
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88715482
has comment: http://stackoverflow.com/comment/88715032
type: Question
has comment: http://stackoverflow.com/comment/88715682
has answer: http://stackoverflow.com/a/50856963
has comment: http://stackoverflow.com/comment/88715237
answer count: 1
has body: Hello i am trying to autogenerate a PDF, i have made a python script that generates the wanted PDF but to generate it i have to call my_cover.py -s "Atsumi" -t "GE1.5s" -co "Japan" from my command line. Does anyone know an easy way to call this command line from within my python script. In the script i will prompt the user to input the 3 strings which currently are "Atsumi", "GE1.5s" and "Japan" but these should change with whatever the user inputs and should therefore also change in the command line call. Any help is much appreciated site_name = raw_input('Name of wind turbine site: ') turbine_name = raw_input('Name of turbine type: ') country_name = raw_input('Name of country location: ') parser = argparse.ArgumentParser() parser.add_argument('-s', '--site') parser.add_argument('-t', '--turbine') parser.add_argument('-c', '--country') args = parser.parse_args() with open('cover.tex','w') as f: f.write(content%args.__dict__) cmd = ['pdflatex', '-interaction', 'nonstopmode', 'cover.tex'] proc = subprocess.Popen(cmd) proc.communicate() retcode = proc.returncode if not retcode == 0: os.unlink('cover.pdf') raise ValueError('Error {} executing command: {}'.format(retcode, ' '.join(cmd))) os.unlink('cover.tex') os.unlink('cover.log') "Code to run the command line goes here" '''my_cover.py -s "Atsumi" -t "GE1.5s" -co "Japan"'''
has title: Run command line containing multiple strings from python script
has comment: http://stackoverflow.com/comment/88741916
score: 0
has comment: http://stackoverflow.com/comment/88716525
has comment: http://stackoverflow.com/comment/88718357
tagged with: python
tagged with: pdf-generation
tagged with: command-line

http://stackoverflow.com/comment/88919042
comment on: http://stackoverflow.com/a/50960783
score: 0
type: Comment
has text: Would there be a way to remove rows of data depending on the input data (what you have done currently) and remove the output label along with it?
type: AnswerComment

system-calls
type: Tag
tags question: http://stackoverflow.com/q/50896965
tag name: system-calls

http://stackoverflow.com/comment/88753257
comment on: http://stackoverflow.com/a/50875438
score: 2
has text: FWIW `root_win.bind('<Destroy>', good_bye)` works for me, the function is called only once. Python 3.6.5 from python.org on windows 7 32 bits.
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50955206
has answer: http://stackoverflow.com/a/50955393
possible better answer: http://stackoverflow.com/a/50955337
tagged with: python
score: 1
upvote count: 1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50955393
has answer: http://stackoverflow.com/a/50955428
type: Question
answer count: 3
has answer: http://stackoverflow.com/a/50955337
downvote count: 0
has body: Problem: Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice. My code: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ for x in nums: for y in nums: if nums.index(x) != nums.index(y) and x + y == target : return [nums.index(x), nums.index(y)] print (twoSum ([3, 3],6)) Output: null In my mind the first "iteration" (I am not quite sure if this is the right term) looks like : If 0 != 0 (False) and 3 + 3= 6 (True) --&gt; as the first condition is not met, the y loops So the next iteration looks like: If 0 != 1 (True) and 3 + 3 = 6 (True) --> as above conditions are met, the function would return [0,1], but instead the code actually returns null and I do not understand the reason. So, I would really appreciate, if someone could either explain what's happening, or tell me some keywords, in order to search for the answer on my own :)
favorite count: 0
tagged with: python-3.x
has title: Two Sum LeetCode - why my own code failed

http://stackoverflow.com/q/50931606
tagged with: requirements.txt
has comment: http://stackoverflow.com/comment/88864366
has body: I have a requirements.txt file with data like py3DNS==3.1.0; python_version &gt; '3' scapy-python3==0.23; python_version &gt; '3' pyDNS==2.3.6; python_version &lt; '3' scapy==2.4.0; python_version &lt; '3' for specifying python version during installation of libraries and in setup.py I am using to load requirements from requirements.txt file requirements = open("requirements.txt").read().rsplit() setup( install_requires=requirements, ...) and got this requirements = ['py3DNS==3.1.0;', 'python_version', '&gt;', "'3'", 'scapy-python3==0.23;', 'python_version', '&gt;', "'3'", 'pyDNS==2.3.6;', 'python_version', '&lt;', "'3'", 'scapy==2.4.0;', 'python_version', '&lt;', "'3'"] which basically can't be used, I can make changes manually but I wanted to know if there is any generic way to do this stuff
has answer: http://stackoverflow.com/a/50931854
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/88866478
has title: python version in requirements.txt issues with install requires in setup.py
has comment: http://stackoverflow.com/comment/88866352
favorite count: 0
score: 0
tagged with: python
tagged with: python-2.x
has comment: http://stackoverflow.com/comment/88864611
tagged with: python-3.x
tagged with: setup.py
upvote count: 2
type: UnansweredQuestion
downvote count: 2

http://stackoverflow.com/comment/88961444
comment on: http://stackoverflow.com/a/50983061
type: AnswerComment
score: 0
type: Comment
has text: @Submi - To get exactly same output use reset_index. updated to the solution

http://stackoverflow.com/a/50943973
has body: Please also read the comments: for i in list2: #iterate through list2 for j in list1: #iterate through list of dictinaries if i in j.values(): #if value of list2 present in the values of a dict then proceed print(j['Value'])
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/50943899
score: 1

http://stackoverflow.com/a/50985253
upvote count: 5
answers question: http://stackoverflow.com/q/50983008
has body: Before trying to answer your question, I would like to make a quick remark about your use of the ModelCheckpoint callback. Let's have a look at the default parameters : keras.callbacks.ModelCheckpoint(filepath, monitor='val_loss', verbose=0, save_best_only=False, save_weights_only=False, mode='auto', period=1) The save_weights_only parameter's default value is False which means what you are actually saving is not only the model's weights but the entire architecture ! Thus, when loading the weights of your model you can either redefine the model and use load_weights. Or you can directly load your model from the file, using the load_model function. Now, to save only the encoder, I would write a new checkpoint callback, like this : class CustomCheckpoint(Callback): def __init__(self, filepath, encoder): self.monitor = 'val_loss' self.monitor_op = np.less self.best = np.Inf self.filepath = filepath self.encoder = encoder def on_epoch_end(self, epoch, logs=None): current = logs.get(self.monitor) if self.monitor_op(current, self.best): self.best = current # self.encoder.save_weights(self.filepath, overwrite=True) self.encoder.save(self.filepath, overwrite=True) # Whichever you prefer As an alternative, since you already have the save file for the entire network, you can separate your encoder from the decoder like this : from keras.models import load_model autoencoder = load_model("path_to_file") encoder = Model(autoencoder.layers[0].input, autoencoder.layers[1].output)
score: 5
downvote count: 0
type: Answer

http://stackoverflow.com/comment/88844087
comment on: http://stackoverflow.com/q/50920683
score: 0
type: Comment
has text: I try this and I've the same problem, I believe that my vhost config be wrong. But I not found any tutorial to correctly deploy setup for python3.6 and mod_wsgi
type: QuestionComment

http://stackoverflow.com/comment/88894901
comment on: http://stackoverflow.com/q/50948658
type: Comment
type: QuestionComment
score: 0
has text: Can you explain your situation a bit more into details?

http://stackoverflow.com/comment/88908428
type: Comment
comment on: http://stackoverflow.com/q/50952618
type: QuestionComment
has text: Updated the boolean values, now getting a new error with the positional_wrapper from the googleapiclient
score: 0

python-keyring
type: Tag
tag name: python-keyring
tags question: http://stackoverflow.com/q/50979461

http://stackoverflow.com/q/50959718
type: AnsweredQuestion
tagged with: list
upvote count: 3
accepted answer: http://stackoverflow.com/a/50959780
possible better answer: http://stackoverflow.com/a/50959830
type: Question
has answer: http://stackoverflow.com/a/50961751
score: 3
has answer: http://stackoverflow.com/a/50959830
tagged with: iterator
downvote count: 0
has answer: http://stackoverflow.com/a/50959780
favorite count: 0
tagged with: python-3.x
answer count: 5
has answer: http://stackoverflow.com/a/50976650
has body: Say I have a long list: &gt;&gt;&gt; import string &gt;&gt;&gt; my_list = list(string.ascii_lowercase) &gt;&gt;&gt; my_list ['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'] I want to loop over this list and select n items by sequence repeatedly. E.g. if I want to select 5 items, then it should be like: step 1: ['a', 'b', 'c', 'd', 'e'] step 2: ['f', 'g', 'h', 'i', 'j'] step 3: ['k', 'l', 'm', 'n', 'o'] step 4: ['p', 'q', 'r', 's', 't'] step 5: ['u', 'v', 'w', 'x', 'y'] step 6: ['z', 'a', 'b', 'c', 'd'] step 7: ['e', 'f', 'g', 'h', 'i'] ...... So the point is: I want to make sure when I reach the last item of the list, the first items can be appended to the last one and the looping just keep going. For appending the first items to the last items, I've tried something like this: def loop_slicing(lst_, i): """ Slice iterable repeatedly """ if i[0] &gt; i[1]: return [n for n in lst_[i[0]:]+lst_[:i[1]]] else: return lst_[i[0]:i[1]] When I call this function, I can do this: &gt;&gt;&gt; loop_slicing(my_list, (0, 5)) ['a', 'b', 'c', 'd', 'e'] &gt;&gt;&gt; loop_slicing(my_list, (25, 4)) ['z', 'a', 'b', 'c', 'd'] Where I can just make a generator which can generate 5 sequential numbers in range(0, 26) to loop over my_list and get 5 items each time. I don't know if this is the best approach. So is there any more efficient way to do the stuff?
has answer: http://stackoverflow.com/a/50960944
has title: Select n items by sequence of a list repeatedly in python
tagged with: python

http://stackoverflow.com/q/50975012
linked to: http://stackoverflow.com/q/41790750
score: 2
type: AnsweredQuestion
has body: I have the following method in my Tornado handler: async def get(self): url = 'url here' try: async for batch in downloader.fetch(url): self.write(batch) await self.flush() except Exception as e: logger.warning(e) This is the code for downloader.fetch(): async def fetch(url, **kwargs): timeout = kwargs.get('timeout', aiohttp.ClientTimeout(total=12)) response_validator = kwargs.get('response_validator', json_response_validator) extractor = kwargs.get('extractor', json_extractor) try: async with aiohttp.ClientSession(timeout=timeout) as session: async with session.get(url) as resp: response_validator(resp) async for batch in extractor(resp): yield batch except aiohttp.client_exceptions.ClientConnectorError: logger.warning("bad request") raise except asyncio.TimeoutError: logger.warning("server timeout") raise I would like yield the "batch" object from multiple downloaders in paralel. I want the first available batch from the first downloader and so on until all downloaders finished. Something like this (this is not working code): async for batch in [downloader.fetch(url1), downloader.fetch(url2)]: .... Is this possible? How can I modify what I am doing in order to be able to yield from multiple coroutines in parallel?
linked to: http://stackoverflow.com/q/50901182
tagged with: async-await
possible better answer: http://stackoverflow.com/a/50975957
has answer: http://stackoverflow.com/a/50975690
has answer: http://stackoverflow.com/a/50975957
has title: Python parallelising "async for"
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/88946406
accepted answer: http://stackoverflow.com/a/50975690
downvote count: 0
tagged with: asynchronous
favorite count: 0
tagged with: python-asyncio
upvote count: 2
tagged with: python

http://stackoverflow.com/comment/88754650
score: 0
type: Comment
type: QuestionComment
has text: This is not as CSV file. What have you tried? Please show your code first, and state your concrete problem. Then we may be able to help.
comment on: http://stackoverflow.com/q/50876470

dna-sequence
tags question: http://stackoverflow.com/q/50887675
type: Tag
tag name: dna-sequence

http://stackoverflow.com/comment/88813990
score: 2
type: Comment
type: QuestionComment
has text: `[^ابتثجحخدذرزسشصضطظعغفقكنهويىؤئء]` is a regex, so use it with the appropriate `re.sub` method.
comment on: http://stackoverflow.com/q/50907064

http://stackoverflow.com/comment/89006016
has text: I want to send arbitrary TCP, and ethernet packets periodically (every 20 ms). I was wondering if by opening two separate sockets, I can send TCP and ethernet packets at the same time.
comment on: http://stackoverflow.com/q/51006213
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89012178
comment on: http://stackoverflow.com/a/51009773
type: AnswerComment
has text: thanks, your answer is more readable and beginner friendly though so i'd say it's better
score: 0
type: Comment

http://stackoverflow.com/q/50963613
has body: I've written a small function to replace certain words with python-docx, which works great except that it changes some style element but weirdly not all of them. My function (simplified): def template2doc(replace_dict, source, destination): """ Creates a new docx file from a template, replacing keywords withing the template and saving with a new name :param replace_dict: dict for replacing each key with its value :param source: path to source template file :param destination: path to save the result document :return: None """ doc = docx.Document(source) for key, replacement in replace_dict.items(): for paragraph in doc.paragraphs: if key in par.text: paragraph.text = paragraph.text.replace(key, replacement) # Save the result doc.save(destination) This works for replacing words or sentences, but fails to preserve some style elements for the paragraph (alignment, font size, bold) but preserves others (double underline for example). So my question: Is there a better way to replace phrases in docx files, while still keeping all of the former styling? Note: i'm not "married" to python-docx, any solution or package that works will do
type: UnansweredQuestion
upvote count: 3
downvote count: 1
has title: Preserving styles while replacing words in python-docx
type: Question
has answer: http://stackoverflow.com/a/51868655
answer count: 1
tagged with: python-docx
linked to: http://stackoverflow.com/q/34779724
favorite count: 0
tagged with: python
score: 2
tagged with: http://stackoverflow.com/tag/docx

http://stackoverflow.com/comment/88885875
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50924974
score: 0
has text: I've made it more clearer above. Please let me know if you still don't understand it

http://stackoverflow.com/q/50895659
type: Question
score: 3
has comment: http://stackoverflow.com/comment/88791309
has answer: http://stackoverflow.com/a/50895771
accepted answer: http://stackoverflow.com/a/50895771
upvote count: 3
downvote count: 0
answer count: 1
has body: Is it possible to access decorator attributes in Python 3? For example: is it possible to access self.misses after the call to the decorated fibonacci method? class Cache: def __init__(self, func): self.func = func self.cache = {} self.misses = 0 def __call__(self, *args): if not (args in self.cache): self.misses += 1 self.cache[args] = self.func(*args) return self.cache[args] @Cache def fibonacci(n): return n if n in (0, 1) else fibonacci(n - 1) + fibonacci(n - 2) fibonacci(20) ### now we want to print the number of cache misses ###
tagged with: decorator
favorite count: 0
has title: How to access decorator attributes?
tagged with: python
tagged with: python-decorators
has comment: http://stackoverflow.com/comment/88792301
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88791299

http://stackoverflow.com/a/50911980
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50910900
score: 0
answers question: http://stackoverflow.com/q/50910900
type: Answer
has body: If the idea is to use recursion for combining the results as well as in the algorithm itself then this will work: def GCD(*numbers): a, b = numbers[:2] if len(numbers) == 2: if b == 0: return a else: return GCD(b, a % b) else: return GCD(GCD(a, b), *numbers[2:]) print(GCD(*received_inputs)) Another options include a loop (ok) or using functools.reduce (not recommended as not readable enough).

http://stackoverflow.com/comment/88795605
has text: Note that the OP now has to do stuff in both the inner loop and the outer loop.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50897981

http://stackoverflow.com/comment/88869818
type: Comment
has text: Thanks. Edited to eliminate syntax error: Foo.num_examples('bar', 86)
comment on: http://stackoverflow.com/a/50935518
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88796927
has text: Anyways if the 3 coordinate arrays have the right values and shape, they can be used as I first indicated `arr[x, y, z]`.
score: 1
comment on: http://stackoverflow.com/a/50898189
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/88840479
has text: Okay so here's what I want to do:
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50919759
type: Comment

http://stackoverflow.com/comment/98637413
score: 1
comment on: http://stackoverflow.com/a/50892019
type: AnswerComment
has text: It does not work. Travis asks me to `Please override the script: key in your .travis.yml to run tests.`
type: Comment

http://stackoverflow.com/q/50988726
type: AnsweredQuestion
downvote count: 0
favorite count: 0
tagged with: series
has answer: http://stackoverflow.com/a/50988814
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/88972049
upvote count: 2
accepted answer: http://stackoverflow.com/a/50988814
has comment: http://stackoverflow.com/comment/88972113
answer count: 1
has title: How to get boolean index array for pandas DataFrame where obs != last_obs?
has body: I have a DataFrame where there is a column we can call 'X.' So something like 'print(df.X)' would yield some integers somewhere between -10,000 and 10,000. For example: ID X 1 0 2 0 3 1 4 1 ... 7334 -19 7335 -19 7336 -20 7337 -20 &gt;&gt;&gt; For the example above, I'd like a boolean index I can use to subset the DataFrame where row 3 is equal to True and row 7336 is equal to True, because the value in X changes from the last observation. All others should be False.
tagged with: pandas
score: 2

http://stackoverflow.com/q/50859634
type: Question
score: 1
has body: I built a script in Python to copy any files from a list of folders to a destination folder already made. source = ['c:/test/source/', ] destination = 'c:/test/destination/' def copy(source, destination): import os, shutil try: for folder in source: files = os.listdir(folder) for file in files: current_file = os.path.join(folder, file) shutil.copy(os.path.join(folder, file), destination) except: pass The problem with this script is that it didn't copy the sub folders. Any suggestion to fix it ? Thanks
accepted answer: http://stackoverflow.com/a/50859660
answer count: 1
downvote count: 0
favorite count: 0
has title: Python copy files script
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50859660
upvote count: 1

http://stackoverflow.com/comment/88875641
has text: @DyZ Good point on IDLE. IIRC (I haven't used it in forever…), it captures the SyntaxError and highlights the line in-place, instead of letting it show the error information normally?
comment on: http://stackoverflow.com/q/50938630
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88984312
score: 0
has text: @ℕʘʘḆḽḘ that is why I included the "1000 bytes" approach, as it doesn't use lines splitting
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50994842

http://stackoverflow.com/q/50877184
has answer: http://stackoverflow.com/a/50877455
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88756454
type: Question
tagged with: ctypes
downvote count: 0
tagged with: http://stackoverflow.com/tag/c
accepted answer: http://stackoverflow.com/a/50877455
answer count: 1
has title: Python 3 ctypes call for function with returned struct fails with segfault
favorite count: 0
tagged with: python-3.x
upvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/88756491
has body: I'm trying to run a C function that returns a struct containing multiple int (for now). My C source looks like this: struct my_struct { int i; int j; } ; extern "C" struct my_struct struct_test(){ struct my_struct s; s.i = 2; s.j = 331; return s; } The corresponding Makefile is this: CXX=/usr/bin/g++ PYTHON=/usr/bin/ipython3 --colors Linux CXXFLAGS=-Wall -fPIC -O3 -c LDFLAGS=-Wall -shared -Wl,-soname,libfoo.so TARGETS=mylib.so all: mylib.so test mylib.so: mylib.cpp $(CXX) $(CXXFLAGS) -o mylib.o mylib.cpp $(CXX) $(LDFLAGS) -o mylib.so mylib.o test: mylib.so $(PYTHON) ctypes_call_test.py clean: rm -f $(TARGETS) And the Python script is here: import ctypes libname = './mylib.so' class my_struct(ctypes.Structure): _fields_ = [ ("i", ctypes.c_int), ("j", ctypes.c_int), ] mylib = ctypes.cdll.LoadLibrary(libname) mylib.struct_test.argtypes=[] mylib.struct_test.restype=ctypes.POINTER(my_struct) ret = mylib.struct_test(); print('got return value') print(ret.contents.i, ret.contents.j) When I run the Python script, it crashes immediately after the print() statement. Any ideas why this is happening?
score: 2

http://stackoverflow.com/q/50967231
has body: I have a DataFrame.... _id doc_count doc_media_url image_tagging 0 327bcc224b8c7049 1.0 URL1 {'success': True, 'tags': [], 'custom_tags': []} 1 e466c4966666c69e 1.0 URL2 {'success': True, 'tags': [{'tag': 'Cartoon', ... 2 b4303830389cf8f9 1.0 URL3 {'success': True, 'tags': [{'tag': 'Poster', '... 3 00a424323220b68e 1.0 URL4 {'success': True, 'tags': [{'tag': 'Stage', 'c... 4 c66e3e2921a7c7cd 1.0 URL5 {'success': True, 'tags': [], 'custom_tags': []} ... and my issue is with the image_tagging column. Currently it is a column of dictionaries. I intend to extract out the keys of the dictionary into their own columns, however I'm being impeded because one single row of the data is not a dictionary but a list which throws off any operations that are expecting a dictionary. df.image_tagging.apply(lambda x: type(x)).value_counts() &lt;class 'dict'&gt; 14067 &lt;class 'list'&gt; 1 Name: image_tagging, dtype: int64 This list item shouldn't be there so I'd like to clean out that row. However I'm having an issue selecting rows by type because Pandas mainly focuses on dtypes and a dict and a list are classified as the same (I think anyway!). Is there a way I can select the row with the list item in that column so that I can remove it from the DataFrame? Thanks for any assistance!
accepted answer: http://stackoverflow.com/a/50967339
upvote count: 5
has title: Pandas - Select Rows by 'type' (Not dtype)
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/50967339
tagged with: python
type: AnsweredQuestion
type: Question
score: 5

http://stackoverflow.com/comment/88866215
comment on: http://stackoverflow.com/q/50933454
score: 0
type: Comment
type: QuestionComment
has text: @Barmar I was already able to read the last line of the file. I was wanting to search for a string from within that last line.

http://stackoverflow.com/q/50894963
tagged with: pickle
tagged with: python
has body: I have a problem with rdkit and spark. I gives me an error Depickling from a version number (9.0)that is higher than our version (7.2) I am using conda, I tried to update pickle (I thought maybe that is the problem) however it seems that conda does not have pickle. Can anyone provide some direction please with regards to the source of the problems. Thanks
answer count: 0
has comment: http://stackoverflow.com/comment/88790003
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88790077
has comment: http://stackoverflow.com/comment/88790056
has title: Depickling from a version number that is higher than our version
type: Question
has comment: http://stackoverflow.com/comment/88789955
has comment: http://stackoverflow.com/comment/88789922
has comment: http://stackoverflow.com/comment/88790051
score: 0

http://stackoverflow.com/comment/88824046
has text: Use a dictionary instead of new variable names.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50911501

http://stackoverflow.com/comment/88839992
has text: Yes, I observed that. I do not think it is causing the problem because if I delete \x00 in the beginning, it works with utf-16 and gives "rarely used" Chinese character.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50919558

http://stackoverflow.com/a/50883927
answers question: http://stackoverflow.com/q/50883894
score: 0
type: Answer
has body: What you need is a way to determine the index position as you iterate through the list. You can create a simple counter than increments as you go through the list: dark = [] dposition = [] count = 0 for a in pixels: if a&lt;100: dark.append(a) dposition.append(count) count += 1 Or you can use Python's built in enumerate function to generate the position as you iterate through it: dark = [] dposition = [] for position, a in enumerate(pixels): if a&lt;100: dark.append(a) dposition.append(position)

http://stackoverflow.com/comment/88934983
type: Comment
type: QuestionComment
has text: Do you want to print EVERY possible chain?
comment on: http://stackoverflow.com/q/50968717
score: 0

http://stackoverflow.com/comment/88839102
score: 0
comment on: http://stackoverflow.com/q/50919585
has text: Okay, but that code is made to select folders, what I understand is that you want to be able to enter the folders and see the files, but only select folders. I am right?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50877785
favorite count: 0
tagged with: python
type: AnsweredQuestion
has body: One can obtain the "column headers" from an sklearn Bunch as Bunch.feature_names. However, this does not give the "column header" for the target variable. How does one obtain the "column header" for the target variable? e.g. for the Iris dataset: &gt;&gt;&gt; data.feature_names ['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width(cm)'] In this spirit, the "column header" for the target variable would be something like "species" (since data.target_names gives array(['setosa', 'versicolor', 'virginica'], dtype='&lt;U10'). Does a sklearn Bunch have a means to obtain the "column header" for the target, e.g. "species"?
score: 3
has title: How to obtain target feature name from a sklearn `Bunch`
accepted answer: http://stackoverflow.com/a/50879725
upvote count: 3
type: Question
has answer: http://stackoverflow.com/a/50879725
answer count: 1
downvote count: 0
tagged with: scikit-learn

http://stackoverflow.com/a/50975344
type: Answer
has comment: http://stackoverflow.com/comment/88980096
has comment: http://stackoverflow.com/comment/89012541
has comment: http://stackoverflow.com/comment/88948875
has body: You can use below Xpath driver.find_element_by_xpath("//textarea[@name='to']").send_keys("abc@gmail.com")
score: 0
has comment: http://stackoverflow.com/comment/88948776
answers question: http://stackoverflow.com/q/50974639
has comment: http://stackoverflow.com/comment/89017629

http://stackoverflow.com/q/50918667
has body: Hello I have run into an issue that is usually a common fix but mine has a twist. The usual answer I will quote here: "Sequence numbers between the client and the server has to be sync. In your case even if you reset the sequence number, you will get the same error because the client will send a larger sequence number that you have. It is a common practice that both the client and the server resets the sequence numbers on agreement(on logon,each day or sending 141=Y etc.)." The problem is that this flag "ResetMsgSeqNum" can only be used in the onLogon method in Quickfix. I am not able to login because the sequence numbers are out of sync so I do not have the opportunity to tell the acceptor to reset it's sequence numbers as well. There have been suggestions to increment to the next sequence number as well however those were for the Java Quickfix and I am unaware how to do this in the python version. I will post a sample of my log below of what is happening. NOTE: I have removed identifying info only from the even logs so the tags are not actually blank below. Messages such as "onCreate" are debugging statements to indicate if a method has been successfully been executed. I appreciate any and all help! onCreate &lt;20180618-22:50:15.000000000, FIX.4.4:, event&gt; (Created session) &lt;20180618-22:50:15.000000000, FIX.4.4:, event&gt; (Connecting to on port 8101 (Source :0)) toAdmin &lt;20180618-22:50:15.000000000, FIX.4.4:, outgoing&gt; (8=FIX.4.4 9=112 35=A 34=13 49= 52=20180618-22:50:15.000 56= 554=PASSWORD &lt;20180618-22:50:15.000000000, FIX.4.4:, event&gt; (Initiated logon request) &lt;20180618-22:50:16.000000000, FIX.4.4:, incoming&gt; (8=FIX.4.4 9=76 35=5 34=6 49= 52=20180618-22:50:16.227 56= 10=171 ) fromAdmin &lt;20180618-22:50:16.000000000, FIX.4.4:, event&gt; (Received logout request) toAdmin &lt;20180618-22:50:16.000000000, FIX.4.4:, outgoing&gt; (8=FIX.4.4 9=77 35=5 34=14 49= 52=20180618-22:50:16.000 56= 10=208 ) &lt;20180618-22:50:16.000000000, FIX.4.4:,…
favorite count: 0
has answer: http://stackoverflow.com/a/51109084
tagged with: quickfix
tagged with: python
has title: Resetting acceptor sequence numbers as an initiator without ability to use onLogon
type: AnsweredQuestion
tagged with: python-3.x
upvote count: 1
accepted answer: http://stackoverflow.com/a/51109084
type: Question
score: 1
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/89018966
comment on: http://stackoverflow.com/q/50997675
type: QuestionComment
has text: vtkMarchingCubes assuming the mask you're talking about is a binary segmentation of the surface you are looking for
score: 0
type: Comment

http://stackoverflow.com/q/50870442
has body: We are using Django Rest Framework to expose API's to Add, edit and retrieve data about users and their skill (with levels) We have models for users, skills and the skillmatrix (through model where we need to add additional data about skill level of that user for a given skill.) class Freelancer(models.Model): user = models.UUIDField (primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=30) contactNumber = models.BigIntegerField (default=None,blank=True, null=True) emailAddress = models.EmailField (max_length=50, blank=False, null=True) bachelorsDegree = models.CharField(max_length=50) mastersDegree = models.CharField(max_length=50) userCertificates = models.TextField(max_length=200) IsActive = models.BooleanField (default=True) UserPassword = models.CharField (max_length=50) DeacivateDate = models.DateTimeField (blank=True, null=True) Address = models.TextField(max_length=200) Pincode = models.IntegerField() class Skill(models.Model): name = models.CharField(max_length=100) skilltype = models.CharField(max_length=100,null=True) userSkills = models.ManyToManyField(Freelancer,through='SkillMatrix') class SkillMatrix(models.Model): user = models.ForeignKey(Freelancer,on_delete=models.CASCADE) skill = models.ForeignKey(Skill,on_delete=models.CASCADE) level = models.CharField(max_length=100,null=True) Now my challenge is the following: I want to find the most efficient way to search for users with specific skills and return it in the order of most relevant to least relevant. There are around 10000 users and around 300 skills. So for example if the required skills are ["python", "html", "css", "postgres"] then I should be able to return a list of UserID's so that User1 >> Skills Python, html, css, postgres all advanced User2 >> Skills python html, css advanced, postgres intermediate User3>> Skills python, html, css advanced, no postgres skill Please help!
type: Question
tagged with: search
score: 0
tagged with: django-rest-framework
has comment: http://stackoverflow.com/comment/88742733
has comment: http://stackoverflow.com/comment/88742492
has comment: http://stackoverflow.com/comment/88757141
type: UnansweredQuestion
tagged with: django
tagged with: python
tagged with: many-to-many
has title: Complex Search in a through model for Many to many relationships in Django
answer count: 0

http://stackoverflow.com/comment/88743713
type: Comment
type: QuestionComment
score: 1
has text: did you use `virtualenv` ?
comment on: http://stackoverflow.com/q/50871016

http://stackoverflow.com/a/51012327
answers question: http://stackoverflow.com/q/51011010
type: Answer
score: 2
has body: You don't need to declare a constructor unless you need to do something specific. For example, our Widget class have a constructor that does lot of stuff, like applying the properties, create the widget canvas, apply kv rules, bind the construtor events if passed etc. If you create a widget, but have nothing to do, there is no need to declare a constructor, the MRO will determinate which one to use on the subclasses. This is the same for all Python classes.
downvote count: 0
upvote count: 2

http://stackoverflow.com/comment/88784799
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50892047
has text: cwd of the process is inherited. If your cmd is at C:\ and you start your server like `python c:\user\name\blabla\serv.py`, then cwd is C:\. Ether change your cwd in cmd (`cd c:\user\name\blabla\ `), hardcode `c:\\user\\name\\blabla\\ ` as path in your app, or look at `__file__` and calculate your paths relative to the location of current python file.
score: 0

http://stackoverflow.com/q/50895751
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/88791633
downvote count: 5
tagged with: flask
has body: I am running a flask server on my Raspberry Pi. I would like to send an mp3 file from android phone to raspberry pi using my app. I have successfully read the mp3 file into InputStream object. I would like to know how to send this object to Pi
has title: How to send mp3 file using a POST request from android studio to flask server
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50896002
type: UnansweredQuestion
tagged with: android
tagged with: python
score: -5
tagged with: java

http://stackoverflow.com/comment/88936487
comment on: http://stackoverflow.com/a/50937460
has text: You got me. I'm using an Anaconda package with numpy installed and assumed it was up to date but just ran the upgrade and went from 1.13.3 to 1.14.5 so that was the incorrect assumption. Problem solved! This is my first time writing my own python from scratch rather than working with a colleagues notebook.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/88889875
comment on: http://stackoverflow.com/q/50946163
has text: `(?P<HOLDER>[^:]*)` should probably be `(?P<HOLDER>[^,]*)` - you want to match up to the next comma (or end of text), not up to the next colon.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50934089
score: 4
has answer: http://stackoverflow.com/a/50934151
linked to: http://stackoverflow.com/q/28556942
possible better answer: http://stackoverflow.com/a/50934151
type: AnsweredQuestion
has body: In a pandas dataframe, how can I drop a random subset of rows that obey a condition? In other words, if I have a Pandas dataframe with a Label column, I'd like to drop 50% (or some other percentage) of rows where Label == 1, but keep all of the rest: Label A -&gt; Label A 0 1 0 1 0 2 0 2 0 3 0 3 1 10 1 11 1 11 1 12 1 12 1 13 I'd love to know the simplest and most pythonic/panda-ish way of doing this! Edit: This question provides part of an answer, but it only talks about dropping rows by index, disregarding the row values. I'd still like to know how to drop only from rows that are labeled a certain way.
tagged with: dataframe
type: Question
upvote count: 4
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/50934196
favorite count: 0
tagged with: pandas
accepted answer: http://stackoverflow.com/a/50934196
has title: "Drop random rows" from pandas dataframe
tagged with: python

http://stackoverflow.com/comment/88955924
has text: Um can you provide example? I'm not sure how to do that
comment on: http://stackoverflow.com/q/50978756
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50999995
type: Answer
answers question: http://stackoverflow.com/q/50999881
has body: Try to update numba and llvmlite references from git numba conda install -c numba llvmlite
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50999881

http://stackoverflow.com/q/50942660
tagged with: list
has title: how to calculate statistic significance for two list in an ab test by using python
has body: I made an A/B test, I have data as following: control_conversion test_conversion day1 100 101 day3 140 200 day5 200 320 day7 400 800 Control and test group have 1000 traffic so the conversion rate would be: control_conversion test_conversion day1 0.10 0.10 day3 0.14 0.20 day5 0.20 0.32 day7 0.40 0.80 I want to use python to calculate the statistic significance for day1, day3, day5, day7 for control and test. So I would need to make two list: control = [0.1, 0.14, 0.20, 0.40] test = [0.1,0.2,0.32,0.8] How can I calculate four p value for the two list? like what I want to see is a list of p values pvalue =[0.1, 0.2, 0,1,0.2,0.1]
type: UnansweredQuestion
type: Question
has answer: http://stackoverflow.com/a/50943159
has comment: http://stackoverflow.com/comment/88883376
score: 0
answer count: 2
upvote count: 1
downvote count: 1
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/51135321

http://stackoverflow.com/q/50958259
tagged with: python
tagged with: parallel-processing
tagged with: tensorflow
type: Question
score: 5
has comment: http://stackoverflow.com/comment/88917449
linked to: http://stackoverflow.com/q/47086599
upvote count: 5
has title: Parallelizing batching using tf.data.Dataset.from_generator()
has body: I have a computationally-expensive method for simulating data coded up as a generator that I want to feed into my neural network model in Tensorflow. I would like to quickly generate batches of data by parallelizing the calls made to the generator. My current data input pipeline as shown below: def data_iterator(): # data generation procedure to be parallelized pass dataset = tf.data.Dataset.from_generator(data_iterator, (tf.float32,tf.float32), (tf.TensorShape([HEIGHT, None, 1]), tf.TensorShape([2]))) dataset = dataset.padded_batch(BATCH_SIZE, padded_shapes=(tf.TensorShape([HEIGHT, None, 1]), tf.TensorShape([2]))) iterator = dataset.make_one_shot_iterator() x_image, y_ = iterator.get_next() Unfortunately, I found that creating a batch of data using the from_generator() method cannot easily be parallelized with no way to specify how many threads I use to pull data from the generator to create batches. I tried the solution in this thread(https://stackoverflow.com/a/47089278) which uses a wrapper function and mapping in parallel and found that the speed did not increase at all. Previously, I was using queues to input my data which seemed to work well as follows: class CustomRunner(object): """ This class manages the the background threads needed to fill a queue full of data. """ def __init__(self): self.dataX = tf.placeholder(dtype=tf.float32, shape=[HEIGHT,WIDTH,1]) self.dataY = tf.placeholder(dtype=tf.float32, shape=[2]) # The actual queue of data. The queue contains a vector for # the features, and a scalar label. self.queue = tf.FIFOQueue(shapes=[[HEIGHT,WIDTH,1],[2]], dtypes=[tf.float32, tf.float32], capacity=QUEUE_CAPACITY) self.enqueue_op = self.queue.enqueue([self.dataX, self.dataY]) def get_inputs(self,batch_size): """ Return's tensors containing a batch of images and labels """ images_batch, labels_batch = self.queue.dequeue_many(batch_size) return images_batch, labels_batch def thread_main(self, sess): """ Function run on alternate thread. Basically, keep a…
downvote count: 0
has comment: http://stackoverflow.com/comment/88913866
favorite count: 0
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88914596
has comment: http://stackoverflow.com/comment/88914412

http://stackoverflow.com/comment/88905637
type: QuestionComment
comment on: http://stackoverflow.com/q/50952702
type: Comment
has text: Have you seen https://stackoverflow.com/a/7644962/18771 (especially the comment under the answer)?
score: 0

http://stackoverflow.com/comment/88994599
comment on: http://stackoverflow.com/q/50997936
score: 0
type: Comment
type: QuestionComment
has text: question has nothing to do with `machine-learning` - kindly do not spam the tag (removed)

http://stackoverflow.com/q/50920710
tagged with: python
score: 1
upvote count: 1
type: Question
tagged with: ssl
has answer: http://stackoverflow.com/a/50921722
tagged with: openssl
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
has body: I'm currently reading Foundations of Python Network Programming and came across the following example, demonstrating how to use Python's ssl module: Listing 6-3: Securing a Socket with TLS for Both Client and Server in Python 3.4 or Newer #!/usr/bin/env python3 # Foundations of Python Network Programming, Third Edition # https://github.com/brandon-rhodes/fopnp/blob/m/py3/chapter06/safe_tls.py # Simple TLS client and server using safe configuration defaults import argparse, socket, ssl def client(host, port, cafile=None): purpose = ssl.Purpose.SERVER_AUTH context = ssl.create_default_context(purpose, cafile=cafile) raw_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) raw_sock.connect((host, port)) print('Connected to host {!r} and port {}'.format(host, port)) ssl_sock = context.wrap_socket(raw_sock, server_hostname=host) while True: data = ssl_sock.recv(1024) if not data: break print(repr(data)) def server(host, port, certfile, cafile=None): purpose = ssl.Purpose.CLIENT_AUTH context = ssl.create_default_context(purpose, cafile=cafile) context.load_cert_chain(certfile) listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM) listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) listener.bind((host, port)) listener.listen(1) print('Listening at interface {!r} and port {}'.format(host, port)) raw_sock, address = listener.accept() print('Connection from host {!r} and port {}'.format(*address)) ssl_sock = context.wrap_socket(raw_sock, server_side=True) ssl_sock.sendall('Simple is better than complex.'.encode('ascii')) ssl_sock.close() if __name__ == '__main__': parser = argparse.ArgumentParser(description='Safe TLS client and server') parser.add_argument('host', help='hostname or IP address') parser.add_argument('port', type=int, help='TCP port number') parser.add_argument('-a', metavar='cafile', default=None, help='authority: path to CA certificate PEM file') parser.add_argument('-s', metavar='certfile', default=None, help='run as server: path to ser…
has title: Python SSL Unknown CA Error
type: UnansweredQuestion

http://stackoverflow.com/comment/88887881
type: Comment
comment on: http://stackoverflow.com/a/50945082
score: 0
type: AnswerComment
has text: My script is working when I call it from a python file like the posted example.

http://stackoverflow.com/comment/88899738
score: 0
type: AnswerComment
has text: Ah! like that. You can use modulo or a dictionary. I will edit the answer
comment on: http://stackoverflow.com/a/50950731
type: Comment

http://stackoverflow.com/q/50966211
score: 0
has title: how to read a list from a text file which is just below some text in python?
answer count: 1
tagged with: python
tagged with: regex
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50966252
type: Question
accepted answer: http://stackoverflow.com/a/50966252
has body: This is a text file from which I have to extract the python list (starting from [{"WW":"WW18" ... ... ) and them perform some operations on that list. how to do this? Verified Title Successfully 6 Title of the graph Firmware Trend Status - AB - WW24.7 Title of the graph with categoryFirmware Trend Status - AB - WW24.7 ###########Firmware Weekly Status Value############ [{"WW":"WW18","Pass":0,"Fail":8,"Notrun":47,"Notready":0,"total":45,"passPerc":0,"runPerc":15},{"WW":"WW19","Pass":0,"Fail":8,"Notrun":47,"Notready":0,"total":25,"passPerc":0,"runPerc":15},{"WW":"WW20","Pass":0,"Fail":8,"Notrun":47,"Notready":0,"total":35,"passPerc":0,"runPerc":15},{"WW":"WW21","Pass":0,"Fail":8,"Notrun":47,"Notready":0,"total":45,"passPerc":0,"runPerc":15},{"WW":"WW22","Pass":0,"Fail":8,"Notrun":47,"Notready":0,"total":55,"passPerc":0,"runPerc":15},{"WW":"WW23","Pass":0,"Fail":8,"Notrun":47,"Notready":0,"total":75,"passPerc":0,"runPerc":15},{"WW":"WW24","Pass":0,"Fail":8,"Notrun":47,"Notready":0,"total":65,"passPerc":0,"runPerc":15},{"WW":"WW25","Pass":0,"Fail":0,"Notrun":0,"Notready":0,"total":0,"passPerc":0,"runPerc":0},{"WW":"WW26","Pass":0,"Fail":0,"Notrun":0,"Notready":0,"total":0,"passPerc":0,"runPerc":0},{"WW":"WW27","Pass":0,"Fail":0,"Notrun":0,"Notready":0,"total":0,"passPerc":0,"runPerc":0},{"WW":"WW28","Pass":0,"Fail":0,"Notrun":0,"Notready":0,"total":0,"passPerc":0,"runPerc":0},{"WW":"WW29","Pass":0,"Fail":0,"Notrun":0,"Notready":0,"total":0,"passPerc":0,"runPerc":0},{"WW":"WW30","Pass":0,"Fail":0,"Notrun":0,"Notready":0,"total":0,"passPerc":0,"runPerc":0}] edit: I tried the following code: import re import ast fo=open(r"D:\Combined2345.txt","r") s=fo.read() data = re.search("\[.*?\]", s) if data: print( ast.literal_eval(data.group())) but it shows error: Traceback (most recent call last): File "D:/com12.py", line 7, in &lt;module&gt; print( ast.literal_eval(data.group())) File "C:\Users\2015s\AppData\Local\Programs\Python\Python36-32\lib\ast.py", line 85, in literal_eval…

http://stackoverflow.com/comment/88914050
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50958316
has text: @user48956 Of course Python 2.7 has no ModuleProxy class. That's why I had to write one in my answer. [You can see it working here.](https://repl.it/repls/ParchedEmbellishedCensorware)

http://stackoverflow.com/a/50938408
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50938167
type: Answer
answers question: http://stackoverflow.com/q/50938167
upvote count: 2
has body: The issue seems to be that ScalarMappable objects seem to be able to have at most one colorbar associated with them. When you draw the second colorbar with the same ScalarMappable, the original colorbar is unlinked and the previous settings are lost for the first colorbar. Your code is missing some details (in particular, the definition of cax), so you either have to create two separate mappables, or directly use what each scatter call gives you. Furthermore, I'd be explicit about where you want to get your colorbars to be inserted. An example fix, assuming that cax was really meant to refer to your scatter plots: import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import numpy as np X = np.random.rand(100) * 40 - 20 Y = np.random.rand(100) * 40 - 20 Z = np.random.rand(100) * 40 - 20 C = np.random.randint(1,8,100) custom_ticks = list('ABCDEFGH') fig = plt.figure(figsize = (20,15)) ax1 = fig.add_subplot(121) sc1 = ax1.scatter(X, Y, c = C, cmap='viridis') # use this mappable ax1.set_title("2D Representation", fontsize = 18) ax1.set_xlabel("TSNE1", fontsize = 14) ax1.set_ylabel("TSNE2", fontsize = 14) ax1.set_xlim(-20,20) ax1.set_ylim(-20,20) ax1.set_xticks(list(range(-20,21,10))) ax1.set_yticks(list(range(-20,21,10))) cbar = fig.colorbar(sc1, ax=ax1, ticks=list(range(0,9))) # be explicit about ax1 cbar.ax.tick_params(labelsize=15) cbar.ax.set_yticklabels(custom_ticks) ax2 = fig.add_subplot(122, projection='3d') sc2 = ax2.scatter(X, Y, Z, c=C, cmap='viridis') # next time use this one ax2.set_title("3D Representation", fontsize = 18) ax2.set_xlabel("TSNE1", fontsize = 14) ax2.set_ylabel("TSNE2", fontsize = 14) ax2.set_zlabel("TSNE3", fontsize = 14) ax2.set_xlim(-20,20) ax2.set_ylim(-20,20) ax2.set_zlim(-20,20) ax2.set_xticks(list(range(-20,21,10))) ax2.set_yticks(list(range(-20,21,10))) ax2.set_zticks(list(range(-20,21,10))) cbar = fig.colorbar(sc2, ax=ax2, ticks=list(range(0,9))) # sc1 here is the bug cbar.ax.tick_params(labelsize=15) cbar.ax.set_yt…
score: 2

http://stackoverflow.com/comment/88810115
comment on: http://stackoverflow.com/q/50904883
has text: Ahh! thanks @ThomWiggers - so I can use: for item in tree.findall('.//{http://schemas.microsoft.com/developer/msbuild/2003}RunCodeAnalysis'): item.text = 'true' and that does what I wanted. Now all I need to do is figure out why it removes the <?xml version="1.0" encoding="utf-8"?> part when I use tree.write() and I can get this script working
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/q/50946258
answer count: 0
has body: i know xml and json are not same and have diffrences but in my job i can convert them and xml contain null true false so my code is : #q = big XML (32000 line) null = "null" true = "true" start_time = time.time() q = eval(dumps(xmltodict.parse(q))) print("--- %s seconds ---" % (time.time() - start_time)) i can't use json.loads because it convert null to None , true to True. after running my program i want to send it back to JavaScript and it cause error. my problem is about RunTime for large xml (not too large just 2Mb) above code print 1.1480658054351807 secs and its very Bad. is there any faster way to to this convertation i don't know which information will help just can say my CPU is intel xeon x5675
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/88893937
type: Question
has comment: http://stackoverflow.com/comment/88893824
upvote count: 3
downvote count: 1
has comment: http://stackoverflow.com/comment/88892064
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88891662
type: UnansweredQuestion
tagged with: python
tagged with: http://stackoverflow.com/tag/xml
has title: fast convert xml to json xml (avoid CPU usage 100 and reduce RunTime)
score: 2
has comment: http://stackoverflow.com/comment/88894143

http://stackoverflow.com/q/51002465
downvote count: 0
tagged with: where-clause
favorite count: 0
has comment: http://stackoverflow.com/comment/88998657
has body: I have this: import numpy as np mol= np.array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20], [21], [22], [23], [24], [25], [26], [27]]) i = np.where(mol == 7) print(i) But it's return (array([], dtype=int64),) Also, if i do i = np.where(mol == 7) It's return the same What's the problem? Thank you!
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/88998937
upvote count: 2
has answer: http://stackoverflow.com/a/51002510
answer count: 1
tagged with: numpy
has title: np.where return an empty array with numpy array in it
accepted answer: http://stackoverflow.com/a/51002510
score: 2
type: AnsweredQuestion

http://stackoverflow.com/comment/88847269
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50911946
has text: But I want to drop the duplicates by date, `res = res.drop_duplicates()` means to drop duplicates in all the days.

http://stackoverflow.com/q/50877281
has title: Filter out all rows in a dataframe containing '**'
has answer: http://stackoverflow.com/a/50877333
favorite count: 0
has answer: http://stackoverflow.com/a/50877342
tagged with: python
has body: I am trying to filter out all rows in a DataFrame that contain the substring '**'. I have tried doing this with df = df[~df['title'].str.contains('**')] However I keep getting an error error: nothing to repeat at position 0 and can't figure out why.
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88756547
tagged with: dataframe
has comment: http://stackoverflow.com/comment/88756564
type: Question
has comment: http://stackoverflow.com/comment/88756549
answer count: 2
has comment: http://stackoverflow.com/comment/88756512
tagged with: series
possible better answer: http://stackoverflow.com/a/50877333
score: 0
tagged with: pandas
upvote count: 1
accepted answer: http://stackoverflow.com/a/50877342
downvote count: 1

http://stackoverflow.com/a/50956404
answers question: http://stackoverflow.com/q/50956309
upvote count: 2
has comment: http://stackoverflow.com/comment/88910515
has comment: http://stackoverflow.com/comment/88910381
has body: The problem is that your format has quotes around the datetimes, plus a leading space: f.write("1, 1, '2018-01-01 10:00:00'\n") But your parser doesn't strip those quotes and space off, and your strptime isn't expecting them. And, while 2018-01-01 10:00:00 would match your format, '2018-01-01 10:00:00' does not. You can solve this in a few ways: Use the csv module for reading (or numpy, since you're already importing it), which will handle CSV quoting and spaces automatically. Do the quote handling manually—e.g., timestamp = columns[2].strip().strip("'"). Add the space and quotes to the strptime format: datetime.strptime(columns[2]," '%Y-%m-%d %H:%M:%S'") The first one seems by far the cleanest, but they'll all work. Of course once you fix that, you're going to have another problem: a.write(','+LogTime-temp) is trying to add a string ',' to a datetime object, and then subtract None from the result. None of those types are compatible, so this makes no sense. If you were trying to diff subsequent times, then you have to: Handle the first row specially, since it has no previous time; Handle the first diff specially too, since it has no preceding ,; Subtract the times to get a timedelta before trying to attach one of them to a string; Either convert the diff to a string with str instead of just adding it to ',', or, maybe better, use an f-string (or format) instead of adding strings. This should be enough to get you started, but it's not the complete program: temp = None for line in a: # ... up to LogTime = ... if temp is not None: diff = LogTime - temp print(diff) temp = LogTime And then you're trying to write to the file at the same time you're reading it, which is just going to make a horrible mess. You'll read one line, then overwrite the next line—or, more likely, half the next line, or the next two and a third lines, or whatever, then read the next line after that… What you want to do is one of: Write to a different file (you can os.replace it over the original on…
has comment: http://stackoverflow.com/comment/88910501
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/88910503
score: 2

http://stackoverflow.com/a/50982027
answers question: http://stackoverflow.com/q/50981906
upvote count: 2
score: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/88960978
has body: When initializing logger specify location where you want your logs to be saved. logging.config.fileConfig('logging.config', defaults={'yourlogfile': '/path/to/log/file'})
type: Answer

http://stackoverflow.com/comment/89025379
comment on: http://stackoverflow.com/q/50898333
has text: But, as the question was how to get a single average color from each sample, I should accept @mark-ransom's answer. Thanks for your help anyways.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50965660
downvote count: 0
has answer: http://stackoverflow.com/a/50968301
has comment: http://stackoverflow.com/comment/88932751
has comment: http://stackoverflow.com/comment/88940062
tagged with: pandas
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50968316
has comment: http://stackoverflow.com/comment/88932629
has title: How to loop through lists from pandas dataframe in a function
score: 1
has comment: http://stackoverflow.com/comment/88933431
favorite count: 0
tagged with: nested-lists
type: Question
has comment: http://stackoverflow.com/comment/88933479
answer count: 3
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/88932579
has comment: http://stackoverflow.com/comment/88933246
has answer: http://stackoverflow.com/a/50971726
has comment: http://stackoverflow.com/comment/88939995
has comment: http://stackoverflow.com/comment/88966706
has comment: http://stackoverflow.com/comment/88932141
has body: Here is my dataframe, df = pd.DataFrame({'Id': [102,103,104,303,305],'ExpG_Home':[1.8,1.5,1.6,1.8,2.9], 'ExpG_Away':[2.2,1.3,1.2,2.8,0.8], 'HomeG_Time':[[93, 109, 187],[169], [31, 159],[176],[16, 48, 66, 128]], 'AwayG_Time':[[90, 177],[],[],[123,136],[40]]}) First, I need to create an array y, for a given Id number, it takes values from same row (ExpG_Home &amp; ExpG_Away). y = [1 - (ExpG_Home + ExpG_Away), ExpG_Home, ExpG_Away] Second, I found this much harder, for the Id used in creating y, the function below takes the corresponding lists from HomeG_Time &amp; AwayG_Time and creates an array. Unfortunately, my function takes one row at a time. I need to do this for a large dataset. x1 = [1,0,0] x2 = [0,1,0] x3 = [0,0,1] total_timeslot = 200 # number of timeslot per game. k = 1 # constant #For Id=102 with ExpG_Home=2.2 and ExpG_Away=1.8 HomeG_Time = [93, 109, 187] AwayG_Time = [90, 177] y = np.array([1-(2.2 + 1.8)/k, 2.2/k, 1.8/k]) # output of y = [0.98 , 0.011, 0.009] def squared_diff(x1, x2, x3, y): ssd = [] for k in range(total_timeslot): if k in HomeG_Time: ssd.append(sum((x2 - y) ** 2)) elif k in AwayG_Time: ssd.append(sum((x3 - y) ** 2)) else: ssd.append(sum((x1 - y) ** 2)) return ssd sum(squared_diff(x1, x2, x3, y)) Out[37]: 7.880400000000012 This output is for the first row only.
accepted answer: http://stackoverflow.com/a/50971726
possible better answer: http://stackoverflow.com/a/50968301

http://stackoverflow.com/comment/88889933
has text: @bhupathituraga This is also not located and there are two buttons next to one another: Read and New and I need to click New so I think even if it had located the button-read it wouldn't have helped me
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50946084
type: QuestionComment

http://stackoverflow.com/q/50893067
has body: I have a list of Unix timestamps that I want to convert into UTC time: times = [..., "1371605102000", "1375245962000", ...] However, these times are in milliseconds. I tried this code: from datetime import datetime import tzlocal unix_timestamp = float("1371605102000") local_timezone = tzlocal.get_localzone() local_time = datetime.fromtimestamp(unix_timestamp, local_timezone) print(local_time.strftime("%B %d %Y")) But it threw up this error: Traceback (most recent call last): File "temp.py", line 6, in &lt;module&gt; local_time = datetime.fromtimestamp(unix_timestamp, local_timezone) ValueError: year 45434 is out of range I feel like it has to do with the fact that the timestamp is in milliseconds, but I'm not entirely sure. Other than that, I was also wondering if there was a way to format the dates to something like this: ... Jan 04, 2017 Oct 27, 2016 ... Rather than this: ... January 4, 2017 October 27, 2016 ....
type: Question
has comment: http://stackoverflow.com/comment/88786671
linked to: http://stackoverflow.com/q/6999726
score: 0
has comment: http://stackoverflow.com/comment/88786668
tagged with: unix
tagged with: unix-timestamp
tagged with: python-3.x
answer count: 0
has comment: http://stackoverflow.com/comment/88786653
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/21787496
tagged with: python
has comment: http://stackoverflow.com/comment/88786677
duplicate of: http://stackoverflow.com/q/6999726
has title: convert unix timestamp in milliseconds to UTC time & date formatting python3

http://stackoverflow.com/q/50863660
has comment: http://stackoverflow.com/comment/88729971
has answer: http://stackoverflow.com/a/50870090
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/50863723
favorite count: 0
has comment: http://stackoverflow.com/comment/88741562
score: 0
has comment: http://stackoverflow.com/comment/88729844
tagged with: python
linked to: http://stackoverflow.com/q/37891188
has title: Can PyCharm highlight Python 2 specific code to enable migration?
has comment: http://stackoverflow.com/comment/88729896
tagged with: pycharm
has comment: http://stackoverflow.com/comment/88762343
upvote count: 1
possible better answer: http://stackoverflow.com/a/50863723
downvote count: 1
accepted answer: http://stackoverflow.com/a/50870090
has comment: http://stackoverflow.com/comment/88741654
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88762411
has body: I'm working with a large Python 2 code base, which should be prepared to move to Python 3 some time in the future. I was wondering if there are any ways in PyCharm to highlight parts, which would not run in Python 3, e.g. usages of print 'abc' should be highlighted. I'm not looking for an automated way to transform the code, but I just want to get aware of problematic areas as a first step.
has comment: http://stackoverflow.com/comment/88730054

http://stackoverflow.com/comment/88968958
type: Comment
comment on: http://stackoverflow.com/q/50969167
has text: Apologies for the lack of clarity, to put it simply what complex exponential do I multiply sine_sig = np.sin(2 * np.pi * freq * t_arr) to sweep the sine_sig from freq - sweep_start to freq + sweep_finish
score: 0
type: QuestionComment

http://stackoverflow.com/a/71762684
type: Answer
answers question: http://stackoverflow.com/q/50876784
score: 0
has body: You have to change the input source for sh command from stdin to the input argument of string type: container.exec_run(['sh', '-c', 'echo 123 &gt; /var/abc.txt'])

http://stackoverflow.com/a/50980710
upvote count: 1
has body: This Should Help import time #use a While loop While True: #request said user input x= input("Please Press 1 to continue Or 2 to Exit") #then an if statement if x==1: #call your function printit() time.sleep(5) else:break This should Do the trick
answers question: http://stackoverflow.com/q/50980461
downvote count: 0
type: Answer
score: 1

http://stackoverflow.com/a/50932157
has body: There are two problems with the solution you've tried: chain is not guaranteed to be present and chain is a list of dictionaries and you are treating it as a single dictionary Hopefully the following does what you want it to do: def gen_dict_extract(key, input_dic): rv = { input_dic[key]: input_dic["score1"] + input_dic["score2"], "depth": input_dic["depth"], } if "chain" in input_dic: rv["chain"] = [gen_dict_extract(key, x) for x in input_dic["chain"]] return rv
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88869745
answers question: http://stackoverflow.com/q/50877322
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50877322
score: 1

http://stackoverflow.com/comment/88802442
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50901296
type: QuestionComment
has text: `inventory['gold'] = [n + 50 for n in inventory['gold']]`?

http://stackoverflow.com/q/50922579
tagged with: image-processing
has comment: http://stackoverflow.com/comment/88865945
type: Question
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/88866451
has body: I have segmented a medical image into two classes, namely class 1 (epidermis of the skin) and class 2 (dermis of the skin). I want to detect if there is any class 2 (dermis of the skin) trapped inside or completely surrounded by class 1 (epidermis of the skin). Is there any image processing library function or numpy function which can help me achieve this? If anyone knows any other logic using using numpy fucntions please share that too.
has comment: http://stackoverflow.com/comment/88955120
has comment: http://stackoverflow.com/comment/88866652
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
tagged with: opencv
score: 1
has comment: http://stackoverflow.com/comment/88879600
has title: Trapped region in segmented image
has comment: http://stackoverflow.com/comment/88961914

http://stackoverflow.com/q/50944627
accepted answer: http://stackoverflow.com/a/51007641
has title: Image resize not working on PhotoImage in tkinter
tagged with: image
type: Question
has body: I am trying to make a code to display smaller wind vector images over a Map background image. The only problem is that the wind vectors are larger than required and I want to scale them down. I tried subsample() but it doesn't work for some reason and the image remains of same size. The preliminary code for this is as follows; from tkinter import * root = Tk() root.title("Click me!") def next_image(event): #toggle between image2 and image3 global toggle_flag global x, y, photo2, photo3 if toggle_flag == TRUE: # display photo2, same center x, y canvas1.create_image(x, y, image=photo2) toggle_flag = False else: canvas1.create_image(x, y, image=photo3) toggle_flag = True toggle_flag = True # pick three GIF image files you have in your working directory # image1 is larger than image2 and image3 image1 = "Map.png" photo1 = PhotoImage(file=image1) image2 = "icons8-wind-speed-43-47-50.png" photo2 = PhotoImage(file=image2) photo2.subsample(50) image3 = "icons8-wind-speed-103-107-50.png" photo3 = PhotoImage(file=image3) photo3.subsample(50) # make canvas the size of image1/photo1 width1 = photo1.width() height1 = photo1.height() canvas1 = Canvas(width=width1, height=height1) canvas1.pack() # display photo1, x, y is center (anchor=CENTER is default) x = (width1)/2.0 y = (height1)/2.0 canvas1.create_image(x, y, image=photo1) canvas1.bind('&lt;Button-1&gt;', next_image) # bind left mouse click root.mainloop() I am using Python 3.6 on Windows 10 and the default tkinter package. Please help. The output looks like this;
answer count: 1
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/51007641
tagged with: python
favorite count: 0
tagged with: python-3.x
tagged with: tkinter
has comment: http://stackoverflow.com/comment/88912964
upvote count: 1
type: AnsweredQuestion

http://stackoverflow.com/a/66010600
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50866057
has body: Perhaps this help to do it in a clear way and for other cases too: from pyspark.sql.functions import col from pyspark.sql.types import IntegerType def fromBooleanToInt(s): &quot;&quot;&quot; This is just a simple python function to move boolean to integers. &gt;&gt;&gt; fromBooleanToInt(None) &gt;&gt;&gt; fromBooleanToInt(True) 1 &gt;&gt;&gt; fromBooleanToInt(False) 1 &quot;&quot;&quot; if s == True: return 1 elif s==False: return 0 else: return None This is to create a simple dataframe to test df_with_doubles = spark.createDataFrame([(True, False), (None,True)], ['A', 'B']) df_with_doubles.show() +----+-----+ | A| B| +----+-----+ |true|false| |null| true| +----+-----+ This is to define the udf fromBooleanToInt_udf = F.udf(lambda x: fromBooleanToInt(x), IntegerType()) Now let do the casting/transformation: column_to_change = 'A' df_with_doubles_ = df_with_doubles.withColumn(column_to_change,fromBooleanToInt_udf(df_with_doubles[column_to_change])) df_with_doubles_.show() +----+-----+ | A| B| +----+-----+ | 1|false| |null| true| +----+-----+

http://stackoverflow.com/comment/88980400
type: Comment
has text: @Finfa811 yes, I'm able to work on it. I don't understand why you're having errors. I too used the python code example.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50986971

http://stackoverflow.com/q/50977195
type: Question
answer count: 2
score: 2
downvote count: 0
has answer: http://stackoverflow.com/a/50994789
has body: Do Bokeh Servers have the capability to autoreload whenever changes are made to the source? Capability in a similar fashion to Django's autoreload in development mode.
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
has title: Bokeh Servers Autoreload
tagged with: bokeh
has answer: http://stackoverflow.com/a/73980852

http://stackoverflow.com/q/50890074
has title: Replace value in dataframe column, if other 'better' value exists elsewhere
tagged with: python
type: AnsweredQuestion
score: 3
tagged with: dataframe
possible better answer: http://stackoverflow.com/a/50890530
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/50890167
accepted answer: http://stackoverflow.com/a/50890167
has body: I have a dataframe structured roughly as follows (it's a list of event participants; the pool is small enough that we can assume that a repeating value refers to the same person): id_1 id_2 id_3 ... year name country 1_c 2_a 3_a 2011 John France 1_b 2_a 3_c 2010 Jill UK 1_c 2_b 3_c 2018 John Germany 1_c 2_b 3_c 2014 Jason Italy 1_c 2_b 3_b 2017 John Unknown The aim is to replace the 'Unknown' values with the a country name, if that person has a known country from their participation in another year. In the extremely unlikely event that they're listed under different countries in different years, I'm happy to just tag them under whichever country they were listed under in the year closest to the 'Unknown' year (so above, we would change 'Unknown' to 'Germany' for John). I'm a complete pandas (and python!) novice. I've created a list of unique name/country pairs using drop_duplicates, but I'm assuming there must be a much more elegant way to do the rest than the mess of list, tuple and dict conversions I'm currently knee deep in.
downvote count: 0
tagged with: python-2.7
upvote count: 3
tagged with: pandas
favorite count: 0
has answer: http://stackoverflow.com/a/50890530

http://stackoverflow.com/comment/88735140
type: Comment
score: 1
type: QuestionComment
has text: I'd say example one is just really bad practice. Don't do that and be careful with the code where you found it. In Python, we have a saying that explicit is better than implicit, example one breaks that principle, severly.
comment on: http://stackoverflow.com/q/50866336

http://stackoverflow.com/comment/88794114
has text: So did it help!?
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50890923

http://stackoverflow.com/a/50866777
downvote count: 0
has comment: http://stackoverflow.com/comment/88736405
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/88736546
score: 1
has body: one solution would be to use groupby to group consecutive Player scores from the same player tup = [('Player1', 'A', 1, 100),('Player1', 'B', 15, 100),('Player2', 'A', 7, 100), ('Player2', 'B', 65, 100), ('Global Total', None, 88, 100)]` then import our groupby from itertools import groupby result = dict((name,dict((x[1],x[2:]) for x in values)) for name,values in groupby(tup,lambda x:x[0])) then just go and update all the totals for key in result: if key == "Global Total": continue # skip this one ... # sum up our player scores result[key]['total'] = [sum(col) for col in zip(*result[key].values())] # you can print the results too print result # {'Player2': {'A': (7, 100), 'total': [72, 200], 'B': (65, 100)}, 'Player1': {'A': (1, 100), 'total': [16, 200], 'B': (15, 100)}, 'Global Total': {'total': [88, 100], None: (88, 100)}} NOTE This solution !REQUIRES! that all of player1's scores are grouped together in your tuple, and all of player2's scores are grouped etc
answers question: http://stackoverflow.com/q/50866385

http://stackoverflow.com/q/50988346
has body: I'm very new to python so I'm unsure about this. My ideal goal is to have a list that has the first element be a length of 30 composed of a random combination of 0/1's and also in that same list have elements 1-29 be a length of 5 composed of a random combination of 0/1's. Therefore, having a list that is 30 elements long. However, I can't seem to wrap my head around how to accomplish this. I tried appending the 1-29 to the first element but that just made a longer list. Ideally, I'd like it to look something similar to list = [ 30 random zero/one's here, then 29 more elements with a length of 5 composed of random zero/one's] Any help is greatly appreciated. Thank you, Pck
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88971534
has comment: http://stackoverflow.com/comment/88971485
favorite count: 0
has answer: http://stackoverflow.com/a/50988494
type: Question
has comment: http://stackoverflow.com/comment/88971603
answer count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/88971349
possible better answer: http://stackoverflow.com/a/50988534
has answer: http://stackoverflow.com/a/50988534
score: 0
has comment: http://stackoverflow.com/comment/88971408
upvote count: 1
accepted answer: http://stackoverflow.com/a/50988494
downvote count: 1
has comment: http://stackoverflow.com/comment/88971623
has comment: http://stackoverflow.com/comment/88971377
has title: Python different sized elements

http://stackoverflow.com/comment/88790569
has text: Updated my answer
type: Comment
comment on: http://stackoverflow.com/a/50895154
type: AnswerComment
score: 0

http://stackoverflow.com/a/50973538
has body: SQLAlchemy doesn't directly expose the 'where' clause part of a select; not all SELECT statements have one, after all. In addition, the clause can become rather complex. Personally, I'd only test the expressions in an integration test, and only to make sure the correct data is returned. SQLAlchemy does give you tools to visit the object tree, albeit somewhat underdocumented. You could use this to extract any comparisons from the tree, so &lt;left&gt; &lt;op&gt; &lt;right&gt; expressions where left and right are columns elements: from sqlalchemy.sql import visitors, ColumnElement def comparison_visitor(expr, callback): """Finds all binary operators, and calls callback(op, left, right)""" def visit_binary(op): callback(op, op.left, op.right) # visit each expr element, but for select clauses, ignore the column collection visitors.traverse(expr, {'column_collections': False}, {'binary': visit_binary}) visitors.traverse() traverses any SQLAlchemy expression (by repeatedly calling the ColumnClause.get_children() method of the objects, passing in the mapping given as the second argument to traverse()), and calls the function that matches the __visit_name__ attribute of each object. BinaryClause objects have binary as the visit name. You can then use this to test if specific conditions are present: from sqlalchemy.sql import operators from sqlalchemy.sql.expressions import BindParameter from sqlalchemy.sql.schema import Column def test_where(self): where = add_test_col1_where_clause(create_test_select(), 'foo bar') def test_comparison(op, left, right): self.assertIs(op.operator, operators.eq) # == test self.assertIsInstance(left, Column) # between the col_1 column self.assertEq(left.name, 'col_1') self.assertIsInstance(right, BindParameter) # and a parameter self.assertEq(right.value, 'foo bar') # with value 'foo bar' comparison_visitor(where, test_comparison)
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50972149
answers question: http://stackoverflow.com/q/50972149
score: 5
type: AcceptedAnswer
upvote count: 5
type: Answer

http://stackoverflow.com/q/50966768
type: Question
has answer: http://stackoverflow.com/a/50966836
score: 0
has body: But when i run command sudo apt-get install python3-pip. It is installed but inot as python3.6. It is installed in python3.5.I have also specified the version in command i.e sudo apt-get install python3.6-pip.But it gives me an error. Reading package lists... Done Building dependency tree Reading state information... Done E: Unable to locate package python3.6-pip E: Couldn't find any package by glob 'python3.6-pip' E: Couldn't find any package by regex 'python3.6-pip'
answer count: 4
type: UnansweredQuestion
has title: I want to install pip for python3.6. When i allready have another version of python3 is installed.
tagged with: pip
tagged with: python
has answer: http://stackoverflow.com/a/50967064
has answer: http://stackoverflow.com/a/50967592
has answer: http://stackoverflow.com/a/63793923

http://stackoverflow.com/q/51009450
answer count: 1
has answer: http://stackoverflow.com/a/51009517
tagged with: python
has comment: http://stackoverflow.com/comment/89011547
type: AnsweredQuestion
type: Question
accepted answer: http://stackoverflow.com/a/51009517
has body: I have this code import urllib.request fw = open("myfile.txt", "r") red = fw.read() line = red.split("\n") blue = line.split("@")[0] i=0 while i&lt;len(blue): try: try code is here try: try code is here except: print(blue[i] + " is " + "having e1") except: print(blue[i] + " is " + "having e2") i+=1 I am getting Errno 2 No Such File or Directory when I try to run my file. However, when I remove the line blue = line.split("@") it works fine. What I want to do is to repeat this code on all the lines of myfile.txt - so I split \n first to get one line of the file then I want to get the characters before @ in this line and put it in the string blue I can't understand why it work when I remove blue = line.split("@") Any help would be appreciated.
score: 0
has title: Errno 2 No Such File or Directory on 2 splits

http://stackoverflow.com/a/50993297
answers question: http://stackoverflow.com/q/50993194
downvote count: 0
type: AcceptedAnswer
upvote count: 2
type: Answer
has body: You would remove the last one fig, ax = plt.subplots(2,2) ax[1,1].remove()
accepted answer of: http://stackoverflow.com/q/50993194
score: 2

http://stackoverflow.com/comment/88876937
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50938424
has text: Wasn't aware of dateutil model until now. It worked!! Thank you so much

http://stackoverflow.com/q/50938421
has body: I am using Conda to run a virtual environment (python version 3.6.5). I am fairly new to coding so please bear with me. I am trying to from p5 import * However this is returning the following error. . . (VisCoding) C:\Users\Taha Arif\Desktop\VisCoding&gt;python intro.py Traceback (most recent call last): File "intro.py", line 9, in &lt;module&gt; from p5 import * ModuleNotFoundError: No module named 'p5' After activating my virtualenv, I performed pip install p5 It ran and installed them to my virtualenv. I can see p5 when i run pip list. Can someone provide an explanation on how I can point python to the direction of the p5 module? Please provide insight as to what python does when looking for a module. Thanks! I am running Windows 10.
tagged with: python
has comment: http://stackoverflow.com/comment/88875343
answer count: 0
tagged with: pip
upvote count: 1
type: Question
tagged with: virtual-environment
downvote count: 0
has comment: http://stackoverflow.com/comment/88875157
score: 1
linked to: http://stackoverflow.com/q/3701646
tagged with: windows-10
has title: pip install worked, but module is still not found, Virtual Environment
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/88776180
type: QuestionComment
score: 0
has text: @abarnert I understood now sorry for misunderstanding before. Best explaination by the way.
comment on: http://stackoverflow.com/q/50884426
type: Comment

http://stackoverflow.com/q/50918071
downvote count: 1
has comment: http://stackoverflow.com/comment/88849154
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88847612
has comment: http://stackoverflow.com/comment/88930404
has title: Can't reach the bottom of a webpage
possible better answer: http://stackoverflow.com/a/50920821
tagged with: python
has comment: http://stackoverflow.com/comment/88849452
tagged with: selenium-webdriver
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50968161
has comment: http://stackoverflow.com/comment/88848888
accepted answer: http://stackoverflow.com/a/50968161
tagged with: selenium
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/88844668
type: Question
has comment: http://stackoverflow.com/comment/88930495
has comment: http://stackoverflow.com/comment/88849296
has answer: http://stackoverflow.com/a/50920821
has comment: http://stackoverflow.com/comment/88931193
has body: I've written a script in python with selenium to handle the infinite scrolling webpage. The problem I'm facing is that It scrolls few times then quits the browser. It never reaches the bottom. I tried with Explicit Wait as well but that gives even fewer scrolling. How can I reach the bottom when there will be no more scrolling to do. This is my try: import time from selenium import webdriver from urllib.parse import urljoin url = "https://www.instagram.com/explore/tags/travelphotoawards/" driver = webdriver.Chrome() driver.get(url) last_len = len(driver.find_elements_by_css_selector(".v1Nh3 a")) new_len = last_len while True: last_len = new_len driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") time.sleep(5) items = driver.find_elements_by_css_selector(".v1Nh3 a") new_len = len(items) if last_len == new_len:break driver.quit() Edit: If I try like below, I can do the scrolling as many times as I want but that is not a good idea to cope with: import time from selenium import webdriver from selenium.webdriver.common.keys import Keys url = "https://www.instagram.com/explore/tags/travelphotoawards/" driver = webdriver.Chrome() driver.get(url) for scroll in range(1,10): #I can do the scrolling as many times as I want but it is fully hardcoded item = driver.find_element_by_tag_name("body") item.send_keys(Keys.END) elems = driver.find_elements_by_css_selector(".v1Nh3 a") time.sleep(3) driver.quit() I hope there is any way to do the scrolling automatically until it reaches the bottom.
score: 0
answer count: 2
upvote count: 1

http://stackoverflow.com/comment/88824870
comment on: http://stackoverflow.com/a/50911382
type: Comment
has text: @Elena to achieve the desired order, I've replaced `d.apply(tuple, axis=1)` with `d.apply(lambda x: list(x)[::-1], axis=1)`
type: AnswerComment
score: 0

http://stackoverflow.com/comment/88840314
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50920203
has text: I got 4. For the 4 logical cores I guess

http://stackoverflow.com/a/50893460
has body: Your question isn't very clear, but you'll likely want the exec() function which can execute external programs. Here's the documentation http://php.net/manual/en/function.exec.php
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50893404

http://stackoverflow.com/q/50897213
has body: I am trying to webscrape google search results using python and beautifulsoup. In my first program I'm just trying to get all links on the search result page. Ultimately what I want to do is follow the links to other websites and then scrape those websites. The problem is when I'm looking at the links my program is giving me they are not pointing to the correct url. For example the first website url after searching "what is python" in google is is 'https://www.python.org/doc/essays/blurb/' however my program is giving me '/url?q=https://www.python.org/doc/essays/blurb/&amp;sa=U&amp;ved=0ahUKEwirv7mZzNnbAhXD5YMKHdl0AFsQFggUMAA&amp;usg=AOvVaw3Q2RD0gl-X3BiEJ-5HIxmF' Reviewing the BeautifulSoup documentation I am expecting output similar to their example: for link in soup.find_all('a'): print(link.get('href')) # http://example.com/elsie # http://example.com/lacie # http://example.com/tillie Instead I am getting a preceding '/url?q=' and lots of unpexcted characters after the website address. Can someone someone explain why I am not getting the expected output? Here is my code: import requests from bs4 import BeautifulSoup search_item = 'what is python' url = "https://www.google.ca/search?q=" + search_item response = requests.get(url) soup = BeautifulSoup(response.text, "lxml") for link in soup.find_all('a'): print(link.get('href'))
possible better answer: http://stackoverflow.com/a/69140346
linked to: http://stackoverflow.com/q/45468005
tagged with: web-scraping
accepted answer: http://stackoverflow.com/a/51275915
has title: not getting correct url beautifulsoup python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88794149
has answer: http://stackoverflow.com/a/51275915
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/88794305
tagged with: beautifulsoup
score: 0
has answer: http://stackoverflow.com/a/69140346
tagged with: python

http://stackoverflow.com/comment/88726899
score: 0
type: AnswerComment
type: Comment
has text: or python3 style `variable='vjk' compare="end {0}".format(variable) string.index(compare)`
comment on: http://stackoverflow.com/a/50862190

http://stackoverflow.com/q/50865482
has body: I have used scipy griddata to interpolate with polar data. I have a file with azimuth, altitude, and a value. First, I converted azimuth and altitude to Cartesian coordinates to use with griddata. I then create steps from 0 to 90 for altitude and 0 to 360 for azimuth. alt = np.array(alt) x,y = alt * np.cos(az), alt*np.sin(az) xi = np.linspace(0, 90, 100) yi = np.linspace(np.radians(10.), np.radians(350.), 100) zi = griddata((x, y), value, (xi[None,:], yi[:,None]), method='cubic') ax = plt.subplot(111, projection='polar') cm = plt.cm.get_cmap('jet_r') levels = np.linspace(min(value),max(value), 100) cf = plt.contourf(yi,90-xi,zi.T,levels=levels,cmap=cm) cbar = plt.colorbar() cbar.set_ticks(np.arange(15.5,22, .5)) cbar.set_label(r'mag/arcsec$^2$') ax.set_theta_zero_location('N') ax.set_theta_direction(-1) ax.yaxis.grid(False) #ax.set_rticks([]) ax.scatter(az,90-alt, marker='.', edgecolors='k', facecolors='none') ax.xaxis.grid(False) plt.ylim(0,90) plt.show() I cannot agree with what was returned for griddata. For example, the data point (the black dots) at 225 at the lowest altitude is 16.5 mags/arcsec^2. Griddata returned a value around 18.5 mag/arcsec^2 for that area. My other issue is how bad the interpolation is at azimuth 350-10. It does not blend well. See below: I changed the range from 10 to 350 to get: Which I am happier with, but I would like to fill in the keyhole in the plot. Any help filling in the keyhole is greatly appreciated. As well as how to improve the griddata results. I also do not agree with the polar plot rotation and data mapping. I believe there is some errors there, but that is for another post.
tagged with: matplotlib
type: UnansweredQuestion
answer count: 0
downvote count: 0
score: 1
favorite count: 0
tagged with: polar-coordinates
type: Question
tagged with: python
tagged with: interpolation
has title: Issues with scipy interpolate griddata polar coordinates
upvote count: 1
has comment: http://stackoverflow.com/comment/88734369

http://stackoverflow.com/comment/108493043
comment on: http://stackoverflow.com/a/50955461
score: 0
type: AnswerComment
has text: We're planning to add this functionality for Spyder 5, to be released in 2021.
type: Comment

http://stackoverflow.com/comment/88928359
comment on: http://stackoverflow.com/q/50965902
type: Comment
type: QuestionComment
score: 2
has text: You are getting the error because when the program tries to rename the second file as `1.jpg` it will fail with the error file is already avaialble

http://stackoverflow.com/comment/88805813
comment on: http://stackoverflow.com/q/50902981
score: 0
type: Comment
type: QuestionComment
has text: What type is `data`? Your manipulation of the array dtype looks extremely suspicious

http://stackoverflow.com/comment/88915197
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50954883
type: Comment
has text: Does your file have a blank line after each of the two lines that you want to remove? Your example does not make that clear and you did not say. If so, you probably want to remove *two* lines after the date/time line. That can be done by changing the flag variable `skiplines` from a Boolean to an integer: start it at 2 and count down to 0. If you just want to remove blank lines at the top of the file, another Boolean flag variable could take care of that. If you give more details about your files I can give more details about a solution.

http://stackoverflow.com/a/50984097
upvote count: 1
answers question: http://stackoverflow.com/q/50978894
accepted answer of: http://stackoverflow.com/q/50978894
has body: You can use the singleton encoding function provided by Keras directly. Something like this: import numpy as np from keras.utils import np_utils y_train_label = [7,4,11,11,14] y_train_label_onehot = np_utils.to_categorical(y_train_label) print('one_hot:',y_train_label_onehot) The results：
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 1

http://stackoverflow.com/q/50893146
type: Question
has answer: http://stackoverflow.com/a/50893336
has body: I have a bunch of float values, for example: x1 = 1.11111111 x2 = 2.22222222 I want to write these values to a file: f = open("a.dat", "w+") f.write("This is x1: ",x1) f.write("\n") #I want to separate the 2 lines f.write("This is x2: ",x2) At this point I got an error on the second line: write() takes exactly one argument (2 given) How do I write to file such that when I open it, I see this format: This is x1: 1,1111111 This is x2: 2,2222222 And yes, the file has to be ***.dat It's not .txt
upvote count: 5
has answer: http://stackoverflow.com/a/50893178
tagged with: python-3.6
has answer: http://stackoverflow.com/a/50893202
accepted answer: http://stackoverflow.com/a/50893178
favorite count: 0
has answer: http://stackoverflow.com/a/50893199
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/50893202
has comment: http://stackoverflow.com/comment/88786726
has title: What is the correct format to write float value to file in Python
tagged with: python
answer count: 4
score: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88786735
has comment: http://stackoverflow.com/comment/88786727
has comment: http://stackoverflow.com/comment/88786721
downvote count: 1

http://stackoverflow.com/comment/88871029
comment on: http://stackoverflow.com/q/50934443
has text: Possible duplicate of [Execute multiple batch files concurrently and monitor if their process is completed](https://stackoverflow.com/questions/43754374/execute-multiple-batch-files-concurrently-and-monitor-if-their-process-is-comple) or [How to wait all batch files to finish before exiting?](https://stackoverflow.com/questions/33584587/how-to-wait-all-batch-files-to-finish-before-exiting)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50990042
has title: Create single CSV from two CSV files with X and Y values in python
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/50990218
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
tagged with: geo
type: AnsweredQuestion
tagged with: list
has body: I have two CSV files; one containing X(longitude) and the other Y(latitude) values (they are 'float' data type) I am trying to create a single CSV with all possible combinations (e.g. X1,Y1; X1, Y2; X1,Y3; X2,Y1; X2,Y2; X2,Y3... etc) I have written the following which partly works. However the CSV file created has lines in between values and i also get the values stored like this with there list parentheses ['20.7599'] ['135.9028']. What I need is 20.7599, 135.9028 import csv inLatCSV = r"C:\data\Lat.csv" inLongCSV = r"C:\data\Long.csv" outCSV = r"C:\data\LatLong.csv" with open(inLatCSV, 'r') as f: reader = csv.reader(f) list_Lat = list(reader) with open(inLongCSV, 'r') as f: reader = csv.reader(f) list_Long = list(reader) with open(outCSV, 'w') as myfile: for y in list_Lat: for x in list_Long: combVal = (y,x) #print (combVal) wr = csv.writer(myfile) wr.writerow(combVal)
score: 1
possible better answer: http://stackoverflow.com/a/50990491
upvote count: 1
has answer: http://stackoverflow.com/a/50990491
accepted answer: http://stackoverflow.com/a/50990218
type: Question
answer count: 2

http://stackoverflow.com/comment/88750677
comment on: http://stackoverflow.com/q/50874618
score: 0
type: Comment
type: QuestionComment
has text: Do you want to modify such probabilities in each row, in order to reproduce a more gaussian-like distribution?

http://stackoverflow.com/comment/88912247
type: QuestionComment
has text: @BowlingHawk95 _"...(to which I'd ask why you're writing it in python)..."_ I am using the tools I have available.
comment on: http://stackoverflow.com/q/50956798
score: 0
type: Comment

http://stackoverflow.com/q/50917310
tagged with: mailgun
has body: Consider the following settings.py snippet from https://github.com/anymail/django-anymail: INSTALLED_APPS = [ # ... "anymail", # ... ] ANYMAIL = { # (exact settings here depend on your ESP...) "MAILGUN_API_KEY": "&lt;your Mailgun key&gt;", "MAILGUN_SENDER_DOMAIN": 'mg.example.com', # your Mailgun domain, if needed } EMAIL_BACKEND = "anymail.backends.mailgun.EmailBackend" # or sendgrid.EmailBackend, or... DEFAULT_FROM_EMAIL = "you@example.com" # if you don't already have this in settings In this example, both the MAILGUN_SENDER_DOMAIN and DEFAULT_FROM_EMAIL have the domain example.com. We've recently made a change such that the two domains are different, and it seems that I am no longer able to send emails using the AnyMail backend. My theory is that MailGun 'enforces' the two domains to be the same, but it is not clear to me from the documentation whether this is indeed the case. Can anyone confirm whether this is required?
has answer: http://stackoverflow.com/a/50917545
tagged with: django-anymail
has title: With Django AnyMail with MailGun, does the MAILGUN_SENDER_DOMAIN have to match the domain in the DEFAULT_FROM_EMAIL?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50917545
tagged with: python
type: Question
score: 0
tagged with: django
answer count: 1

http://stackoverflow.com/a/50958140
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50957744
has body: The closure captures are just a distraction here, and so is handling 90 and ss in different ways,1 so let's throw all of that out and just solve the problem you're struggling with. First, you want a function that does one thing if called with an argument, and a different thing if called without an argument. That's easy; just use a parameter with a default value, or use *args. Second, the "different thing" you want to do is to return a function that recursively does the same thing as your function, except for sticking an extra 'o' in the result. When defining a recursive data structure—whether it's a recursive closure, or a recursive defaultdict, the easiest way to do it is usually to use recursion. For example: def foo(x=None, *, _chain=0): if x is None: def bar(*args): return foo(*args, _chain=_chain+1) return bar else: return 'f' + 'o'*_chain + x You could rewrite bar as a decorator, and return bar(foo), but that seems unnecessary. It wouldn't change the fact that the key here is that foo returns a function that calls foo. 1. If you don't know how to do that, just if isinstance(x, str):. Or, if you want to get fancy, look up functools.singledispatch.
has comment: http://stackoverflow.com/comment/88914218
has comment: http://stackoverflow.com/comment/88914577
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50957744

http://stackoverflow.com/q/51003389
has body: I have a list of m elements and n different numbers that appear in a list of strings. The list follows the following format example eq = ['12', '2', '3', '-123', '-1', 'X'] Note, X represents the constant 1, other than the variable 1. I want to be able to convert this to a lambda function that takes in a list x and acts like this list was summed together. For our example the function would be f(x) = x[1]*x[2] + x[2] + x[3] - x[1]*x[2]*x[3] - x[1] + 1 I know how to do this with a normal function, but I wanted to get it to work with a lambda and hit a wall. Any help would be appreciated! Here is the function that works for the problem: def evaluateList(x, lst): num = 0 for term in lst: if term[0] == "X": num += 1 elif term[0] == "-": num -= reduce(lambda x,y: x*y, [x[int(y)-1] for y in term[1:]]) else: num += reduce(lambda x,y: x*y, [x[int(y)-1] for y in term]) return num
has title: Creating a Python lambda function from a string sequence
has comment: http://stackoverflow.com/comment/89000391
answer count: 4
has answer: http://stackoverflow.com/a/51003651
score: 2
tagged with: function
downvote count: 0
type: UnansweredQuestion
tagged with: string
has comment: http://stackoverflow.com/comment/89000436
tagged with: python
has comment: http://stackoverflow.com/comment/89000477
favorite count: 0
tagged with: python-3.x
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/51003662
tagged with: lambda
has answer: http://stackoverflow.com/a/51003610
has comment: http://stackoverflow.com/comment/89000399
has answer: http://stackoverflow.com/a/51003659

http://stackoverflow.com/comment/89131541
type: AnswerComment
score: 0
type: Comment
has text: There is problem with AUC metric with Keras. I will explain in the post. By the way, I just saw in your code you put target_tensors=[dataset_labels] in model.compile. I think you don't need that if you use the generator. Is it written by mistake?
comment on: http://stackoverflow.com/a/50979587

http://stackoverflow.com/q/50951527
has comment: http://stackoverflow.com/comment/88924473
has body: I have a received a json file with some data, that I'm supposed to analyse. The data comes from a sql-database, thus, it is normally structured in tables. However, when I receive it it looks like this: {'TimeStamp1': '2018-06-03 00:21:04', 'Owner1': 'Some owner', 'Description1': 'A description', 'TimeStamp2': '2018-06-03 00:22:15', 'Owner2': 'A new Owner', 'Description2': 'A new description'} ... And so on. So only one line/object with all the data and multiple keys with almost the same name. How can I concvert it in Python to something similar to a sql-setup or: {'records': {'TimeStamp': '2018-06-03 00:21:04', 'Owner': 'Some owner', 'Description': 'A description'}, {'TimeStamp': '2018-06-03 00:22:15', 'Owner': 'A new Owner', 'Description': 'A new description'} } And still guarantee that the right owner is on the same line as the associated time stamp and description? :)
answer count: 1
accepted answer: http://stackoverflow.com/a/50971483
tagged with: python
type: AnsweredQuestion
tagged with: syntax
has comment: http://stackoverflow.com/comment/88900811
has title: sanitize wrong json format in python
type: Question
has answer: http://stackoverflow.com/a/50971483
tagged with: http://stackoverflow.com/tag/json
score: 0

http://stackoverflow.com/q/51004990
type: AnsweredQuestion
has title: Python: fence-post caused by for loop
downvote count: 0
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/51005035
score: 5
has answer: http://stackoverflow.com/a/51005080
tagged with: python
has answer: http://stackoverflow.com/a/51005035
has comment: http://stackoverflow.com/comment/89003522
accepted answer: http://stackoverflow.com/a/51005080
answer count: 2
has comment: http://stackoverflow.com/comment/89003828
tagged with: loops
tagged with: for-loop
upvote count: 5
has body: I am trying to build a basic random serial number generator in Python, which inserts each generated S\N into a list. In the end of every generated S\N there is an unnecessary dash (-). For example: XXXX-YYYY-ZZZZ-NNNN- Code: import random import string x = "" l = [] # A blank list for y in range(0,3): # Creating 3 different serial numbers for t in range(0,4): # Creating 4 sections to each S\N and seperating them with a dash (-) for i in range(0, 5): # Creating a 5 letters combination x += random.choice(string.ascii_letters) x += "-" # Causes problem since printed 4 times instead of 3 l.append(x) x = "" print(l) Output: ['GzWFP-Owoyk-NNKBk-RKZBm-', 'nxTtS-aGVff-yVfLo-WQVJN-', 'HUmTd-XzSSK-weSKs-BHNSv-'] I tried different variations but none of them seems to work. Best Regards.

http://stackoverflow.com/q/50987126
has title: Python files extractor on executable
tagged with: python
tagged with: exe
has answer: http://stackoverflow.com/a/50990296
score: 0
has comment: http://stackoverflow.com/comment/88975195
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88968985
has body: I have build one executable file with python pyinstaller and need to keep some files within the executable when i execute the file it has to extract the other files to the specific path like installing a packages in specific folders. i have done the following pyinstaller -F --add-data 'installation.zip:installation.zip' --onefile but i don't have any idea how to extract the zip file in executable to the destination.
accepted answer: http://stackoverflow.com/a/50990296
answer count: 1
tagged with: pyinstaller

http://stackoverflow.com/a/50941074
has body: So after a while I got it working by making my own WSGI application file instead of using the webapp2. There are still some issues such as the message being formatted wrong, but this is my code now: from pyramid.config import Configurator from pyramid.response import Response import email, getpass, imaplib, os, re import sys detach_dir = "C:\OTHERS\CS\PYTHONPROJECTS" def imaptest(request): m = imaplib.IMAP4_SSL("imap.gmail.com") m.login("testi.protokolla@gmail.com", "testiprotokolla221") m.select("INBOX") resp, items = m.search(None, '(FROM "vallu.toivonen96@gmail.com")') items = items [0].split() my_msg = [] msg_cnt = 0 break_ = False for emailid in items[::1]: resp, data = m.fetch(emailid, "(RFC822)") if ( break_ ): break for response_part in data: if isinstance(response_part, tuple): msg = email.message_from_string(response_part[1]) varSubject = msg['subject'] varDate = msg['date'] if varSubject[0] == '$': r, d = m.fetch(emailid, "(UID BODY[TEXT])") ymd = email.utils.parsedate(varDate)[0:3] my_msg.append([ email.message_from_string(d[0][1]), ymd]) msg_cnt += 1 # Print as HTML return Response( 'Content-Type': 'text/html' "Your latest Email:" + str(msg) ) config = Configurator() config.add_route('imaptest', '/imaptest') config.add_view(imaptest, route_name='imaptest') app = config.make_wsgi_app()
answers question: http://stackoverflow.com/q/50903075
type: Answer
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50903075

http://stackoverflow.com/q/50935821
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88870282
tagged with: python
has body: has anyone managed to link their discord bot with a website they have created? I have a discord bot written in python and I want to link it with a Django site I have created to take certain data from the bot and upload it to my site... I dont expect the code to be written for me I just was wondering if anyone has done this before and how I should approach this.. Thanks!
tagged with: bots
has title: Linking a Discord bot with Django site / Discord.py
has comment: http://stackoverflow.com/comment/88871090
type: Question
tagged with: discord.py
has comment: http://stackoverflow.com/comment/88870394
score: 0
tagged with: discord
has comment: http://stackoverflow.com/comment/88873667
tagged with: python-3.x
answer count: 0

http://stackoverflow.com/q/50900199
score: 0
type: Question
has answer: http://stackoverflow.com/a/50900888
answer count: 1
tagged with: python-3.x
has body: I have some data in a file that looks like this: [General] StartWithLastProfile=1 [Profile0] Name=Sveta IsRelative=1 Path=Profiles/lqtrtj3x.Sveta Default=1 [Profile1] Name=Jason IsRelative=1 Path=Profiles/er5rtak4.Jason [Profile2] Name=Sarah IsRelative=1 Path=Profiles/23mvfqcj.Sarah I want to read all data and construct a namedtuple based on that data, but the output is quite strange, and I'm not sure how to explain it and what to do about it. Here is what I tired: def split_and_return_data(data_to_split): return data_to_split.split("=")[1] def main(): # read_profile_attributes returns a list containing the data profile_attributes = read_profile_attributes(profile_ini) # Ignore the first 3 elements list_of_firefox_profiles = list_of_profile_attributes[3:len(profile_attributes)] firefox_profile = namedtuple("Profile", ["Name", "IsRelative", "Path", "Default"]) name = None isRelative = None path = None default = None for profile_attribute in list_of_firefox_profiles: if profile_attribute and "Name" in profile_attribute: name = split_and_return_data(profile_attribute) elif profile_attribute and "IsRelative" in profile_attribute: isRelative = split_and_return_data(profile_attribute) elif profile_attribute and "Path" in profile_attribute: path = split_and_return_data(profile_attribute) elif profile_attribute and "Default" in profile_attribute: default = split_and_return_data(profile_attribute) print("{0}, {1}, {2}, {3}".format(name, isRelative, path, default)) if __name__ == "__main__": main() Output: None, None, None, None Sveta, None, None, None Sveta, 1, None, None Sveta, 1, Profiles/lqtrtj3x.Sveta, None Sveta, 1, Profiles/lqtrtj3x.Sveta, 1 Sveta, 1, Profiles/lqtrtj3x.Sveta, 1 Sveta, 1, Profiles/lqtrtj3x.Sveta, 1 Jason, 1, Profiles/lqtrtj3x.Sveta, 1 Jason, 1, Profiles/lqtrtj3x.Sveta, 1 Jason, 1, Profiles/er5rtak4.Jason, 1 Jason, 1, Profiles/er5rtak4.Jason, 1 Jason, 1, Profiles/er5rtak4.Jason, 1 Sarah, 1, Profiles/er5rtak4.Jason, 1 Sarah, 1, Profiles/er5rtak4.Jason, 1 …
has title: Display data outputs strange results
tagged with: python
accepted answer: http://stackoverflow.com/a/50900888
type: AnsweredQuestion

http://stackoverflow.com/comment/88799928
has text: Are you sure, I mean after it has been printed, will it continue to print all the time or will it just loop and check for the new updates?
type: Comment
comment on: http://stackoverflow.com/a/50899541
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88765229
comment on: http://stackoverflow.com/q/50878862
has text: Even I went through the same situation. And it was solved when I added something extra to my Procfile. Content of my procfile is : `web: gunicorn myproject.wsgi web: gunicorn myproject:myapp web: python manage.py runserver 0.0.0.0:$PORT`
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88899111
has text: if your list is [1,2,3,4,5,6,7,8,9,10] and you are starting at index 5 then you are summing 6+7+8+9+10
type: Comment
comment on: http://stackoverflow.com/q/50950575
score: 0
type: QuestionComment

http://stackoverflow.com/a/51002833
upvote count: 0
score: -2
type: Answer
downvote count: 2
has body: Works perfectly: import os os.environ['SOMEVAR'] = 'bla' print(os.getenv('SOMEVAR')) # in your shell: export SOMEVAR1="blabla" print(os.getenv('SOMEVAR1')) Gives: bla blabla
answers question: http://stackoverflow.com/q/51002694

http://stackoverflow.com/q/50873376
type: Question
has body: I was searching for different ways of using a WHILE loop or FOR loop for the problem which I'm currently facing. I'm looking for pending (checking) loop I have code which sends the request and receives an output, which is an empty field or date when the report created. Idea is to do something like this: WHILE generatedDate is None: run the script which gets information if it None IF generatedDate is not None Another bit of code which will download the report which just created Does code should looks like this?? while x is None #Do stuff if x is not None #Do other stuff The answer was exactly what I was looking for, sorry for not providing full detailed information. import time #This part I made to access API and receive up to date JSON file def get_data(): data=None #Initially no data return data #This section was modified to def download_report def treat_data(data): #do the stuff when you got data, in your case download the report pass #Check if data received generatedData=get_data() #Loop for pinging when data will be filled in. while generatedData==None: #Pingin text print "waiting data" generatedData=get_data() #Wating time between checks time.sleep(0.25) #download_report call after exiting the loop (after field become not empty) treat_data(generatedData) #report generated
tagged with: do-while
possible better answer: http://stackoverflow.com/a/50873462
has answer: http://stackoverflow.com/a/50873462
answer count: 2
tagged with: for-loop
accepted answer: http://stackoverflow.com/a/50873914
upvote count: 0
favorite count: 0
tagged with: while-loop
tagged with: python
score: -2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88748317
has comment: http://stackoverflow.com/comment/88748347
has title: Python while loop ( until data exist )
downvote count: 2
has answer: http://stackoverflow.com/a/50873914
has comment: http://stackoverflow.com/comment/88749007
has comment: http://stackoverflow.com/comment/88748448
tagged with: loops

http://stackoverflow.com/a/50899698
downvote count: 2
has comment: http://stackoverflow.com/comment/88801203
has body: Don't use an explicit loop. Here's one solution via pd.Series.apply: def func(x): return x * 2.0 mask = df['column3'] == 'orange' df.loc[mask, 'column2'] = df.loc[mask, 'column2'].apply(func) print(df) index column1 column2 column3 0 0 2 5.0 apple 1 1 4 3.0 apple 2 2 6 2.0 orange 3 3 8 6.0 apple 4 4 10 10.0 orange However, if you operation can be vectorised, as in this case, you should use vectorised operations. For example: df.loc[df['column3'] == 'orange', 'column2'] *= 2 Since NumPy arrays, which are behind numeric series in Pandas, work better with vectorised solutions than with explicit loops, you will see performance benefits cross over to Pandas.
answers question: http://stackoverflow.com/q/50899676
has comment: http://stackoverflow.com/comment/88800650
score: -2
has comment: http://stackoverflow.com/comment/88800524
upvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/88800319
has comment: http://stackoverflow.com/comment/88799870

http://stackoverflow.com/q/51009719
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89012225
has title: Prompting user input() and using regular expression
has comment: http://stackoverflow.com/comment/89012123
type: Question
has comment: http://stackoverflow.com/comment/89012098
has answer: http://stackoverflow.com/a/51009845
accepted answer: http://stackoverflow.com/a/51009845
has comment: http://stackoverflow.com/comment/89012353
upvote count: 1
has comment: http://stackoverflow.com/comment/89012179
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89012262
has comment: http://stackoverflow.com/comment/89012163
has comment: http://stackoverflow.com/comment/89012159
has comment: http://stackoverflow.com/comment/89012145
has body: I want to use regular expression to print all the text fragments in a list found in another text. Both texts are prompted by the user and the names (egg and egg_carton are just names, it's not about eggs). The following code prints an empty list. I think the problem is the re.compile part of the code, but I don't know how to fix this problem. I would like the code modified in it's form, not a completely other method of solving this problem. Appreciate it. import re egg= input() egg_carton = input() text_fragment = re.compile(r'(egg)') find_all = text_fragment.findall(egg_carton) print(find_all)
has comment: http://stackoverflow.com/comment/89012037
tagged with: python
has comment: http://stackoverflow.com/comment/89012108
type: AnsweredQuestion

http://stackoverflow.com/q/50937721
has body: I see that there is supposed to be support for creating python wrappers to the C++ generated protobuf readers. From http://yz.mit.edu/wp/fast-native-c-protocol-buffers-from-python/ I find a simple way to turn on support by setting the environment variable: PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=cpp if I do that I get the following error: import pyFileLib.db_proc_geo_pb2 File "C:\sandbox\PrortoBuf\lib\pyFileLib\db_proc_geo_pb2.py", line 6, in &lt;module&gt; from google.protobuf import descriptor as _descriptor File "c:\python\winpython-64bit-3.6.3.0qt5\python-3.6.3.amd64\lib\site-packages\google\protobuf\descriptor.py", line 46, in &lt;module&gt; from google.protobuf.pyext import _message ImportError: cannot import name '_message' I see a way to extend the protoc generator to natively generate fastpython ouput: https://github.com/Cue/fast-python-pb git clone https://github.com/Cue/fast-python-pb.git cd fast-python-pb python setup.py install I get the following error when trying to run protoc with --fastpython_out: ModuleNotFoundError: No module named 'plugin_pb2' --fastpython_out: protoc-gen-fastpython: Plugin failed with status code 1. It looks like this is related to: https://groups.google.com/forum/#!topic/protobuf/5Ywz8gwn9Kk python installation of protocol buffers does not generate the google.protobuf.compiler.plugin_pb2 python file, while google.protobuf.descriptor_pb2 is explicitly generated by protobuf/python/setup.py How do I go about making this explicit installation happen...or otherwise making protobuf performance in python acceptable?
tagged with: python
downvote count: 0
type: UnansweredQuestion
type: Question
score: 3
has answer: http://stackoverflow.com/a/50950265
upvote count: 3
answer count: 1
has title: Problems getting fastpython protobuf support
favorite count: 0
tagged with: python-3.x
tagged with: protocol-buffers

http://stackoverflow.com/q/50966018
has title: Close off an endpoint on node.js server by via Kubernetes
tagged with: python
has comment: http://stackoverflow.com/comment/88957382
tagged with: node.js
has answer: http://stackoverflow.com/a/50981018
has comment: http://stackoverflow.com/comment/88957390
type: AnsweredQuestion
score: 0
type: Question
has body: I have a Docker image which runs a python subprocess, which is a node.js server exposing an end point /check. The whole thing is put inside a Kubernetes pod and uses /check as the readinessProbe endpoint. Now at some point, I want to close this endpoint or force-fail all the requests coming at it. Ideally, I want to do this via higher-level entities (i.e. Kubernetes lifecycle hooks) so as not to touch the lower-level implementation (such as opening a new endpoint /stop that switch some boolean flag and force the /check to fail) Is that possible at all? If not, what is the best alternative?
accepted answer: http://stackoverflow.com/a/50981018
tagged with: docker
has comment: http://stackoverflow.com/comment/88968197
tagged with: kubernetes
answer count: 1
has comment: http://stackoverflow.com/comment/88968226

http://stackoverflow.com/q/50992457
answer count: 0
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/88979712
score: 0
has body: I'm trying to create a command that when executed, will write to a json file in the same directory and send a message every 24 hours. And I've got it to work partially, however in the console when the message is supposed to be executed it spits out an error. Here is my code, I'm honestly puzzled on why it's not working. @bot.command(pass_context=True) async def message(ctx, *args): if ctx.message.author.server_permissions.administrator or ctx.message.author.id == 'id here': phrase = " ".join(args) time = datetime.datetime.now() try: data["24h"][ctx.message.channel.id] = { "time": time.strftime("%m:%d:%H:%M"), "message": phrase, "just_sent": False } await bot.say("Succesfully added a message to be said every 24 hours!") except Exception as err: await bot.say("An error has occured!") print(traceback.format_exc()) #save data to file with open("data.json", "w") as write_file: json.dump(data, write_file)
has comment: http://stackoverflow.com/comment/88979786
tagged with: python
has title: Having trouble with getting a json timed event to work

http://stackoverflow.com/comment/88910508
type: Comment
type: QuestionComment
has text: @miradulo rejection sampling is new to me and from what I read, I can't see a way to use it here. Can you explain it or give a link that explains it?
score: 0
comment on: http://stackoverflow.com/q/50956063

http://stackoverflow.com/q/50949476
tagged with: python
has body: I have saved a dictionary as json to re-use later across a number of areas. The dictionary structure is: dict = { 1: 'Name', 2: 'Name2', 3: 'Name3' } I have saved it as so: with open('fpath', 'w') as out : json.dump(dict, out) When I am reading it back in, though, it reads the dictionary keys as strings, not ints, as follows: with open('fpath', 'r') as inf : dict = json.load(inf) print (dict) dict = { '1': 'Name', '2': 'Name2', '3': 'Name3' } This makes it so I can't use it as needed, for example to map it to a pandas dataframe column. How do I save the dictionary so that the keys are saved and read back in as ints, not strings?
tagged with: dictionary
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/50949630
linked to: http://stackoverflow.com/q/1450957
score: 1
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/88896633
has title: JSON dict saving keys as string not int
has comment: http://stackoverflow.com/comment/88896464
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/1450957

http://stackoverflow.com/q/50989052
has comment: http://stackoverflow.com/comment/88972758
has comment: http://stackoverflow.com/comment/88972780
has comment: http://stackoverflow.com/comment/88972731
type: UnansweredQuestion
has body: when i try to get default python version its showing 3.6 but when i try to run my code its running in python 2.7 ...i have used scrapy crawl cablo to make the file run ABC abstract method is also installed Traceback (most recent call last): File "/usr/local/bin/scrapy", line 11, in &lt;module&gt; sys.exit(execute()) File "/usr/local/lib/python2.7/dist-packages/scrapy/cmdline.py", line 149, in execute cmd.crawler_process = CrawlerProcess(settings) File "/usr/local/lib/python2.7/dist-packages/scrapy/crawler.py", line 249, in _init_ super(CrawlerProcess, self).__init__(settings) File "/usr/local/lib/python2.7/dist-packages/scrapy/crawler.py", line 137, in _init_ self.spider_loader = _get_spider_loader(settings) File "/usr/local/lib/python2.7/dist-packages/scrapy/crawler.py", line 336, in _get_spider_loader return loader_cls.from_settings(settings.frozencopy()) File "/usr/local/lib/python2.7/dist-packages/scrapy/spiderloader.py", line 61, in from_settings return cls(settings) File "/usr/local/lib/python2.7/dist-packages/scrapy/spiderloader.py", line 25, in _init_ self._load_all_spiders() File "/usr/local/lib/python2.7/dist-packages/scrapy/spiderloader.py", line 47, in _load_all_spiders for module in walk_modules(name): File "/usr/local/lib/python2.7/dist-packages/scrapy/utils/misc.py", line 71, in walk_modules submod = import_module(fullpath) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/megha/Downloads/Data_scuff/Data_scuff/spiders/cablo.py", line 11, in &lt;module&gt; from abc import ABC, abstractmethod ImportError: cannot import name ABC
has comment: http://stackoverflow.com/comment/88973842
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88994321
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/50989419
tagged with: python
has title: Python 3.6.5 installed but the file taking python 2.7 as a default
has comment: http://stackoverflow.com/comment/88972722
has comment: http://stackoverflow.com/comment/88973249
has comment: http://stackoverflow.com/comment/88972963
tagged with: scrapy
has comment: http://stackoverflow.com/comment/88972783
has comment: http://stackoverflow.com/comment/88973075
answer count: 1
downvote count: 1

http://stackoverflow.com/q/50866736
has body: How can I make the following code more pythonic? so I can combine if/else and 2 assert statement into one line? @pytest.mark.parametrize('para', [1, -1, 0]) def test_xxxx(self, para): def test(value): return False if value &gt;= 0 else True if para &gt;= 0: assert test(para) is False else: assert test(para) is True
has answer: http://stackoverflow.com/a/50913313
score: 3
downvote count: 0
favorite count: 0
has title: How to assert once with multiple conditions?
type: Question
tagged with: python
tagged with: pytest
upvote count: 3
answer count: 2
has answer: http://stackoverflow.com/a/50866780
has comment: http://stackoverflow.com/comment/88735738
type: UnansweredQuestion

http://stackoverflow.com/q/50909747
downvote count: 0
score: 1
tagged with: scikit-learn
favorite count: 0
type: Question
upvote count: 1
tagged with: python
has title: How to add LabelBinarizer columns to DataFrame
answer count: 1
has answer: http://stackoverflow.com/a/50909859
has body: I have recently started working with LabelBinarizer by running the following code. (here are the first couple of rows of the CSV file that I'm using): import pandas as pd from sklearn.preprocessing import LabelBinarizer #import matplotlib.pyplot as plot #-------------------------------- label_conv = LabelBinarizer() appstore_original = pd.read_csv("AppleStore.csv") #-------------------------------- lb_conv = label_conv.fit_transform(appstore["cont_rating"]) column_names = label_conv.classes_ print(column_names) print(lb_conv) I get the lb_conv and the column names. Therefore: how could I attach label_conv to appstore_original using column_names as the column names? If anyone could help that would be great.
accepted answer: http://stackoverflow.com/a/50909859
tagged with: pandas
type: AnsweredQuestion

http://stackoverflow.com/comment/88877376
type: QuestionComment
type: Comment
has text: Did you set the pygame.key.set_repeat()? When the keyboard repeat is enabled, keys that are held down will generate multiple pygame.KEYDOWN events. When pygame is initialized the key repeat is disabled.
score: 0
comment on: http://stackoverflow.com/q/50939298

http://stackoverflow.com/comment/88828865
comment on: http://stackoverflow.com/q/50914229
score: 0
type: Comment
type: QuestionComment
has text: Can you find these div[n] elements as a list, then do element.findElement on each in a loop?

http://stackoverflow.com/a/50871906
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50871840
has body: Both of those snippets are essentially identical to: return dict.fromkeys(words, True) Which is a mapping where the keys are the items in words and the values are True. The dict class also takes an iterable of (key, value) pairs, which is what you are creating in both of those snippets. In the first, it is a generator expression, so not all the items are created at once, but they are created as it is iterated over. The second is a list compression, so a list is created to begin with and all the items are created and put into a list. In either case, dict sees an iterable.
answers question: http://stackoverflow.com/q/50871840
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/88745682
downvote count: 0
has comment: http://stackoverflow.com/comment/88745501
score: 5

http://stackoverflow.com/comment/89000962
has text: of course. but the whole lambda-ing that function is a game. so let's have fun
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51003651
type: Comment

http://stackoverflow.com/a/51007152
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51007129
has comment: http://stackoverflow.com/comment/89008161
has body: The problem is that you are using 32-bit Python distribution on a 64-bit Windows machine, so it can't load IA 32-bit .dll on an AMD 64-bit platform. Change the Python distribution to a 64-bit one and hopefully it should work.
downvote count: 0

http://stackoverflow.com/comment/88786866
score: 0
comment on: http://stackoverflow.com/a/50892293
type: AnswerComment
has text: @Simon, great to hear!
type: Comment

http://stackoverflow.com/comment/88898510
type: Comment
comment on: http://stackoverflow.com/a/50937324
has text: Thanks. Do you need speakers separated when they alternate or is one string transcript enough for each?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88915020
score: 0
type: Comment
type: QuestionComment
has text: import os import subprocess if os.path.exists('C:\\Program Files (x86)\\TeamViewer.exe'): subprocess.run('C:\\Program Files (x86)\\TeamViewer.exe') this is what i got now..sorry about the format but I have no ideea how to introduce as code in a comment. problem is no error is given, teamviewer still won't start.
comment on: http://stackoverflow.com/q/50958584

http://stackoverflow.com/comment/88947150
type: Comment
type: QuestionComment
has text: Can you noot chose which one gets placed first? Like in word you chose which image gets 'brought to the front'
comment on: http://stackoverflow.com/q/50973137
score: 0

http://stackoverflow.com/q/50955592
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/88908854
type: Question
tagged with: numpy
has title: Reshaping Python array in a particular way
has body: I am working on a Python code so that I can basically do this with a Numpy Array I have a Matlab code for it, which is A = [1:30]'; % Example matrix rows = 3; for i=1:(numel(A)-rows+1) B(1:rows,i)=A(i:i+rows-1,1); end or, without any loop, B = conv2(A.', flip(eye(rows))); B = B(:, rows:end-rows+1); Can someone help me do the same in Python? Using the reshape function is not helping since I need to "mirror" the values (and not only reorganizing them). Thank you.
has answer: http://stackoverflow.com/a/50956546
tagged with: arrays
possible better answer: http://stackoverflow.com/a/50956444
has answer: http://stackoverflow.com/a/50956444
tagged with: matrix
has answer: http://stackoverflow.com/a/50956911
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/50956976
has comment: http://stackoverflow.com/comment/88909522
tagged with: reshape
tagged with: python
answer count: 4
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50956911

http://stackoverflow.com/a/50892917
has body: Using groupby.count + pd.Series.duplicated: df['count_b'] = df.groupby('b').transform('count') df.loc[df['b'].duplicated(), 'count_b'] = -1 print(df) a b count_b 0 1 32 3 1 4 32 -1 2 5 32 -1 3 9 45 2 4 8 45 -1 5 3 76 4 6 5 76 -1 7 7 76 -1 8 9 76 -1 You can, if you wish, combine the two steps with numpy.where: import numpy as np df['count_b'] = np.where(df['b'].duplicated(), -1, df.groupby('b')['b'].transform(len))
type: Answer
answers question: http://stackoverflow.com/q/50892819
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/a/54457135
has body: first solution is to save the current mouse location then return to it after mouse click as follows import pyautogui (x,y)=pyautogui.position() pyautogui.click(600,300) pyautogui.moveTo(x,y) second solution is to make a keyboard shortcut for the button then simply pressing the button without moving the mouse
score: -1
answers question: http://stackoverflow.com/q/50901191
upvote count: 0
type: Answer
downvote count: 1

http://stackoverflow.com/a/50903492
accepted answer of: http://stackoverflow.com/q/50902512
has body: It'd seem that by default the passed value is JSON encoded, if it is a list or a dict. You can work around that by passing an explicit array literal: In [15]: from sqlalchemy.dialects.postgresql import array In [16]: session.query(Foo).\ ...: filter(Foo.data['test'].has_any(array(['1', '2']))).all() 2018-06-18 09:07:20,780 INFO sqlalchemy.engine.base.Engine BEGIN (implicit) 2018-06-18 09:07:20,780 INFO sqlalchemy.engine.base.Engine SELECT foo.id AS foo_id, foo.data AS foo_data FROM foo WHERE ((foo.data -&gt; %(data_1)s)) ?| ARRAY[%(param_1)s, %(param_2)s] 2018-06-18 09:07:20,781 INFO sqlalchemy.engine.base.Engine {'data_1': 'test', 'param_1': '1', 'param_2': '2'} Out[16]: [] This way you do not need to manually format the array literal from the string representation of a Python list, which is probably rather error prone. The error itself is the result of Postgresql trying to parse the passed literal – containing JSON – as an array. As the error states, the text representation of an array may start with a dimension decoration that specifies the array's subscript ranges: '[1:1][-2:-1][3:5]={{{1,2,3},{4,5,6}}}'::int[]
answers question: http://stackoverflow.com/q/50902512
type: Answer
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/88806874
has comment: http://stackoverflow.com/comment/88807767
score: 4
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88808117

http://stackoverflow.com/comment/88937013
comment on: http://stackoverflow.com/q/50957742
has text: Right after the `self.seldir.show()` in the `select_dir()` function, you should be able to access `self.seldir.selected`. Without an MCVE (see [How to create a Minimal, Complete, and Verifiable Example](https://stackoverflow.com/help/mcve) it's hard to understand and help with your question.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88762644
has text: And I am assuming here the time column is not sorted, right ?
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50880096

http://stackoverflow.com/comment/98968515
has text: This should be the preferred answer for MacOs users
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/55681774
score: 3

http://stackoverflow.com/comment/88967239
type: AnswerComment
score: 0
type: Comment
has text: Thank you for taking the time to explain this! I'm really tempted to delete the question since it seems i'ts going to be a one way ticket to downvote-town. But seeing the effort some of you are making to explain these things, I don't have any choice but to let it stand. Thanks again!
comment on: http://stackoverflow.com/a/50986118

http://stackoverflow.com/q/50878193
downvote count: 0
answer count: 1
tagged with: string
favorite count: 0
has title: Padding string placeholder after bracket in python logging
type: UnansweredQuestion
tagged with: python
has body: I currently have my logging string in Python set up like this: logging.basicConfig( format='[%(asctime)s] [%(levelname)-5s] %(message)s', level=logging.DEBUG ) Which produces something like that: [2018-06-15 10:54:15,021] [DEBUG] debug [2018-06-15 10:54:15,022] [INFO ] info [2018-06-15 10:54:15,022] [ERROR] error So the padding for the levelname occurs inside the square brackets. Instead, I would like to have the padding outside the bracket, so it looks like this: [2018-06-15 10:54:15,021] [DEBUG] debug [2018-06-15 10:54:15,022] [INFO] info [2018-06-15 10:54:15,022] [ERROR] error Unfortunately there doesn't seem to be a syntax for putting extra characters (like the []) between '%' and 's', nor can I pad the format string before passing it to basicConfig(). Is there a way to accomplish what I want?
upvote count: 5
tagged with: formatting
type: Question
has answer: http://stackoverflow.com/a/50878881
score: 5

http://stackoverflow.com/comment/88801249
type: Comment
type: QuestionComment
has text: How are you "building" the initial dict? If you structure the multi-level dict differently then it might work better. Have a dict for each level of uniqueness you require: `ind[individual]['name']['BIRT']` then as you add items to the dict the first time you see Mr Smith his "record" will be created. Each future time you see his record the previous one will be overwritten.
score: 0
comment on: http://stackoverflow.com/q/50900608

http://stackoverflow.com/a/51007185
answers question: http://stackoverflow.com/q/51007157
downvote count: 0
type: Answer
has body: dictNames = {} with open("Sentences.dat") as file: for line in file: parts = line.split() num = int(parts.lstrip('#')) dictNames[num] = parts[3]
upvote count: 1
score: 1

pycharm
tags question: http://stackoverflow.com/q/50886471
tags question: http://stackoverflow.com/q/51002441
tags question: http://stackoverflow.com/q/50988763
tags question: http://stackoverflow.com/q/51009736
tags question: http://stackoverflow.com/q/50877370
tags question: http://stackoverflow.com/q/50944006
tag name: pycharm
tags question: http://stackoverflow.com/q/50941163
tags question: http://stackoverflow.com/q/50863660
tags question: http://stackoverflow.com/q/50980355
tags question: http://stackoverflow.com/q/50997319
tags question: http://stackoverflow.com/q/50974936
tags question: http://stackoverflow.com/q/51001009
tags question: http://stackoverflow.com/q/50881403
tags question: http://stackoverflow.com/q/50955005
tags question: http://stackoverflow.com/q/50879286
tags question: http://stackoverflow.com/q/50889452
tags question: http://stackoverflow.com/q/50900159
tags question: http://stackoverflow.com/q/50936029
tags question: http://stackoverflow.com/q/50891018
tags question: http://stackoverflow.com/q/50949250
tags question: http://stackoverflow.com/q/50919845
tags question: http://stackoverflow.com/q/50938332
tags question: http://stackoverflow.com/q/50959385
tags question: http://stackoverflow.com/q/50881940
tags question: http://stackoverflow.com/q/50982375
tags question: http://stackoverflow.com/q/50990239
type: Tag
tags question: http://stackoverflow.com/q/50936098
tags question: http://stackoverflow.com/q/50955549
tags question: http://stackoverflow.com/q/50928743
tags question: http://stackoverflow.com/q/50993171
tags question: http://stackoverflow.com/q/51001804
tags question: http://stackoverflow.com/q/50985140
tags question: http://stackoverflow.com/q/50970555

http://stackoverflow.com/comment/88968237
has text: Yes ShadowRanger wrote an excellent related answer here https://stackoverflow.com/a/40996908/6260170
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50985232

http://stackoverflow.com/comment/88713434
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50855109
has text: Suppose the sentence was , 'John became the first writer to get the 1000 reviews.' . I added an extra 'the'. According to the output, 'the first writer' needs to be tagged and not the extra 'the'; but it gets tagged as well.
score: 0

http://stackoverflow.com/a/50993283
has body: With Series.str.rsplit, limiting the number of splits. df['col1'].str.rsplit('|', n=1, expand=True).rename(columns=lambda x: f'col{x + 1}') If the above throws you a SyntaxError, it means you're on a python version older than 3.6 (shame on you!). Use instead df.col1.str.rsplit('|', 1, expand=True)\ .rename(columns=lambda x: 'col{}'.format(x + 1)) col1 col2 0 MLB|NBA NFL 1 MLB NBA 2 NFL|NHL|NBA MLB There's also the faster loopy str.rsplit equivalent. pd.DataFrame( [x.rsplit('|', 1) for x in df['col1'].tolist()], columns=['col1', 'col2'] ) col1 col2 0 MLB|NBA NFL 1 MLB NBA 2 NFL|NHL|NBA MLB P.S., yes, the second solution is faster: df = pd.concat([df] * 100000, ignore_index=True) %timeit df['col1'].str.rsplit('|', n=1, expand=True) %timeit pd.DataFrame([x.rsplit('|', 1) for x in df['col1'].tolist()]) 473 ms ± 13.8 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) 128 ms ± 1.29 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
has comment: http://stackoverflow.com/comment/88981415
upvote count: 12
has comment: http://stackoverflow.com/comment/88981260
has comment: http://stackoverflow.com/comment/88981570
has comment: http://stackoverflow.com/comment/88981203
has comment: http://stackoverflow.com/comment/88981755
answers question: http://stackoverflow.com/q/50993263
has comment: http://stackoverflow.com/comment/88981309
score: 12
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88981797
accepted answer of: http://stackoverflow.com/q/50993263
has comment: http://stackoverflow.com/comment/88981481
type: Answer

http://stackoverflow.com/q/50864135
score: 3
type: Question
tagged with: python-2.7
has body: I have the following code inside my script to create a log of all the prints that the script does in the console: import sys class Logger(object): def __init__(self): pathLogs = 'logs/' if not os.path.isdir(pathLogs): os.makedirs(pathLogs) file_name = pathLogs + "logger.log" self.terminal = sys.stdout self.log = open(file_name, "a") def write(self, message): self.terminal.write(message) self.log.write(message) sys.stdout = Logger() It works fine, but it prints everything to a file only after the script is finished. It is not printing anything while the script is running, even though I do see my prints in the console. How can I make it not wait until the end of the script to start printing to a my log file?
favorite count: 0
has comment: http://stackoverflow.com/comment/88730865
has comment: http://stackoverflow.com/comment/88730922
upvote count: 3
has comment: http://stackoverflow.com/comment/88732208
tagged with: python
has comment: http://stackoverflow.com/comment/88730803
has comment: http://stackoverflow.com/comment/88732539
answer count: 0
downvote count: 0
type: UnansweredQuestion
has title: How to make Logger write to file while Python script is running
tagged with: logging

http://stackoverflow.com/comment/88808196
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50903736
has text: @pyd no need. Try this: `res = {k : v[k].dropna().tolist() for k in df}` and then just filter out empty values as needed.

http://stackoverflow.com/comment/88823719
score: 0
comment on: http://stackoverflow.com/a/50911382
type: AnswerComment
has text: I'm sorry to mention this but when I'm running exactly your code I'm still getting this structure: `{'pageid': {1234: [45678, 78908, 23208], 4567: [789323, 1094738, 565980]}, 'timestamp': {1234: [1504010302, 1504016546, 1506691286], 4567: [1529577322, 1532173522, 1532190922]}}` Anyway thank you very much for trying to help!
type: Comment

http://stackoverflow.com/q/50911993
tagged with: vertex-shader
tagged with: fragment-shader
tagged with: python
tagged with: kivy
has title: Kivy Fix "Output of vertex shader 'frag_color' not read by fragment shader" message
answer count: 0
downvote count: 0
score: 1
type: Question
has body: When using any Kivy Screen transition based on the ShaderTransition, a message saying [INFO ] [Shader ] program: &lt;WARNING: Output of vertex shader 'frag_color' not read by fragment shader&gt; is outputted, and I would like to get rid of this message. I know that I can set the logger levels to turn off any message classified as info and below which would resolve this, but I'd prefer to not do that. I'd rather modify the necessary files to fix this message. So, I'm wondering what would need to be done to fix the Output of vertex shader 'frag_color' not read by fragment shader error.
upvote count: 1
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/50893586
tagged with: numpy
answer count: 1
has body: I am using the following to calculate the running gradients between data in the same indexes across multiple matrices: import numpy as np array_1 = np.array([[1,2,3], [4,5,6]]) array_2 = np.array([[2,3,4], [5,6,7]]) array_3 = np.array([[1,8,9], [9,6,7]]) flat_1 = array_1.flatten() flat_2 = array_2.flatten() flat_3 = array_3.flatten() print('flat_1: {0}'.format(flat_1)) print('flat_2: {0}'.format(flat_2)) print('flat_3: {0}'.format(flat_3)) data = [] gradient_list = [] for item in zip(flat_1,flat_2,flat_3): data.append(list(item)) print('items: {0}'.format(list(item))) grads = np.gradient(list(item)) print('grads: {0}'.format(grads)) gradient_list.append(grads) grad_array=np.array(gradient_list) print('grad_array: {0}'.format(grad_array)) This doesn't look like an optimal way of doing this - is there a vectorized way of calculating gradients between data in 2d arrays?
score: 0
tagged with: python
has answer: http://stackoverflow.com/a/50893647
accepted answer: http://stackoverflow.com/a/50893647
has title: Numpy calculate gradients accross matrices
type: AnsweredQuestion
type: Question

http://stackoverflow.com/a/50869557
has body: There is a problem in your template. {% csrf_token %} {{ form.p }} Sign up Change your code in template from above to the following one: {% csrf_token %} {{ form.as_p }} Sign up When you give it as form.p the template engine searches for an attribute with name 'p' inside 'form' object, but that is not what we want. So use form.as_p instead to render the form wrapped in paragraph elements.
type: Answer
answers question: http://stackoverflow.com/q/50869399
has comment: http://stackoverflow.com/comment/88769657
score: 2
accepted answer of: http://stackoverflow.com/q/50869399
has comment: http://stackoverflow.com/comment/88773897
has comment: http://stackoverflow.com/comment/88773277
downvote count: 0
has comment: http://stackoverflow.com/comment/88772179
upvote count: 2
has comment: http://stackoverflow.com/comment/88790296
type: AcceptedAnswer

http://stackoverflow.com/comment/88812953
has text: Thank you, that worked perfectly! Edit: Also thanks for the other advice.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50886974
type: Comment

http://stackoverflow.com/comment/88780384
comment on: http://stackoverflow.com/q/50889419
has text: May be it is better to look at search engines? Like Haystack+Whoosh (for beginning, also far more complicated - Solr and ElasticSearch).
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/50895146
accepted answer of: http://stackoverflow.com/q/50894960
type: Answer
answers question: http://stackoverflow.com/q/50894960
has comment: http://stackoverflow.com/comment/88791198
upvote count: 1
score: 1
has body: Firstly, you have to indent your code. to say if (condition) then do print('hello') you write it this way: if condition: print('hello') Secondly, you are using i =+ 1 which is the same as i=1 I think you meant i +=1 which is i = i+1 Finally, I suggest this code: answer = input("Enter a string: ") vowel_repeated_count = 0 length_Answer = len(answer) i=0 while (i &lt;length_Answer-1): #we check if it's a vowel if answer[i] in ["a","e","i","o","u"]: #we check if it's followed by the same vowel if answer[i+1] == answer[i]: #increment the vowel_repeated_count vowel_repeated_count +=1 #we save the vowel for the display vowel = answer[i] #we skip the other same repeated vowels #example: abceeed, we skip the third e while (answer[i] == vowel and i &lt; length_Answer-1): i +=1 #we add this incrementation because we're in a while loop i +=1 if vowel_repeated_count == 0: print("no repeating vowles") elif vowel_repeated_count == 1: print("the letter "+ str(vowel) +" repeats") else: print ("more than 1 repeating vowels")
has comment: http://stackoverflow.com/comment/88790919
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/88771215
has text: @OlivierMelançon I would like the 2nd and 4th index in this example to be a kind of wildcard, as it will accept 0 or 1 as long as the 1st, 2nd, and 3rd indexes are equivalent to their counterparts in the `data` tuple. I'm just not sure how to make the 2nd and 4th indexes 'wildcards'.
comment on: http://stackoverflow.com/a/50884411
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/50993978
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88983726
has answer: http://stackoverflow.com/a/50996766
has comment: http://stackoverflow.com/comment/88984175
has comment: http://stackoverflow.com/comment/88984899
tagged with: machine-learning
upvote count: 1
has comment: http://stackoverflow.com/comment/88983778
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/88983998
has title: How to get Keras network to not output all 1s
has comment: http://stackoverflow.com/comment/88984004
accepted answer: http://stackoverflow.com/a/50996766
has body: I have a bunch of images that look like this of someone playing a videogame (a simple game I created in Tkinter): The idea of the game is that the user controls the box at the bottom of the screen in order to dodge the falling balls (they can only dodge left and right). My goal is to have the neural network output the position of the player on the bottom of the screen. If they're totally on the left, the neural network should output a 0, if they're in the middle, a .5, and all the way right, a 1, and all the values in-between. My images are 300x400 pixels. I stored my data very simply. I recorded each of the images and position of the player as a tuple for each frame in a 50-frame game. Thus my result was a list in the form [(image, player position), ...] with 50 elements. I then pickled that list. So in my code I try to create an extremely basic feed-forward network that takes in the image and outputs a value between 0 and 1 representing where the box on the bottom of the image is. But my neural network is only outputting 1s. What should I change in order to get it to train and output values close to what I want? Of course, here is my code: # machine learning code mostly from https://machinelearningmastery.com/tutorial-first-neural-network-python-keras/ from keras.models import Sequential from keras.layers import Dense import numpy as np import pickle def pil_image_to_np_array(image): '''Takes an image and converts it to a numpy array''' # from https://stackoverflow.com/a/45208895 # all my images are black and white, so I only need one channel return np.array(image)[:, :, 0:1] def data_to_training_set(data): # split the list in the form [(frame 1 image, frame 1 player position), ...] into [[all images], [all player positions]] inputs, outputs = [list(val) for val in zip(*data)] for index, image in enumerate(inputs): # convert the PIL images into numpy arrays so Keras can process them inputs[index] = pil_image_to_np_array(image) return (inputs, outputs) if __name__ …
has comment: http://stackoverflow.com/comment/88983956
has comment: http://stackoverflow.com/comment/88983979
has comment: http://stackoverflow.com/comment/88984408
answer count: 1
tagged with: neural-network
downvote count: 0
score: 1
tagged with: keras
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/88983659
linked to: http://stackoverflow.com/q/41236657

http://stackoverflow.com/comment/89005148
type: QuestionComment
comment on: http://stackoverflow.com/q/51005745
score: 0
has text: Possible duplicate of [QSqlDatabase: QMYSQL driver not loaded on Ubuntu 15.04 64bits](https://stackoverflow.com/questions/37369480/qsqldatabase-qmysql-driver-not-loaded-on-ubuntu-15-04-64bits)
type: Comment

http://stackoverflow.com/comment/101899766
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50866911
has text: Possible duplicate of [Python in-memory cache with time to live](https://stackoverflow.com/questions/31771286/python-in-memory-cache-with-time-to-live)
score: 0

parameters
tags question: http://stackoverflow.com/q/50910349
type: Tag
tag name: parameters
tags question: http://stackoverflow.com/q/50939773

http://stackoverflow.com/q/50859626
has title: Python - Import Classes from different Projects
linked to: http://stackoverflow.com/q/714063
linked to: http://stackoverflow.com/q/14509192
tagged with: python-import
type: AnsweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/50859789
type: Question
tagged with: python
linked to: http://stackoverflow.com/q/44070953
has comment: http://stackoverflow.com/comment/88722028
score: 0
accepted answer: http://stackoverflow.com/a/50859789
tagged with: import
has body: First off all: Sorry - I know that there already exist several questions which concern issues with the python import mechanism. However after hours of searching through SO I still couldn't find a sufficent answer for me. Problem I've got two independent Python projects hosted on my GitLab Server. Let's call them foo and foo-Tester. As the name implies, foo-Tester is a automatic Tester for the foo-Project. foo has the following structure: -foo - __init__.py - fooClass.py -bar - __init__.py - barClass.py -foobar - __init__.py - foobarClass.py etc. The classes import each other via relativ imports. For sake of this example the foo-Tester Project just contains: - foo-Tester - __init__.py - tester.py While the tester.py just contains: from foo.fooClass import fooClass myfoo = fooClass() Both Projects reside next to each other on the file-system: - some-folder - foo - foo-Tester So my question is: What is the best approach/best-practice to import the fooClass from foo into tester.py from the foo-Tester-Project? What I've tried Using setup.py Some Answers (e.g. this suggest using setup.py. As far as I understand this approach, one would need to install the foo-Project each time it is changed - am I correct? This wouldn't be a good solution for us as the Project is under heavy development with many changes a day. Appending to system-path This answer suggest adding the foo project path to the system path. And running the script with the -m Flag Two concerns about this approach: it seems a bit hacky to modify the systempaths it seems like this doesn't work with the relative imports from the foo project as it always throws an relative imports not allowed-Error. I am using Python 3.6. So what would be the best approach for the described problem? Thank you in advance!

http://stackoverflow.com/a/78947254
upvote count: 1
score: 1
downvote count: 0
has body: If you use plotly: import plotly json.dumps(data, cls=plotly.utils.PlotlyJSONEncoder)
type: Answer
answers question: http://stackoverflow.com/q/50916422

http://stackoverflow.com/comment/88898192
has text: So obviuos! Thanks, don't know why I didn't figure it out myself
comment on: http://stackoverflow.com/a/50950113
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/50884396
tagged with: mysql
has answer: http://stackoverflow.com/a/50884749
tagged with: pymysql
type: UnansweredQuestion
tagged with: docker
has comment: http://stackoverflow.com/comment/88770847
has body: I am having trouble making a connection to a MySQL container using pymysql from outside a container on Mac OSX, though I am able to connect to the docker MySQL with MySQL Workbench. I used the following docker-compose.yaml: version: '3' services: db: image: mysql:latest volumes: - ./data/db:/var/lib/mysql ports: - 6603:3306 restart: always environment: MYSQL_ROOT_PASSWORD: password MYSQL_USER: testuser MYSQL_PASSWORD: password And the following pymysql import pymysql conn = pymysql.connect( host='0.0.0.0', port=6603, user='testuser', password='password', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor ) And received the following error: OperationalError: (1045, "Access denied for user 'testuser'@'172.18.0.1' (using password: NO)") The same applies when trying to login as root. I have tried: 1) Granting privileges in many permutations, also setting up HOST as '%' 2) Removing and recreating the mounted volume Mainly I want to be able to access the MySQL database from an interactive shell during development. Any guidance would be great. Thanks.
type: Question
tagged with: docker-for-mac
has title: Is it possible to make a pymysql connection to a MySQL docker container?
tagged with: python
answer count: 1
score: 0

http://stackoverflow.com/q/50883192
accepted answer: http://stackoverflow.com/a/50884059
tagged with: python
tagged with: dictionary
upvote count: 2
has comment: http://stackoverflow.com/comment/88768724
possible better answer: http://stackoverflow.com/a/50883299
has answer: http://stackoverflow.com/a/50883299
has body: I am pulling data from an API, and creating a dictionary that looks like this. my_dict = {'server_name1': ['utah', 'california', 'idaho', 'texas'], 'server_name2': ['NewYork'], 'server_name3': ['idaho', 'new york', 'texas'], 'server_name4': ['florida'], 'server_name5': ['utah', 'california']} I am trying to create maintenance groups so we only have to notify clients about maintenance one time by knowing all the servers they touch, which in turn requires knowing all the servers other customers on those servers are on. So I want to combine as many like groups as possible and I am doing this by grouping the keys that have at least one matching value as other keys. So my dictionary would go from the above to: new_dict = {'server_name1, server_name2, server_name3, server_name5': ['utah', 'california', 'idaho', 'texas', 'newyork'], 'server_name4': ['florida']} I have some code that does this, but it takes several iterations of grouping, which is not great unless you know exactly how many times you have to group things to get to the smallest number of groups possible. This is my working code. new_dict = {} for key in my_dict.iteritems(): for key2 in my_dict.iteritems(): if len(key[1]) &gt; 0 and len(key2[1]) &gt; 0: if key[0] != key2[0]: if all(x in key[1] for x in key2[1]) == True: newkey = "{0}, {1}".format(key2[0],key[0]) servers = key[0] + ", " + key2[0] states = key[1] + list(key2[1]) group = {servers:states} new_dict.update(group)
has title: Group dictionaries to the smallest set of key values pairs possible
score: 2
type: AnsweredQuestion
tagged with: grouping
downvote count: 0
has answer: http://stackoverflow.com/a/50884059
favorite count: 0
type: Question
answer count: 2

http://stackoverflow.com/q/50966001
tagged with: django
tagged with: python
has body: After going to all the links in Stack Overflow as well as other git etc. too, I am unable to solve my error. Basically, I want to scrap instagram by giving specific hashtag i.e. User will give a hashtag from Django UI and Django function will send that hashtag to scrapy spider for crawling using scrapy.spider.spider.CrawlProcess() Hope for the help ! Following is my code: django/models.py from django.db import models class InstaAccountDetails(models.Model): website = models.URLField() post_id = models.PositiveIntegerField() shortcode = models.CharField(max_length=200) caption = models.CharField(max_length=500) display_url = models.ImageField() loc_id = models.PositiveIntegerField() loc_name = models.CharField(max_length=200) loc_lat = models.IntegerField() loc_lon = models.IntegerField() owner_id = models.PositiveIntegerField() owner_name = models.CharField(max_length=200) taken_at_timestamp = models.DateField() def __str__(self): return self.owner_name django/views.py from django.shortcuts import render, redirect from django.http import JsonResponse from scrapy.crawler import CrawlerProcess, CrawlerRunner from scrapy.utils.project import get_project_settings from instagram_scrapy.instagram_scrapy.spiders.instaCrawler import InstagramSpider def home(request): return render(request, 'instagram_link_app/homePage.html') def get_insta_details(request): field_value = request.GET.get('value_holder') print("request value ::::::::::::::: ",field_value) try: if field_value: return JsonResponse({"msg:" "Hii"}) process = CrawlerProcess(get_project_settings()) process.crawl(InstagramSpider(hashtag=field_value)) process.start() #the script will block here until the crawling is finished print(process) data['process'] = process return JsonResponse(data) else: return JsonResponse({'message': 'None'}) except Exception as e: return JsonResponse({'message': str(e)}) scrapy/settings.py import os import sys import django BOT_NAME = 'instagram_scrapy' SPIDER_MODULES = ['instagram_scrapy.…
upvote count: 1
tagged with: scrapy
type: UnansweredQuestion
has title: How to call scrapy spider inside django view using spider.CrawlerRunner() or CrawlerProcess()
answer count: 0
downvote count: 0
score: 1
favorite count: 0
tagged with: python-3.x
tagged with: django-2.0
type: Question

http://stackoverflow.com/a/50859546
accepted answer of: http://stackoverflow.com/q/50858952
has comment: http://stackoverflow.com/comment/88722151
answers question: http://stackoverflow.com/q/50858952
score: 4
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88721852
type: Answer
upvote count: 4
has comment: http://stackoverflow.com/comment/88721777
downvote count: 0
has body: You cannot use sleep() inside of a tkinter instance. Tkinter is a single thread application and when you tell it to sleep everything in the event list is put on hold/freezes. You need to use after()for any delays in your code. The after() method is specifically meant to manage delays in tkinter. Because in your example it appears you are running 2 separate delays my example will provide both delays. Here is an exampled composed from the code you provided. We can set all the delays we need buy provided a 2nd function. I have added a random number generator to the code to illustrate a continuous change of the colors. import tkinter as tk import random class MainApp(tk.Tk): def __init__(self): tk.Tk.__init__(self) self.tx_value = tk.StringVar() self.tx_value.set("test") self.blink_status = 1 self.tx_label = tk.Label(self, textvariable=self.tx_value, relief=tk.GROOVE, width=4, height=2) self.tx_label.grid(row=0, column=4, sticky=tk.E) self.blink_tx() def blink_tx_step_2(self, color=None): if color != None: self.tx_label["bg"] = color self.after(3500, self.blink_tx) def blink_tx(self): if self.blink_status == 1: self.tx_label["bg"] = 'green' self.tx_value.set('Tx') self.blink_status = random.randint(0, 2) self.after(1000, self.blink_tx_step_2, 'blue') elif self.blink_status == 0: self.tx_label["bg"] = 'red' self.tx_value.set('*') self.blink_status = random.randint(0, 2) self.after(2000, self.blink_tx_step_2, 'orange') else: self.tx_label["bg"] = 'red' self.tx_value.set('x') self.blink_status = random.randint(0, 2) self.after(2000, self.blink_tx_step_2) if __name__ == '__main__': app = MainApp() app.mainloop()

http://stackoverflow.com/q/50975156
tagged with: pandas
has answer: http://stackoverflow.com/a/50975372
answer count: 1
has comment: http://stackoverflow.com/comment/88947517
has comment: http://stackoverflow.com/comment/88946630
has comment: http://stackoverflow.com/comment/88947425
has comment: http://stackoverflow.com/comment/88947158
has body: I have a situation where I need to calculate the local time based on the Pacific time zone column. sample data Pacific_AM_PM timezone 8 Pacific 11 Eastern 20 Central the logic is that, if timezone= Pacific, then local_time: 8+0=8 if timezone= Eastern, then local_time: 11+3=14 only 4 conditions total: Pacific, Eastern, mountain, central expect output Pacific_AM_PM timezone adjust_hour local_time 8 Pacific 0 8 11 Eastern 3 14 20 Central 2 22 I attempt to use numpy.where to set the conditions, but i don't know how. I'm not limited to use numpy.
tagged with: python
has comment: http://stackoverflow.com/comment/88946652
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88947156
type: Question
has comment: http://stackoverflow.com/comment/88946439
accepted answer: http://stackoverflow.com/a/50975372
has comment: http://stackoverflow.com/comment/88946470
has title: multiple conditions with calculation in Pandas dataframe
tagged with: numpy
score: 0

http://stackoverflow.com/q/51002858
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/51004252
has body: I used a class with tkinter to make a window. However, changing the background color does not work for me. I have looked at the other question and tried every solution to changing the background color, but none work. Here is my code: from tkinter import * class Window(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.master = master self.init_window() self.mazeDrawing() def init_window(self): self.master.title('Maze') self.pack(fill=BOTH, expand=1) self.master.geometry("900x600") self.master.config(bg='black') menu = Menu(self.master) self.master.config(menu=menu) file = Menu(menu) file.add_command(label='Exit', command=self.clientExit) menu.add_cascade(label='File', menu=file) def clientExit(self): exit() def mazeDrawing(self): canvas = Canvas(self.master, width='900', height='600') canvas.pack() canvas.create_rectangle(100, 100, 800, 500, outline='red') root = Tk() App = Window(root) App.mainloop() As you can see, I clearly defined the background color as black in init_window as self.master.config(bg='black'), but when I run the code, I get a white window. I'm not sure if this is simply because my computer sucks or if I am violating some python rule. Please plug this into your editor and run the code.
has comment: http://stackoverflow.com/comment/89000352
has title: Does 'config(bg=[color])' not work in classes?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89000405
has answer: http://stackoverflow.com/a/51004252
type: Question
has comment: http://stackoverflow.com/comment/88999617
tagged with: python
tagged with: tkinter

tableau-api
tags question: http://stackoverflow.com/q/50892740
tags question: http://stackoverflow.com/q/50887182
type: Tag
tag name: tableau-api

http://stackoverflow.com/a/50949204
has body: From my perspective the best way of having such functionality is to create Custom Django Field. Use pre_save to adjust value before save. Than define getter for the field and as the setter use pre_save method to convert value before it goes to database. See You can see django.db.fields for inspiration.
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/50948848
score: 1

http://stackoverflow.com/q/50905121
tagged with: selenium
type: Question
has comment: http://stackoverflow.com/comment/88843962
has answer: http://stackoverflow.com/a/64567526
has comment: http://stackoverflow.com/comment/88844004
tagged with: webautomation
has comment: http://stackoverflow.com/comment/88821872
score: 0
answer count: 2
has title: How to click the icon using selenium
has answer: http://stackoverflow.com/a/50905367
has comment: http://stackoverflow.com/comment/88810593
type: UnansweredQuestion
has body: I am trying to automate my certain activities using selenium. I was launching a webpage and a security windows popup appears for the login credentials. I have automated that using Autoit. Now after login I need to click on the option and I have tried it based on the find_element_by_text and find_element_by_id. I was getting an error as Unable to find the element with CSS selector and I have seen some other post in the StackOverflow with the same issue but I could not able to fix it by myself. Here is how my HTML looks like. Could you please guide me on this and also please share any document for further checking. Thanks. driver = webdriver.Ie(r"C:\\IEDriverServer\\IEDriverServer.exe") driver.get('URL of the page') #driver.implicitly_wait(10) # seconds autoit.win_wait("Windows Security") # now make that crap active so we can do stuff to it autoit.win_activate("Windows Security") # type in the username autoit.send('username') # tab to the password field autoit.send("{TAB}") # type in the password autoit.send('password') # kill! autoit.send("{ENTER}") driver.maximize_window() driver.implicitly_wait(120) # seconds #submit_button_incidents = driver.find_element_by_link_text("3-Normal Incidents") submit_button_incidents= driver.find_element_by_id("nodeImgs13pm") submit_button_incidents.click() driver.implicitly_wait(10) ++ updating the info I have tried to copy the whole HTML but the page was restricted so I cant able to view the full HTML page other than the basic templates. Adding some more screenshots of the developer tools. Here how my webpage looks like.
tagged with: python
has comment: http://stackoverflow.com/comment/88822434

http://stackoverflow.com/q/50891292
score: 4
upvote count: 4
has answer: http://stackoverflow.com/a/50891423
tagged with: pandas
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/88786758
has comment: http://stackoverflow.com/comment/88783702
favorite count: 0
tagged with: python-3.x
linked to: http://stackoverflow.com/q/49259580
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88783732
tagged with: python
has comment: http://stackoverflow.com/comment/88783826
duplicate of: http://stackoverflow.com/q/49259580
has title: Python: Replacement not allowed with overlapping keys and values
has comment: http://stackoverflow.com/comment/88783637
type: Question
has body: I'm trying to shuffle the values from an input dataframe, store these new values into a dictionary, and then get an output dataframe by replacing the input dataframe values with their dictionary mapping. However, I get the "Replacement not allowed with overlapping keys and values" error. Here's my code sample: in_df = ['A','B','C'] in_df = pd.DataFrame(in_df,columns=['Alphabets']) df_temp = in_df.sample(frac=1).reset_index(drop=True) df_temp = df_temp.rename(columns={'Alphabets':'sample'}) mask_dict = dict(zip(in_df['Alphabets'], df_temp['sample'])) out_df= in_df.replace({'Alphabets': mask_dict}) in_df looks as follows: Alphabets A B C mask_dict looks something like this: {'A': 'C', 'B': 'A', 'C': 'C'} I want the out_df to look like this: Alphabets C A C I found a way to do this! df_temp = in_df.stack().unique() df_temp = pd.DataFrame(df_temp, columns=['Alphabets']) df_temp1 = df_temp.sample(n=df_temp.size, random_state=123) mask_dict = dict(zip(df_temp['Alphabets'], df_temp1['Alphabets'])) out_df = in_df.applymap(mask_dict.get)
has comment: http://stackoverflow.com/comment/88783671

http://stackoverflow.com/q/50954885
favorite count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/47007680
tagged with: python
tagged with: lambda
has body: I came across a Python Challenge question with a variable declaration I didn't understand. It was asking for the output of this code. a = "abcd" b = "abc" func = (lambda s:s[1:]) or (lambda s:s[:-1]) print(func(b)) I pretty much ignored the second lambda and got the correct answer which was: "bc" My questions are, what is the practical use of having an "or" during variable assignment between lambda functions? And how would I access the second lambda in an "or" statement? What would be an example of the second lambda function being invoked? Note: My question has been marked as a duplicate. The other question and answer provided great information and supplementary knowledge related to my topic. However, that question was dealing with return values and general statements. I think my question is different in that it deals with variable assignment rather than return values, and the application of "or" to functions, which I don't see covered in the other question. I would still like clarification on the concept of truthiness or falsey values applied to a lambda function.
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/88907627
has title: Python: Variable assignment using "or" with lambda functions?
has comment: http://stackoverflow.com/comment/88907601
type: Question
has comment: http://stackoverflow.com/comment/88907411
duplicate of: http://stackoverflow.com/q/47007680
has answer: http://stackoverflow.com/a/50954931
upvote count: 1
answer count: 1

http://stackoverflow.com/a/50909357
has comment: http://stackoverflow.com/comment/88818940
has comment: http://stackoverflow.com/comment/88819104
has comment: http://stackoverflow.com/comment/88819505
has comment: http://stackoverflow.com/comment/88818745
score: 0
answers question: http://stackoverflow.com/q/50909310
has body: Create a .bat file with your text editor. Then type in the commands you need. See below code as an example: @echo off cd C:\Users\azad cd E:\Development\Python\djangogirls dgvenv\Scripts\activate @py.exe python manage.py runserver
has comment: http://stackoverflow.com/comment/88818847
type: Answer

http://stackoverflow.com/comment/88906972
has text: You would just do `getFastaEntry(filename)` inside `generate_fasta_reader` (after the `def getFastaEntry`). As written, there's no reason for this to be an inner function, especially since it looks like you're trying to call it from an outer scope.
score: 3
comment on: http://stackoverflow.com/q/50954671
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50895239
type: AnsweredQuestion
has title: Python combine two lists of dictionaries of unequal lengths into a single list based on a key
has comment: http://stackoverflow.com/comment/88790686
tagged with: collections
type: Question
accepted answer: http://stackoverflow.com/a/50895557
tagged with: data-structures
score: 0
has answer: http://stackoverflow.com/a/50895557
answer count: 1
has body: I am using cassandra with python and i am executing two queries together. I want to group the results of the results together into a single list using a column as key. list1 = [{'firstname':'foo','lastname':'bar','id':1},{'firstname':'foo2','lastname':'bar2','id':2}] list2 = [{'text':'sample','contact_no':'666','id':1},{'text':'sample2','contact_no':'111','id':1}, {'text':'sample3','contact_no':'121','id':2}] I want to group these two lists together using id key as the criteria Expected result [{'firstname':'foo','lastname':'bar','id':1,'text':'sample','contact_no':'666'}, {'firstname':'foo','lastname':'bar','id':1,'text':'sample2','contact_no':'111'},{'firstname':'foo2','lastname':'bar2','id':2,'text':'sample3','contact_no':'121'}] Please advice on how can i do this the most pythonic way. Thanks in advance.
has comment: http://stackoverflow.com/comment/88790841
tagged with: cassandra
tagged with: python

http://stackoverflow.com/q/50973011
has comment: http://stackoverflow.com/comment/88945098
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88945296
has comment: http://stackoverflow.com/comment/88944648
has comment: http://stackoverflow.com/comment/88944428
has body: I have a program written in BASIC, and need it to trigger an external python code by use of a batch file. However, although the batch file is created, it is clear that my python code is not running - the python file is supposed to create other folders, but nothing is created when I run the code. However, when running my script (NoArgv.py) from the shell, it works, so I know the python script is not the problem. I have made sure to add python to my environment variables path, and made sure that I have full permission/access to the file. Below are the contents from the batch file, TEST.bat. "C:\python27\python.exe" "C:\USERS\ELARRICK\DESKTOP\NoArgv.py" DEL "fst.bat" Is there something specifically wrong with this code? If not, what should I change to make sure that the file runs? **Disclaimer: The code is written in a slightly altered version of BASIC by my company, so it may look strange - I'll include the main portion of calling the batch file below just in case someone understands it ' create a batch file $filehandle = fileopen "C:\USERS\ELARRICK\DESKTOP\TEST.bat", 0 ' specify the python exe here $strglob[29] = "C:\python27\python.exe" ' specify the name of the python program you want to run $strglob[30] = "C:\USERS\ELARRICK\DESKTOP\NoArgv.py" ' form a long string write to the batch file $strglob[31] = "\x22"+$strglob[29]+"\x22 " + "\x22"+$strglob[30]+"\x22" ' copy the parameter file over to the directory filewrite $filehandle, $strglob[31] ' this takes care of deleting the batch file filewrite $filehandle, "DEL \x22fst.bat\x22" fileclose $filehandle $filehandle = 0 ' execute the batch file exemodal "C:\USERS\ELARRICK\DESKTOP\TEST.bat"
has comment: http://stackoverflow.com/comment/88945766
downvote count: 0
has title: Batch file Python Execution
score: 1
has comment: http://stackoverflow.com/comment/88946757
has comment: http://stackoverflow.com/comment/88947973
has comment: http://stackoverflow.com/comment/88945439
type: Question
upvote count: 1
tagged with: batch-file
has comment: http://stackoverflow.com/comment/88942679
has comment: http://stackoverflow.com/comment/88948201
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/88945629
answer count: 0

http://stackoverflow.com/q/50915356
tagged with: python
has title: Deleting rows that have decreasing values
accepted answer: http://stackoverflow.com/a/50915528
upvote count: 1
downvote count: 1
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50915528
has comment: http://stackoverflow.com/comment/88831089
has body: I am examining what happens to variable X when Y is increasing. I have a dataframe and I want to keep data where Y is increasing for a minimum of 2 months. Is it possible to loop through a dataframe and drop decreasing rows for Y? date | X | Y --------------- 1-2017 | 2 | 1 2-2017 | 2 | 2 3-2017 | 2 | 3 4-2017 | 2 | 4 5-2017 | 2 | 5 6-2017 | 2 | 4 7-2017 | 2 | 3 8-2017 | 2 | 1 9-2017 | 2 | 1 10-2017 | 2 | 4 11-2017 | 2 | 7 12-2017 | 2 | 1 13-2017 | 2 | 1 After stripping decreasing dates: date | X | Y --------------- 1-2017 | 2 | 1 2-2017 | 2 | 2 3-2017 | 2 | 3 4-2017 | 2 | 4 5-2017 | 2 | 5 9-2017 | 2 | 1 10-2017 | 2 | 4 11-2017 | 2 | 7
has comment: http://stackoverflow.com/comment/88830738
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88830988
score: 0
tagged with: pandas

http://stackoverflow.com/a/50901237
downvote count: 0
score: 2
type: AcceptedAnswer
has body: You can use range like this by using step (indexing): list_1 = [1,3,2,4,3,1,2,7] for i in range(0,len(list_1),2): print(list_1[i]) or just using python slice notation: list_1 = [1,3,2,4,3,1,2,7] for v in list_1[::2]: print(v)
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/50901229
accepted answer of: http://stackoverflow.com/q/50901229

http://stackoverflow.com/q/51010940
has body: I am writing a simple Django web application and I am trying implement REST API. I use django-rest-framework package. I use Python 3.x on Debian sid GNU/Linux. However, when I try access REST API through browser I'm getting error: Traceback (most recent call last): File "/home/lynx/PycharmProjects/hello_world/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/home/lynx/PycharmProjects/hello_world/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/lynx/PycharmProjects/hello_world/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/lynx/PycharmProjects/hello_world/venv/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/lynx/PycharmProjects/hello_world/venv/lib/python3.6/site-packages/django/views/generic/base.py", line 69, in view return self.dispatch(request, *args, **kwargs) File "/home/lynx/PycharmProjects/hello_world/venv/lib/python3.6/site-packages/rest_framework/views.py", line 483, in dispatch response = self.handle_exception(exc) File "/home/lynx/PycharmProjects/hello_world/venv/lib/python3.6/site-packages/rest_framework/views.py", line 443, in handle_exception self.raise_uncaught_exception(exc) File "/home/lynx/PycharmProjects/hello_world/venv/lib/python3.6/site-packages/rest_framework/views.py", line 471, in dispatch self.initial(request, *args, **kwargs) File "/home/lynx/PycharmProjects/hello_world/venv/lib/python3.6/site-packages/rest_framework/views.py", line 389, in initial self.check_permissions(request) File "/home/lynx/PycharmProjects/hello_world/venv/lib/python3.6/site-packages/rest_framework/views.py", line 322, in check_permissions if not permission.has_permissio…
type: Question
downvote count: 0
has title: AssertionError: Cannot apply DjangoModelPermissionsOrAnonReadOnly on a view that does not set `.queryset` or have a `.get_queryset()` method
tagged with: django-rest-framework
answer count: 1
has answer: http://stackoverflow.com/a/51010992
favorite count: 0
tagged with: rest
upvote count: 2
tagged with: django
tagged with: python
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51010992

http://stackoverflow.com/comment/88921911
comment on: http://stackoverflow.com/a/50957878
score: 0
type: AnswerComment
has text: Downvote didn't come from me. I'm trying it out right now :)
type: Comment

http://stackoverflow.com/comment/88836448
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50916170
type: Comment
has text: Also, please review the the [Stack Overflow help on how to create a minimal example](https://stackoverflow.com/help/mcve). For instance, do you observe the same problem once you deleted the progress hook? If you remove all options but `daterange`, does that fix your problem?

http://stackoverflow.com/q/50927740
score: 36
has title: SQLAlchemy: "create schema if not exists"
accepted answer: http://stackoverflow.com/a/55345404
answer count: 5
tagged with: sql
downvote count: 1
upvote count: 37
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88857985
has answer: http://stackoverflow.com/a/55345404
has answer: http://stackoverflow.com/a/77182290
tagged with: python
has comment: http://stackoverflow.com/comment/88857369
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/120936632
has answer: http://stackoverflow.com/a/61274497
tagged with: sqlalchemy
type: Question
has comment: http://stackoverflow.com/comment/88858164
linked to: http://stackoverflow.com/q/18346076
possible better answer: http://stackoverflow.com/a/77182290
has answer: http://stackoverflow.com/a/58382390
has body: I want to do the "CREATE SCHEMA IF NOT EXISTS" query in SQLAlchemy. Is there a better way than this: engine = sqlalchemy.create_engine(connstr) schema_name = config.get_config_value('db', 'schema_name') #Create schema; if it already exists, skip this try: engine.execute(CreateSchema(schema_name)) except sqlalchemy.exc.ProgrammingError: pass I am using Python 3.5.
tagged with: database
has comment: http://stackoverflow.com/comment/88858023
has answer: http://stackoverflow.com/a/73647390
favorite count: 0
has comment: http://stackoverflow.com/comment/88858428

http://stackoverflow.com/a/50979590
has body: ndimage.interpolation.zoom does not have a concept of RGB channels; it zooms an arbitrary n-dimensional array without any particular meaning to each dimension. For example, if you have an image stored as an array of shape (20, 20, 3) then after zoom(image, 2) it will become an array of shape (40, 40, 6) which is of course undesirable. Presumably you will use zoom(image, (2, 2, 1)) to have 2x zoom in both dimensions and no "zoom" in the channel dimension. If so, there is no spillover between channels then. Reading the C code of NI_ZoomShift I see that zoom is achieved using get_spline_interpolation_weights which performs one-dimensional spline interpolation (not bilinear or bicubic). This means that the zoom will consist of: Going over every 1D slice image[:, c, ch] and zooming it by 1D interpolation (no interaction between slices). Going over every 1D slice image[r, :, ch] and zooming it by 1D interpolation. Going over every 1D slice image[r, c, :] and zooming it by 1D interpolation - which with zoom factor of 1 will leave the values the same up to machine precision. A test of the above: zooming the entire image vs zooming each channel separately. import numpy as np from scipy.ndimage.interpolation import zoom image = np.random.uniform(size=(20, 20, 3)) output = zoom(image, (2, 2, 1)) for k in range(3): output_channel = zoom(image[:, :, k], 2) print(np.max(np.abs(output_channel - output[:, :, k]))) The printed values are around 1e-15, i.e., the output is the same up to floating point errors.
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50978828
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50978828
type: Answer

http://stackoverflow.com/a/51003214
score: 3
answers question: http://stackoverflow.com/q/51003197
has comment: http://stackoverflow.com/comment/89000035
has body: pd.read_csv(..., dtype=object) will globally apply the object dtype across all columns read in, if that's what you're looking for. Otherwise, you'll need to pass a dict of the form {'col' : dtype} if you want to map dtypes to column names.
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89000047
has comment: http://stackoverflow.com/comment/89000307
type: Answer
accepted answer of: http://stackoverflow.com/q/51003197
upvote count: 3

http://stackoverflow.com/comment/88958231
type: QuestionComment
has text: i guess it is not possible for privacy reasons then
comment on: http://stackoverflow.com/q/50970148
score: 0
type: Comment

http://stackoverflow.com/q/50910230
has comment: http://stackoverflow.com/comment/88821427
tagged with: makefile
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88821260
type: Question
has answer: http://stackoverflow.com/a/50910777
linked to: http://stackoverflow.com/q/28090490
has title: Ampersand separated commands in a Makefile
tagged with: python-venv
score: 0
has body: I have the following rule on my Makefile. init-local-env: @echo 'initializing python3 local environment in .venv' python3 -m venv .venv &amp;&amp; source .venv/bin/activate But does not take me to my virtual environment. It seems, only the first part of the command is run by the Makefile, because it had created the .venv folder, and only after I run source .venv/bin/activate on the terminal, it takes me to the environment. But, if I run these two commands on the terminal, it runs without an issue, and it takes me to the environment as well. python3 -m venv .venv &amp;&amp; source .venv/bin/activate I tried to use an if clause by referring to this question. init-local-env: @echo 'initializing python3 local environment in .venv' if [ -z "$$(python3 -m venv .venv)" ]; then \ source .venv/bin/activate; \ fi But it doesn't seem to work either. It gives me the below output and creates the .venv folder, but does not execute the second command. bash$ make init-local-env initializing python3 local environment in .venv if [ -z "$(python3 -m venv .venv)" ]; then \ source .venv/bin/activate; \ fi Any idea, what I'm doing wrong? And how can I run these two commands one after the other ( using &amp;&amp; ) ?
answer count: 1
tagged with: virtualenv
accepted answer: http://stackoverflow.com/a/50910777
has comment: http://stackoverflow.com/comment/88820500

http://stackoverflow.com/q/51005333
linked to: http://stackoverflow.com/q/41015779
has comment: http://stackoverflow.com/comment/89004704
type: Question
has title: Paho-mqtt client on Django
has comment: http://stackoverflow.com/comment/89020415
score: 0
has body: Good morning everyone I need a guide on how to configure an mqtt subscriber in a Django app and thus receive messages from CloudMQTT. I try to make a prototype IoT of low energy consumption, for the measurement of temperature and humidity. If someone can refer me to a project with which I can be guided, it would be very helpful.
type: UnansweredQuestion
tagged with: mqtt
tagged with: django
tagged with: python
duplicate of: http://stackoverflow.com/q/41015779
answer count: 0

http://stackoverflow.com/comment/88749068
type: QuestionComment
has text: Thank you. It was the USE_I18N=True....
score: 0
comment on: http://stackoverflow.com/q/50871237
type: Comment

http://stackoverflow.com/q/50911227
duplicate of: http://stackoverflow.com/q/44291155
answer count: 1
has title: How can I visualize categorical data?
has answer: http://stackoverflow.com/a/50911361
has body: I have two datasets like this (dots are random numbers): Category 1 A B C D E F G H 1 3 0 0 3 . . . 2 2 0 0 2 . . . . 3 0 2 4 2 . . . . 4 1 1 5 2 . . . . 5 0 . . . . . . . 6 2 . . . . . . . 7 3 . . . . . . . 8 0 . . . . . . . Category 2 A B C D E F G H 1 1 0 0 1 . . . . 2 1 0 0 1 . . . . 3 1 2 1 2 . . . . 4 0 1 5 0 . . . . 5 0 . . . . . . . 6 0 . . . . . . . 7 3 . . . . . . . 8 0 . . . . . . . A-H = things that the respondent should rank 1-10 = the ranking Ex. A is one time ranked on place 1, two times ranked on place 2 and zero times ranked on place 3 etc. I have two different kind of people that filled in the survey (Category 1 &amp; Category 2) so that's why there are two datasets with different kind of outcomes. Now I want to visualize this in the best way possible, so that you can see things like Category 1 find A &amp; D more important than Category 2. I work with python/pandas/matplotlib. Can somebody help?
score: 0
tagged with: visualization
tagged with: pandas
tagged with: data-visualization
tagged with: python
duplicate of: http://stackoverflow.com/q/49163305
type: UnansweredQuestion
type: Question
linked to: http://stackoverflow.com/q/49163305
tagged with: matplotlib

http://stackoverflow.com/q/50921502
tagged with: webhooks
tagged with: machine-learning
tagged with: django
tagged with: python
score: 2
tagged with: dialogflow-es
type: Question
has title: How to integrate Dialogflow with Django (Python)?
has answer: http://stackoverflow.com/a/50936878
answer count: 1
downvote count: 0
has body: I'm developing an assistant (bot) with Dialogflow, and i have this Django project where I have to extract data and then expose it through the bot, this is going to be stored in a local platform. I worked with Dialogflow and it's integration before but with Node.js and Javascript, with Django (python) is a brand new challenge and I'm confused. Until now I have the following: I know I can do it with this package: https://github.com/dialogflow/dialogflow-python-client-v2 I add a url for a webhook, right now this works locally only, like this: from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt import dialogflow @csrf_exempt def webhook(request): return HttpResponse('Works like a charm!') and in urls.py I have: url(r'^webhook$', views.webhook, name='webhook') And that's all I don't know how to proceed after this, I'm blocked and I don't know how yto make the integration and what's missing, any recommendations?
favorite count: 0
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/a/50971857
answers question: http://stackoverflow.com/q/50971213
type: Answer
score: 11
accepted answer of: http://stackoverflow.com/q/50971213
downvote count: 0
has body: The CPython random.py implementation is very readable. I recommend having a look: https://github.com/python/cpython/blob/3.6/Lib/random.py Anyway, that version of python creates a global random.Random() object and assigns it directly to the random module. This object contains a seed(a) method which acts as a module function when you call random.seed(a). Thus the seed state is shared across your entire program. 1) Yes. moduleA and moduleB uses the same seed. Importing random in moduleA creates the global random.Random() object. Reimporting it in moduleB just gives you the same module and maintains the originally created random.Random() object. 2) No. Not in the example you gave, but in general yes it can matter. You might use moduleB before you set the seed in moduleA thus your seed wasn't set. 3) Hard to tell. Much more complicated code base. That said, I would think it works the same way. The authors of numpy would really have to try to make it work in a different way than how it works in the python implementation. In general, if you are worried about seed state, I recommend creating your own random objects and pass them around for generating random numbers.
upvote count: 11
type: AcceptedAnswer

http://stackoverflow.com/a/50966009
has comment: http://stackoverflow.com/comment/88929172
has body: You can set up Plotly to work in online or offline mode. To work in online you need a username To work in offline just edit the code as import plotly import plotly.graph_objs as go from plotly.offline import * ... ... plotly.offline.plot(fig, filename='gauge-meter-chart.html')
downvote count: 0
score: 8
upvote count: 8
type: Answer
has comment: http://stackoverflow.com/comment/88929042
answers question: http://stackoverflow.com/q/50962895
has comment: http://stackoverflow.com/comment/88929208

http://stackoverflow.com/comment/88882951
comment on: http://stackoverflow.com/a/50941948
has text: Indeed. Thanks again!
type: Comment
score: 1
type: AnswerComment

http://stackoverflow.com/a/50957631
downvote count: 0
upvote count: 2
type: Answer
has body: I assume that [0.0, 0.1, ..., 1.0] are the specific positions on your x- and y-axis for which you are giving the "heat"-values in your .csv-file: # Content of "data.csv" 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 2, 0, 0, 0, 0, 0, 0, 0, 0, 0 7, 8, 5, 1, 2, 1, 0, 0, 0, 0 .... You render the heatmap in IPython or Jupyter with: import numpy as np import matplotlib.pyplot as plt data = np.genfromtxt("data.csv", delimiter=",") plt.imshow(data, cmap='hot', interpolation='nearest') plt.show() Right now the axis tick labels go from 0 to 10 rather than from 0.0 to 1.0, but you can relabel the axes if you want. If you're using a .csv-file that looks exactly like the one in your picture when opened in Excel (with the column and row headers): data = np.genfromtxt("data.csv", delimiter=",", skip_header=True, usecols=range(1, 11)) Cheers, Silas
answers question: http://stackoverflow.com/q/50955504
score: 2

http://stackoverflow.com/q/50964064
linked to: http://stackoverflow.com/q/4326037
linked to: http://stackoverflow.com/q/3013655
has title: how to create a hashmap xml resource in android
answer count: 1
score: 1
has body: i would like to know if there is a way to create a hashmap in the android resources and pull it inside the code with getResource()... ? I am looking to get something similar to python dictionary referenced by key:value. The important part is that i need it to be static inside the resources package Thanks
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: android
has answer: http://stackoverflow.com/a/50964322
has comment: http://stackoverflow.com/comment/126844202
tagged with: python
tagged with: dictionary
linked to: http://stackoverflow.com/q/13814503
downvote count: 1
type: Question
tagged with: hashmap

http://stackoverflow.com/q/51010549
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/89014470
has title: How to do join on 3 tables in Django Rest Framework (only primary keys)
has comment: http://stackoverflow.com/comment/89014868
upvote count: 2
has answer: http://stackoverflow.com/a/51014141
has body: I have three models, each with a primary key. How can I perform join operation using rest framework in Django? These are tables: class Publisher(models.Model): name = models.CharField(max_length=30) address = models.CharField(max_length=50) city = models.CharField(max_length=60) state_province = models.CharField(max_length=30) country = models.CharField(max_length=50) website = models.URLField() class Author(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=40) email = models.EmailField() class Book(models.Model): title = models.CharField(max_length=100) authors = models.ManyToManyField(Author) publisher = models.ForeignKey(Publisher) publication_date = models.DateField()
tagged with: django
type: Question
has comment: http://stackoverflow.com/comment/89014016
tagged with: django-models
has comment: http://stackoverflow.com/comment/89014942

http://stackoverflow.com/comment/89012123
has text: It's not clear whether you meant for `re.compile(r'(egg)')` to look for the actual string `'egg'`, or you want to look what that variable contains.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51009719
score: 0

http://stackoverflow.com/q/50934925
upvote count: 2
type: Question
accepted answer: http://stackoverflow.com/a/50956022
tagged with: bokeh
has title: Set colors according to values in a ColumnDataSource in Bokeh's scatter plot
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50956022
tagged with: python
score: 2
has body: I'm using a pandas dataframe as a ColumnDataSource in Bokeh to plot a scatter where each bubble represents a country. In my dataframe there's a column named "region" informing the region of each country, and I want the bubbles to be in the color that corresponds to their regions. I'd like to use a palette (like Viridis) to do so, but I'm having trouble to understand how that works in Bokeh, since I'm more used to MPL. source = ColumnDataSource(data=dict(x=df['gdp'], y=df['lifeExpec'], s=df['population']/100000)) p = figure(title='Bokeh Bubble Chart', width=600, height=500, x_axis_type='linear', y_axis_type='linear', x_range=(1000, 90000), y_range=(0, 100)) p.scatter(source=source, x='x', y='y', radius = 's', marker="circle", alpha = 0.5) show(p)
type: AnsweredQuestion

http://stackoverflow.com/comment/88992841
type: AnswerComment
has text: This really isn't a good solution. Almost any time you find yourself calling `index` on a list, it's a sign that you're using either the wrong data structure or the wrong algorithm. Here, you could just use a dict, instead of linearly searching through every character every time—it would be simpler, and clearer in meaning, and even more efficient (not that it's going to matter here). But at that point, you've just got roganjosh's answer.
comment on: http://stackoverflow.com/a/50999317
type: Comment
score: 0

http://stackoverflow.com/comment/127658629
has text: using python 3.6.9 i get that '_ original_stdstream_copy' does not exist, but there are sys.__stdout__ and sys.__stderr__ attributes that keep the original values and can be used for the same purposes (Edit: formatting)
comment on: http://stackoverflow.com/a/69227590
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/q/50880660
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50881286
has comment: http://stackoverflow.com/comment/88764137
has comment: http://stackoverflow.com/comment/88799248
score: 1
has body: I made a ui for work using PyQt5 and Python3. Additionally to clicking the buttons, I want to execute specific actions by pressing specific keys on my keyboard e.g. the space bar. I used the following to do so: def keyPressEvent(self, event): key = event.key() if key == Qt.Key_Space: print('space') elif key == Qt.Key_W: print('w') Instead of printing 'space', it presses the focused button in the ui, when I'm pressing the space bar. Just like I hit return. Although pressing the 'W'-key prints 'w' as expected. I already searched here at stackoverflow and other where in the web as well, but I found nothing really helpfull. The best I got was this one here. But it's using PyQt4.3 and copy and paste the code to my editor just brought me some errors. I thought the approach was a good one, but I were not able to transfer this to PyQt5.
tagged with: pyqt5
type: Question
upvote count: 2
has title: How to change space bar behaviour in PyQt5, Python3
tagged with: qkeyevent
answer count: 2
has answer: http://stackoverflow.com/a/50881286
tagged with: pyqt
downvote count: 1
has answer: http://stackoverflow.com/a/50935602
favorite count: 0
accepted answer: http://stackoverflow.com/a/50935602
tagged with: python-3.x
tagged with: python

http://stackoverflow.com/a/66932561
answers question: http://stackoverflow.com/q/50891138
downvote count: 0
type: Answer
has body: sudo apt install proxychains proxychains python3 test.py test.py from requests import get for x in range(10): print(f"Your IP Changes to: {get('https://api.ipify.org').text}") make sure you add some proxy end of /etc/proxychains.conf file
upvote count: 1
score: 1

http://stackoverflow.com/comment/88893450
comment on: http://stackoverflow.com/q/50947689
type: Comment
type: QuestionComment
has text: I understand that these are nested dictionaries, or possibly also a list within a dict, but I am trying to figure out how to access it.
score: 0

http://stackoverflow.com/comment/88949531
type: Comment
has text: Oh, `data` is a string. That's odd. You seem to be decoding your data into a dictionary (with `response.json()`), then re-encoding it (with `json.dumps`) and parsing it again (`json.loads`), only to go on and use the encoded version you had in the middle. Replace `data` in your loop with either `allJson` or `item_dict` (which should have the same contents). And perhaps consider getting rid of the excessive parsing and reparsing!
comment on: http://stackoverflow.com/a/50976492
type: AnswerComment
score: 0

http://stackoverflow.com/q/50898371
tagged with: pulp
has comment: http://stackoverflow.com/comment/88858707
tagged with: python
has comment: http://stackoverflow.com/comment/88876301
type: Question
tagged with: gurobi
score: 0
has body: I'm working on a MILP problem written in python (using pulp and gurobi). Obviously the original developer used Windows and I am running the code on Ubuntu. I am new to this and there is this piece of the code that I really don't understand. "FOR WINDOWS: Catch infeasible model and compute the IIS: to capture the infeasibility source" if MILP.status == pulp.constants.LpStatusInfeasible: print 'Model Infeasible catched in i='+str(i)+'' #'remove all the existing .mps' os.system('"del '+str('*.mps')+'"') #'create the .mps being transformed in .ilp' MILP.solve(pulp.PULP_CBC_CMD()) MPS_file_created = glob.glob("*.mps") #'transform the .mps into a .ilp' os.system('"C:\gurobi600\gurobi600\win64'+str(r'\bin')+'\gurobi_cl.exe ResultFile=violated_constraint.ilp ' +MPS_file_created[0]+'"') print HEMS_MILP I would like to know if this influences the solution and if so - how to use this method in ubuntu.
answer count: 0
type: UnansweredQuestion
has title: os.system Linux translation

http://stackoverflow.com/a/50950998
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50950575
has body: It's difficult to describe a recursive function in short. Please read the comments carefully. my_recursive_function will take the list and the index from which I want to calculate the sum If the index==list_length then I already traversed the list so in this case I shall return 0. If I have not completed traversing the list then I shall take the value of that index call my_recursive_function again from the next index. This is where recursion starts. Then return the sum of current index and value of next indices. For recursion we should place the recursion braking condition at the first portion of the function.Otherwise it may run infinitely. def my_recursive_sum(my_list, index): list_length = len(my_list) if index == list_length: # If i am next to the last element then return 0 and I won't go next and I shall go back return 0 return my_list[index] + my_recursive_sum(my_list, index + 1) # value of current index+value of next indices. a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] result = my_recursive_sum(a, 3) print(result)

http://stackoverflow.com/q/50886896
has title: Code works without functions, doesn't work with functions?
has body: I'm trying to learn PyGame for my A-Level final project, and i've started with Atari Breakout. I have it at a stage where the ball bounces around and off the paddle. However the code is very untidy so I wanted to put it into functions. The code works without functions: import pygame, sys from pygame.locals import * pygame.init() DISPLAYSURF = pygame.display.set_mode((1280, 720)) pygame.display.set_caption('Breakout') padX = 310 padY = 680 dotX = 150 dotY = 150 dotMX = -1 dotMY = -1 loss = False while loss != True: DISPLAYSURF.fill(pygame.Color(0,0,0)) for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() elif event.type == pygame.MOUSEMOTION: padX = event.pos[0]-75 if padX &lt; 3: padX = 3 elif padX &gt; 1127: padX = 1127 pygame.draw.rect(DISPLAYSURF, pygame.Color(0, 0, 255),(padX, padY, 150, 30)) dotX += dotMX dotY += dotMY if dotY &gt;= 720 - 30: loss = True #hor colis if dotX &lt;= 0 + 20: if dotMX == 1: dotMX = -1 else: dotMX = 1 elif dotX &gt;= 1280 - 20: if dotMX == 1: dotMX = -1 else: dotMX = 1 #vert colis if dotY &lt;= 0 - 20: if dotMY == 1: dotMY = -1 else: dotMY = 1 elif dotY &gt;= 720 - 20: if dotMY == 1: dotMY = -1 else: dotMY = 1 #pad colis if dotX &gt;= padX and dotX &lt;= padX + 150 and dotY == 665: if dotMY == 1: dotMY = -1 else: dotMY = 1 pygame.draw.circle(DISPLAYSURF, pygame.Color(255,0,0), (dotX, dotY), 20) pygame.display.update() But here's it but sectioned into functions: import pygame, sys from pygame.locals import * DISPLAYSURF = pygame.display.set_mode((1280, 720)) padX = 310 padY = 680 dotX = 150 dotY = 150 dotMX = -1 dotMY = -1 lives = 5 def main(padX, padY, dotX, dotY, dotMX, dotMY, lives): pygame.init() pygame.display.set_caption('Breakout') while lives != 0: DISPLAYSURF.fill(pygame.Color(0,0,0)) for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() elif event.type == pygame.MOUSEMOTION: padX = event.pos[0]-75 if padX &lt; 3: padX = 3 elif padX &gt; 1127: padX = 1127 pygame.draw.rect(…
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/88775514
has answer: http://stackoverflow.com/a/50887065
has answer: http://stackoverflow.com/a/50887068
has comment: http://stackoverflow.com/comment/88775488
type: UnansweredQuestion
tagged with: python
tagged with: pygame
has answer: http://stackoverflow.com/a/50887196
has comment: http://stackoverflow.com/comment/88775518
type: Question

http://stackoverflow.com/comment/88859871
score: 1
comment on: http://stackoverflow.com/a/50930250
type: AnswerComment
has text: Hi @Dark! Actually , think that will get rid of the space in the middle which we want to preserve.
type: Comment

http://stackoverflow.com/comment/89003747
has text: My bot does not work with voice part of discord.py, its just for text. So - what is the best way for me? How to use database if not uploaded on GitHub, as the application is?
score: 0
comment on: http://stackoverflow.com/q/51003926
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88943187
score: 0
type: QuestionComment
type: Comment
has text: yea I did, that was definitely the issue. Thanks for catching that!
comment on: http://stackoverflow.com/q/50973176

matplotlib-basemap
tags question: http://stackoverflow.com/q/50951790
tag name: matplotlib-basemap
type: Tag
tags question: http://stackoverflow.com/q/50992136
tags question: http://stackoverflow.com/q/50893731
tags question: http://stackoverflow.com/q/50928942
tags question: http://stackoverflow.com/q/50939821
tags question: http://stackoverflow.com/q/50958913

http://stackoverflow.com/comment/88805439
comment on: http://stackoverflow.com/q/50902319
has text: Maybe you can share the link from which you took the code, or post the code here?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88809822
has text: @aspiring1 pd autodiscovers valuetypes - your data probably has at maximum four `' ('` in it, so all those colums get datatype string/object - you probably have no column with 5 `' ('` in it, so the column gets default numeric type [how to check dtype of column](https://stackoverflow.com/questions/22697773/how-to-check-the-dtype-of-a-column-in-python-pandas/22697903) - `None` is the "null" type fo string/object, `NaN` for numeric - feel free to [accept as answer](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) then ;)
comment on: http://stackoverflow.com/a/50895082
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89005498
type: Comment
type: QuestionComment
has text: I'd start with checking for errors on the function calls. If the first call fails the second is useless.
comment on: http://stackoverflow.com/q/51005957
score: 1

http://stackoverflow.com/comment/89000352
score: 0
has text: Is there a way to change the canvas's color? Like make it's background black
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51002858

http://stackoverflow.com/q/50898854
has body: I have the file1 here: #File1 class MyClass1(): def abc(self) --- def efg(self) --- and here's the file2: #File2 from File1 import MyClass1 def test1() callfromfile1 = Myclass1() callfromfile1.abc() def test2() callfromfile1 = Myclass1() callfromfile1.efg() if __name__== "__main__": test() Prob: How to call test2 method only in terminal/command prompt? note: 1. I'm using python3 2. Should I need to add another "class (eg. MyClass2)" above in file2 in order to call the test2 specicifically? 3. Please give some example for reference.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88798201
has answer: http://stackoverflow.com/a/50899536
has comment: http://stackoverflow.com/comment/88798276
has comment: http://stackoverflow.com/comment/88798803
type: Question
has comment: http://stackoverflow.com/comment/88798011
has comment: http://stackoverflow.com/comment/88798704
tagged with: python
has title: How to run a method in terminal/command prompt using python
has comment: http://stackoverflow.com/comment/88798086
has comment: http://stackoverflow.com/comment/88797938
score: 0
has comment: http://stackoverflow.com/comment/88798918
answer count: 1

http://stackoverflow.com/comment/88852990
score: 0
has text: The line appears in a label, not the title bar at top
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50926888

http://stackoverflow.com/comment/88862162
score: 0
has text: I need to see the actual dates.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50931528

http://stackoverflow.com/comment/88911087
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50955674
type: Comment
has text: why did you blit everything at the end

http://stackoverflow.com/q/50894561
score: 0
has comment: http://stackoverflow.com/comment/88789631
tagged with: image-processing
type: Question
has title: making changes to a base64 string and saving it as an image
tagged with: base64
has comment: http://stackoverflow.com/comment/88789525
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88789673
has body: I'm converting an image to a base64 string in python, turning that into a list, making changes to a few characters and converting the base64 string back to an image. The purpose of this is to create glitch art, where small changes in the image's encoding can produce certain effects. This is what my code looks like: import base64 import random import string times = 0 with open(r"C:\Users\Justin\Desktop\image.jpg", "rb") as image: text = base64.b64encode(image.read()) text = str(text) text = list(text) char_no = len(text) while True: crpt_amn = input("how much do you want to corrupt the image? insert a value from 0 to " + str(char_no) + " ") try: if int(crpt_amn) &lt; 0: print("value is out of range!") elif int(crpt_amn) &gt; char_no: print("value is out of range!") else: break except ValueError: print("that isn't a number") while times &lt; (int(crpt_amn) + 1): picked = random.randint(0, char_no) if text[picked] == '/': times += 1 else: text[picked] = random.choice(string.ascii_letters) times += 1 text = ''.join(text) text = str.encode(text) text = base64.b64decode(text) filename = "out_img.jpg" with open(filename, "wb") as picture: picture.write(text) However, there seems to be an issue with converting text to str(text) to str.encode(text) and back to base64.b64decode(text) as the output image wouldn't open. The changes made to the base64 string are minuscule, and even if you set crypt_amn to 0, such that no changes are made to it, the output image still wouldn't open. I've tried getting rid of the whole corruption part and stripped down the code to just this: import base64 import random import string with open(r"C:\Users\Justin\Desktop\image.jpg", "rb") as image: text = base64.b64encode(image.read()) text = str(text) text = str.encode(text) text = base64.b64decode(text) filename = "out_img.jpg" with open(filename, "wb") as picture: picture.write(text) yet the output image is still unable to be opened. Is there any way to achieve the desired functionality, with the …
answer count: 0

http://stackoverflow.com/a/59555780
answers question: http://stackoverflow.com/q/50946003
downvote count: 0
type: Answer
has body: On Jupyter notebook, following worked for me !python -m pip install -U pyLDAvis Alternatively, run Anaconda prompt as administrator and execute the following (base) C:\Windows\system32&gt;conda install -c conda-forge pyLDAvis
score: 1
upvote count: 1

http://stackoverflow.com/comment/88737839
comment on: http://stackoverflow.com/a/50867741
type: AnswerComment
score: 0
has text: He technically didn't mention Python 3
type: Comment

datetime
tags question: http://stackoverflow.com/q/50930002
tags question: http://stackoverflow.com/q/50980606
tags question: http://stackoverflow.com/q/50931528
tags question: http://stackoverflow.com/q/50948852
tags question: http://stackoverflow.com/q/50859101
tags question: http://stackoverflow.com/q/50899612
tags question: http://stackoverflow.com/q/50929953
tags question: http://stackoverflow.com/q/50906899
tags question: http://stackoverflow.com/q/51010380
tags question: http://stackoverflow.com/q/50938688
tags question: http://stackoverflow.com/q/50875363
tags question: http://stackoverflow.com/q/50942291
tags question: http://stackoverflow.com/q/50937626
tags question: http://stackoverflow.com/q/50922533
tags question: http://stackoverflow.com/q/50867503
tags question: http://stackoverflow.com/q/51003239
tags question: http://stackoverflow.com/q/50906943
tags question: http://stackoverflow.com/q/50939369
tags question: http://stackoverflow.com/q/50871693
tags question: http://stackoverflow.com/q/50893955
tags question: http://stackoverflow.com/q/50953736
tags question: http://stackoverflow.com/q/50905048
tags question: http://stackoverflow.com/q/50869003
tags question: http://stackoverflow.com/q/50994585
tags question: http://stackoverflow.com/q/50926518
tag name: datetime
tags question: http://stackoverflow.com/q/50907764
tags question: http://stackoverflow.com/q/50963451
tags question: http://stackoverflow.com/q/50993527
tags question: http://stackoverflow.com/q/50917616
tags question: http://stackoverflow.com/q/50916462
type: Tag
tags question: http://stackoverflow.com/q/50856214
tags question: http://stackoverflow.com/q/50954686
tags question: http://stackoverflow.com/q/50895454
tags question: http://stackoverflow.com/q/50927753
tags question: http://stackoverflow.com/q/50900002
tags question: http://stackoverflow.com/q/50923929
tags question: http://stackoverflow.com/q/50894962
tags question: http://stackoverflow.com/q/50915609
tags question: http://stackoverflow.com/q/50996342
tags question: http://stackoverflow.com/q/51002344
tags question: http://stackoverflow.com/q/50909666
tags question: http://stackoverflow.com/q/50974899
tags question: http://stackoverflow.com/q/50993165
tags question: http://stackoverflow.com/q/50949680

http://stackoverflow.com/comment/88948433
type: AnswerComment
comment on: http://stackoverflow.com/a/50975699
type: Comment
has text: Hi @C Haworth If this does not solve your issue, if you can explain more about what you are trying to accomplish, I'd be happy to help. Good Luck!
score: 0

http://stackoverflow.com/comment/88980408
type: QuestionComment
comment on: http://stackoverflow.com/q/50992705
has text: It looks like the installation script is finding a python version that does not support dictionary comprehension. You may have an old python installation (`2.6` or below) that's getting found before the `2.7`. What do you see when you run `python2 --version`? or even `python --version`?
score: 2
type: Comment

http://stackoverflow.com/q/50884835
type: Question
has title: Python function from C++ program
has body: Below is the logic program of the program I am trying to implement. #include -libraries- { int num, //Number of rows in the CSV file for(i=1; i&lt;=num, i++) { //Call python function //Input to python function - row number //It has to return elements from that particular row } } def row_elements(num): { //Read CSV file //Use Pandas package to fetch the data from CSV file } Can anybody please suggest me with an example how this could be implemented. Thank you.
has comment: http://stackoverflow.com/comment/88771683
downvote count: 0
score: 1
favorite count: 0
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has comment: http://stackoverflow.com/comment/88771633
tagged with: c++
answer count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/88772323

http://stackoverflow.com/comment/88963970
score: 0
type: Comment
type: QuestionComment
has text: Thank you :) log scale is better with real data thanks ;)
comment on: http://stackoverflow.com/q/50977764

http://stackoverflow.com/comment/88748023
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50873088
score: 0
has text: also the same for qfiledialog, you didn't provide any code so I've put something with standard arguments. If you are not using class, you can get rid off the self

http://stackoverflow.com/q/50856366
has comment: http://stackoverflow.com/comment/88715699
has answer: http://stackoverflow.com/a/50856783
upvote count: 1
answer count: 1
tagged with: string
favorite count: 0
tagged with: python-3.x
tagged with: byte
tagged with: python
type: AnsweredQuestion
has body: I am using python3.5, Let M = '\x09\x00\x00\x00\x01\x89\x02\xdb\xd6\x01\x49\x63\x74' Why is the left part of the following comparison not equal to the right part? &gt; M.encode() == b'\x09\x00\x00\x00\x01\x89\x02\xdb\xd6\x01\x49\x63\x74' $ FALSE the type of both is bytes. How can I reach from M to a variable that contains the right part of the above comparison?
downvote count: 0
score: 1
has title: byte vs str.encode in python3
type: Question
accepted answer: http://stackoverflow.com/a/50856783

http://stackoverflow.com/comment/88780891
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50889338
has text: I'm guessing my footnote wasn't enough to avoid the downvote, but I really didn't (and still don't) think that going into the (expertly crafted) detail that PM2 Ring did is worth it -- it's unlikely "the right answer", despite being explicitly asked for.
score: 0

http://stackoverflow.com/comment/88994388
type: AnswerComment
has text: Here still we are opening the file for every chunk(request) of a file. My question is there a way we can open it once on first request(chunk) and next chunk onwards, we should not open the file again, instead we should be able to append until last chunk is received.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50999438

http://stackoverflow.com/q/50950274
tagged with: numpy
has comment: http://stackoverflow.com/comment/88901902
answer count: 4
accepted answer: http://stackoverflow.com/a/50964764
has comment: http://stackoverflow.com/comment/88898407
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88898996
linked to: http://stackoverflow.com/q/651794
score: 1
favorite count: 0
has title: Searching large array by two columns
has comment: http://stackoverflow.com/comment/88898619
type: Question
has comment: http://stackoverflow.com/comment/88899073
tagged with: python
has answer: http://stackoverflow.com/a/50950931
has answer: http://stackoverflow.com/a/50954650
has comment: http://stackoverflow.com/comment/88901166
upvote count: 2
has comment: http://stackoverflow.com/comment/88899036
has comment: http://stackoverflow.com/comment/88901807
has answer: http://stackoverflow.com/a/50964764
possible better answer: http://stackoverflow.com/a/50950931
has answer: http://stackoverflow.com/a/50952472
has body: I have a large array, that looks like something below: np.random.seed(42) arr = np.random.permutation(np.array([ (1,1,2,2,2,2,3,3,4,4,4), (8,9,3,4,7,9,1,9,3,4,50000) ]).T) It isn't sorted, the rows of this array are unique, I also know the bounds for the values in both columns, they are [0, n] and [0, k]. So the maximum possible size of the array is (n+1)*(k+1), but the actual size is closer to log of that. I need to search the array by both columns to find such row that arr[row,:] = (i,j), and return -1 when (i,j) is absent in the array. The naive implementation for such function is: def get(arr, i, j): cond = (arr[:,0] == i) &amp; (arr[:,1] == j) if np.any(cond): return np.where(cond)[0][0] else: return -1 Unfortunately, since in my case arr is very large (>90M rows), this is very inefficient, especially since I would need to call get() multiple times. Alternatively I tried translating this to a dict with (i,j) keys, such that index[(i,j)] = row that can be accessed by: def get(index, i, j): try: retuen index[(i,j)] except KeyError: return -1 This works (and is much faster when tested on smaller data than I have), but again, creating the dict on-the-fly by index = {} for row in range(arr.shape[0]): i,j = arr[row, :] index[(i,j)] = row takes huge amount of time and eats lots of RAM in my case. I was also thinking of first sorting arr and then using something like np.searchsorted, but this didn't lead me anywhere. So what I need is a fast function get(arr, i, j) that returns &gt;&gt;&gt; get(arr, 2, 3) 4 &gt;&gt;&gt; get(arr, 4, 100) -1
downvote count: 1

http://stackoverflow.com/a/50878920
type: AcceptedAnswer
has body: You have a fundamental misunderstanding of how any and or work. I suggest going back and having a look at the documentation I've linked to on those. You want: names = ['M1','M2','M3','M4','M5','M6','M7','M8','M9','M10','M11', 'M12','M13','M14','M15','M16','M17','M18','M19','M20', 'TM1'] if any(name not in df.columns for name in names): ... else: print('incompatable dataset') Alternatively (and this is really just for minimal performance gain), you can use the set difference (returns all values than are in names but not in df.columns): if not set(names) - set(df.columns): ...
accepted answer of: http://stackoverflow.com/q/50878867
answers question: http://stackoverflow.com/q/50878867
type: Answer
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/a/52283965
upvote count: 3
type: AcceptedAnswer
type: Answer
score: 3
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50881227
answers question: http://stackoverflow.com/q/50881227
has body: I ended up finding a cleaner way to do this using OpenCV inspired from this gist: https://gist.github.com/pgorczak/95230f53d3f140e4939c#file-imgmatrix-py In my experience, this approach is somewhat faster and bypassing matplotlib enables full control of the output resolution. In addition, cv2.resize() can be used to rescale the image if necessary and the IMWRITE_JPEG_QUALITY argument can be used to set the JPEG export quality as a handle to control filesize. import itertools import cv2 import os import numpy as np #User defined variables dirname = "my_directory" #Name of the directory containing the images name = "my_image_name" + ".jpg" #Name of the exported file margin = 20 #Margin between pictures in pixels w = 8 # Width of the matrix (nb of images) h = 8 # Height of the matrix (nb of images) n = w*h filename_list = [] for file in os.listdir(dirname): if file.endswith(".JPG"): filename_list.append(file) filename_list.sort(); print(filename_list) imgs = [cv2.imread(os.getcwd()+"/"+dirname+"/"+file) for file in filename_list] #Define the shape of the image to be replicated (all images should have the same shape) img_h, img_w, img_c = imgs[0].shape #Define the margins in x and y directions m_x = margin m_y = margin #Size of the full size image mat_x = img_w * w + m_x * (w - 1) mat_y = img_h * h + m_y * (h - 1) #Create a matrix of zeros of the right size and fill with 255 (so margins end up white) imgmatrix = np.zeros((mat_y, mat_x, img_c),np.uint8) imgmatrix.fill(255) #Prepare an iterable with the right dimensions positions = itertools.product(range(h), range(w)) for (y_i, x_i), img in zip(positions, imgs): x = x_i * (img_w + m_x) y = y_i * (img_h + m_y) imgmatrix[y:y+img_h, x:x+img_w, :] = img resized = cv2.resize(imgmatrix, (mat_x//3,mat_y//3), interpolation = cv2.INTER_AREA) compression_params = [cv2.IMWRITE_JPEG_QUALITY, 90] cv2.imwrite(name, resized, compression_params)

http://stackoverflow.com/comment/88949181
score: 0
comment on: http://stackoverflow.com/a/50941698
type: AnswerComment
has text: I made a few changes. Intead of fromstring i used frombytes. Also, when I don't have the size of the file like I have in this case, how to go about that ? I tried using imgsize = rawData.size but that doesn't work.
type: Comment

http://stackoverflow.com/a/51004204
has body: Like @trollster said, it is indeed better to create dataframes for cust_sell and cust_buy. But let's understand what is not working with your code. When you do: for i in wb.index it means i will take the values of wb.index. And when you print wb.index, you get: Int64Index([0, 1, 2, 3, 4, 5, 6, 7], dtype='int64') Meaning i will take the values 1,2,3 ... So when you do: cust_sell.append([i]) what you are doing is adding to the list_cust_sell a list with inside a single element, i (an integer). If you want to add the entire row, you should use: cust_sell.append(list(wb.loc[i,:])) You will end up with a list of lists, each one containing a row
type: Answer
answers question: http://stackoverflow.com/q/51004029
score: 3
upvote count: 3
downvote count: 0

time-series
tags question: http://stackoverflow.com/q/50904088
tags question: http://stackoverflow.com/q/50888178
type: Tag
tags question: http://stackoverflow.com/q/50980594
tags question: http://stackoverflow.com/q/50860512
tags question: http://stackoverflow.com/q/50880760
tags question: http://stackoverflow.com/q/50951274
tags question: http://stackoverflow.com/q/50968112
tag name: time-series
tags question: http://stackoverflow.com/q/50863229
tags question: http://stackoverflow.com/q/50976950
tags question: http://stackoverflow.com/q/50914408

http://stackoverflow.com/a/52354943
type: Answer
answers question: http://stackoverflow.com/q/51005147
score: 34
downvote count: 1
has body: Releasing RAM memory For releasing the RAM memory, just do del Variables as suggested by @nuric in the comment. Releasing GPU memory This is a little bit trickier than releasing the RAM memory. Some people will suggest you the following code (Assuming you are using keras) from keras import backend as K K.clear_session() However, the above code doesn't work for all people. (Even when you try del Models, it is still not going to work) If the above method doesn't work for you, then try the following (You need to install the numba library first): from numba import cuda cuda.select_device(0) cuda.close() The reason behind it is: Tensorflow is just allocating memory to the GPU, while CUDA is responsible for managing the GPU memory. If CUDA somehow refuses to release the GPU memory after you have cleared all the graph with K.clear_session(), then you can use the cuda library to have a direct control on CUDA to clear up GPU memory.
upvote count: 35
has comment: http://stackoverflow.com/comment/91921646

http://stackoverflow.com/q/50916730
has title: Pre populating editable django admin form from other table
has body: this is the django admin panel with a table named Committees. there is a field named committee type in committees table. There is a table named default, with the model defined below, class default(models.Model): committee_type = models.CharField() description = models.CharField() quorum = models.InetgerField() What i wanted to do is, 1) when i select the committee type to city council in committees table in admin(like in screenshot), I wanted to populate the description and quorum from the default table in to the description and quorum in committees table in the admin itself 2) these populated data should be retrieved from default table where the committee type is city council 3) these fields should be editable in the committees table in admin after getting populated from the default table and should be able to be saved in this committee object Thanks in advance!
type: Question
tagged with: django-admin
tagged with: database
has answer: http://stackoverflow.com/a/78549189
tagged with: django-models
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/50920057
accepted answer: http://stackoverflow.com/a/78549189
tagged with: django
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50916869
has answer: http://stackoverflow.com/a/50916869

http://stackoverflow.com/a/50973474
answers question: http://stackoverflow.com/q/50972143
score: -2
downvote count: 2
has body: Since you have not given the format of intermediary column if more than one waypoint is there, I am giving solution for single waypoint. You basically have a tuple represented as a string in each cell value. So you need to remove the "extra string" part and convert it into tuple of floats. Fortunately, pandas has a function called applymap in which you can pass your custom function and it will apply to whole dataframe. &gt;&gt;&gt; import re, ast &gt;&gt;&gt; # My custom function &gt;&gt;&gt; def convert_to_float(tup): tup = re.sub(r"\'|\s+", '', tup) tup = ast.literal_eval(tup) return tup &gt;&gt;&gt; df = df.applymap(convert_to_float) &gt;&gt;&gt; df.iloc[0,0] (34.957055, 114.740156) &gt;&gt;&gt; type(df.iloc[0,0]) &lt;class 'tuple'&gt; &gt;&gt;&gt; type(df.iloc[0,0][0]) &lt;class 'float'&gt; Now you can extend this custom function for more than one waypoint in your data.
type: Answer
upvote count: 0

http://stackoverflow.com/comment/127561260
type: AnswerComment
has text: It should read now: ```cloud = io.read_point_cloud("cloud.ply")```
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52226098

http://stackoverflow.com/comment/88979585
comment on: http://stackoverflow.com/q/50991432
has text: Possible duplicate of [Selenium using Python - Geckodriver executable needs to be in PATH](https://stackoverflow.com/questions/40208051/selenium-using-python-geckodriver-executable-needs-to-be-in-path)
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/88725160
type: AnswerComment
comment on: http://stackoverflow.com/a/50859002
has text: The custom_settings belong there, they are per-spider settings (which override the project settings) and are confirmed working. As for the pipelines.py, I corrected the mistake, thank you. However, unfortunately Scrapy still does not save the images.
type: Comment
score: 0

http://stackoverflow.com/q/50862747
has answer: http://stackoverflow.com/a/50862811
has body: How to concatenate values from groups in a column to make the values of another column Lets say I have the following: df1 = pd.DataFrame({'Animal': ['Dog','Dog', 'Cat','Cat','Dog'], 'Date': ['01/08/18','01/09/18','01/12/18','02/23/18','01/15/18'], 'Meal': ['DogFood','Bone','Mouse','CatFood','Treat']} ) Animal Date Meal 0 Dog 01/08/18 DogFood 1 Dog 01/09/18 Bone 2 Cat 01/12/18 Mouse 3 Cat 02/23/18 CatFood 4 Dog 01/15/18 Treat Is it possible to use pandas to groupby Animal, Order by date, then concatenate the values of the Meal column to create a new column that looks like the following Animal Date Meal Order 0 Cat 01/12/18 Mouse Mouse CatFood 1 Cat 02/23/18 CatFood Mouse CatFood 2 Dog 01/08/18 DogFood DogFood Bone Treat 3 Dog 01/09/18 Bone DogFood Bone Treat 4 Dog 01/15/18 Treat DogFood Bone Treat
tagged with: concatenation
downvote count: 0
type: UnansweredQuestion
score: 1
favorite count: 0
type: Question
tagged with: pandas
tagged with: python
upvote count: 1
answer count: 1
has title: How to concatenate values from groups in a column in python

http://stackoverflow.com/a/51080600
type: Answer
has body: The problem is that you are adding the negated character class [^-\s] to a pattern already containing .*, a greedy dot pattern that matches any 0 or more characters other than a newline. .*\S+ will match any chars other than newline and then the last non-whitespace char (the + after \S is redundant in this case). Another issue is that re.findall searches for matches anywhere inside the string, but you only need a match at the start of the line. So, you need to add ^ anchor at the pattern start, or use re.match method. Here is a fix for your approach: results = [j for j in x if re.search(r'^hum[^-\s]*001$', j)] # =&gt; ['humabddd001', 'humhudiwhde001', 'hum0001ofejofrjwoorejfoejfo001', 'humifhihweoowhefiwofowfo001', 'humhumhufih001', 'humifwje001001'] See the Python demo online and the regex demo. Details ^ - start of string hum - a literal substring [^-\s]* - 0 or more - or whitespace chars 001 - a 001 literal substring $ - end of string. And as Patricks says, you do not really need a regex unless you want to easily handle all Unicode whitespace. In that case, you might use no_regex_results = [j for j in x if j.startswith('hum') and j.endswith('001') and '-' not in j and ' ' not in j] It is a bit longer and does not handle Unicode whitespace.
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/50919509
upvote count: 1

http://stackoverflow.com/comment/88923783
score: 3
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50963500
has text: `for user_id in filter(lambda x: x != target_user_id, user_dictionary):` should do

http://stackoverflow.com/comment/88998256
type: QuestionComment
has text: hi @schwobaseggl, I have tried with GET method, it is giving 200 status code. when I print p.text, it is showing some javascript code.
comment on: http://stackoverflow.com/q/51002133
score: 0
type: Comment

http://stackoverflow.com/q/50907880
tagged with: pandas
possible better answer: http://stackoverflow.com/a/50908037
tagged with: python
has body: I'm doing a data quality project using Python and Pandas. I have an input dataframe where each column is categorical data, and I want to return a dataframe where each column consists of the top 10 most frequently occuring categories in that column in order, together with the name of said categories (ie a key value pair or a tuple with Categorical variable : Count in each cell.)
has title: Data quality - Pandas
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50908983
accepted answer: http://stackoverflow.com/a/50908983
type: Question
has answer: http://stackoverflow.com/a/50908037
score: 0
answer count: 2

http://stackoverflow.com/a/50934524
has comment: http://stackoverflow.com/comment/88870163
type: AcceptedAnswer
upvote count: 9
has comment: http://stackoverflow.com/comment/93174289
type: Answer
has body: There is no need to use two separate Manager objects. As you have already seen the Manager object allows sharing objects among multiple processes; from the docs: Managers provide a way to create data which can be shared between different processes. A manager object controls a server process which manages shared objects. Other processes can access the shared objects by using proxies. Therefore if you have two different queues you can still use the same manager. In case it helps someone, here is a simple example using two queues with one manager: from multiprocessing import Manager, Process import time class Worker(Process): """ Simple worker. """ def __init__(self, name, in_queue, out_queue): super(Worker, self).__init__() self.name = name self.in_queue = in_queue self.out_queue = out_queue def run(self): while True: # grab work; do something to it (+1); then put the result on the output queue work = self.in_queue.get() print("{} got {}".format(self.name, work)) work += 1 # sleep to allow the other workers a chance (b/c the work action is too simple) time.sleep(1) # put the transformed work on the queue print("{} puts {}".format(self.name, work)) self.out_queue.put(work) if __name__ == "__main__": # construct the queues manager = Manager() inq = manager.Queue() outq = manager.Queue() # construct the workers workers = [Worker(str(name), inq, outq) for name in range(3)] for worker in workers: worker.start() # add data to the queue for processing work_len = 10 for x in range(work_len): inq.put(x) while outq.qsize() != work_len: # waiting for workers to finish print("Waiting for workers. Out queue size {}".format(outq.qsize())) time.sleep(1) # clean up for worker in workers: worker.terminate() # print the outputs while not outq.empty(): print(outq.get()) Using two managers instead like so: # construct the queues manager1 = Manager() inq = manager1.Queue() manager2 = Manager() outq = manager2.Queue() works but there is no need.
downvote count: 0
answers question: http://stackoverflow.com/q/50869656
has comment: http://stackoverflow.com/comment/93202443
accepted answer of: http://stackoverflow.com/q/50869656
score: 9

http://stackoverflow.com/a/50999374
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50884181
has comment: http://stackoverflow.com/comment/89022476
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/50884181
score: 3
upvote count: 3
has body: I think your problem is in middlewares, first of all you need to add some settings # settings.py # uncomment `DOWNLOADER_MIDDLEWARES` and add this settings to it DOWNLOADER_MIDDLEWARES = { 'scrapy_splash.SplashCookiesMiddleware': 723, 'scrapy_splash.SplashMiddleware': 725, 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware': 810, } # url of splash server SPLASH_URL = 'http://localhost:8050' # and some splash variables DUPEFILTER_CLASS = 'scrapy_splash.SplashAwareDupeFilter' HTTPCACHE_STORAGE = 'scrapy_splash.SplashAwareFSCacheStorage' And now run docker sudo docker run -it -p 8050:8050 scrapinghub/splash --disable-private-mode If i do all these steps a get back: scrapy crawl opentable ... 2018-06-23 11:23:54 [scrapy.core.engine] DEBUG: Crawled (200) &lt;GET https://www.opentable.com/new-york-restaurant-listings via http://localhost:8050/render.html&gt; (referer: None) 2018-06-23 11:23:54 [scrapy.core.scraper] DEBUG: Scraped from &lt;200 https://www.opentable.com/new-york-restaurant-listings&gt; {'bookings': [ 'Booked 44 times today', 'Booked 24 times today', 'and many others Booked values' ]}

http://stackoverflow.com/comment/106267078
has text: This approach has its place. I have a piece of stand alone software that has it's own webserver embedded on 443. This provides a very simple redirect w/o having to stand up nginx or apache.
type: Comment
comment on: http://stackoverflow.com/a/50914931
score: 1
type: AnswerComment

http://stackoverflow.com/a/50978581
downvote count: 0
has body: Salesforce does not support SELECT * FROM Object, you must include the specific fields that you want to be returned from the query, id the way you did in the first query. See the SOQL Syntax Help page here
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/50973254

http://stackoverflow.com/comment/88788501
type: QuestionComment
comment on: http://stackoverflow.com/q/50894168
has text: Please add your code with question
score: 2
type: Comment

http://stackoverflow.com/comment/88896464
type: QuestionComment
comment on: http://stackoverflow.com/q/50949476
type: Comment
has text: you can't with json. Use python dict repr + ast.literal_eval
score: 0

http://stackoverflow.com/comment/88733161
type: Comment
comment on: http://stackoverflow.com/q/50863516
has text: If you maintain a session, which you are, you should be able to subsequently issue a request to the "link to Titanic training". If the data is entire csv then that is what the response text will be after issuing that request. Using session and first using posting to the login page should authenticate and persist your session cookie.
type: QuestionComment
score: 0

http://stackoverflow.com/a/50876679
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50876492
has body: I think the way you have it is about as Pythonic as you can get working with lists. Any other option I can think of sacrifices either efficiency or legibility. You could do something like list(map(y.__add__, my_list)) OR list(map(partial(operator.add, y), my_list)) If you use an external dependency like numpy: list(np.array(my_list) + y) That's definitely not more efficient on its own though. It would only make sense if you wanted np.array(my_list) anyway, and didn't convert back to list.
answers question: http://stackoverflow.com/q/50876492
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/a/50979228
has body: I'm not an expert in Python. I vaguely remember running into this issue and when I added the following, it worked. But again, I was trying to import modules that are in different directory. sys.path.insert(0,'/user/mario/python/sampletest')
has comment: http://stackoverflow.com/comment/118242691
has comment: http://stackoverflow.com/comment/88957399
answers question: http://stackoverflow.com/q/50979073
type: Answer
downvote count: 2
upvote count: 0
score: -2
has comment: http://stackoverflow.com/comment/88980422

http://stackoverflow.com/comment/88787425
type: QuestionComment
comment on: http://stackoverflow.com/q/50893458
has text: Now it is saying pymysql.err.InternalError: (1049, "Unknown database 'test'")
score: 0
type: Comment

http://stackoverflow.com/comment/88761974
has text: A side note; having brackets around pretty much everything in this code is not necessary and actually makes it a lot harder to read. `if Shape[z] == 'Spherical':` is perfectly fine, as is `+ " " +`
type: Comment
comment on: http://stackoverflow.com/q/50879860
type: QuestionComment
score: 1

http://stackoverflow.com/q/50868998
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
possible better answer: http://stackoverflow.com/a/50869189
has title: How to combine Pandas dataframe according to unique column
type: AnsweredQuestion
score: 2
upvote count: 3
accepted answer: http://stackoverflow.com/a/50869213
downvote count: 1
type: Question
answer count: 2
tagged with: pandas
linked to: http://stackoverflow.com/q/43297589
has body: I have two CSV files. One is called 'master_registry.csv' and another one is 'master_reference.csv'. Both of these CSV files have a column called 'Master_Id'. I have filtered some values including 'Master_Id' from the 'master_registery.csv' and created new data frame called 'df' and also I have filtered some values including 'Master_Id' from 'master_reference.csv' and created a new data frame called 'df2'. So both of these data frames have 'Master_Id' column. Now I want to create new data frame by combining both 'df' and 'df2' data frames. Can anyone help me do this? # reading CSV from the directory master_registry = pd.read_csv('application/master_registry.csv') master_reference = pd.read_csv('application/master_registry.csv') # filtering some selected columns form the csv df = master_registry .filter(items=['Master_ID', 'Provider First Name', 'Provider Last Name (Legal Name)', 'Provider Credential Text', 'Provider Gender Code','Provider License Number State Code_1', 'Provider Business Practice Location Address City Name']) df2 = master_reference .filter(items=['Master_ID', 'Client_Reference_ID'])
has answer: http://stackoverflow.com/a/50869213
favorite count: 0
has answer: http://stackoverflow.com/a/50869189

http://stackoverflow.com/q/50898184
score: 2
has comment: http://stackoverflow.com/comment/88796348
has comment: http://stackoverflow.com/comment/88796202
tagged with: loops
has body: Consider the string s = "you'll never know the truth" if I want to split this string into 15 characters (s[:15]) I get "you'll never kn" What I want to do with this new string is only extract the complete words ('you'll' and 'never' in this case) and then return that string, and a way for my loop to start at the beginning of the incomplete word. Any idea how to do this? edit: as PM 2Ring has mentioned, I am only concerned with spacing acting as word separators for the moment. Once I figure that out I'll deal with commas, hyphens, newlines and the such. Thanks in advance!
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/88796627
has answer: http://stackoverflow.com/a/50898433
has comment: http://stackoverflow.com/comment/88796657
has comment: http://stackoverflow.com/comment/88796538
downvote count: 0
has answer: http://stackoverflow.com/a/50898431
tagged with: string
has comment: http://stackoverflow.com/comment/88796480
favorite count: 0
has title: Python: How to extract only complete words in a character chunk of x characters?
upvote count: 2
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/50906037
has body: I am having trouble adding conda to my environment variables on windows. I installed anaconda 3 though I didn't installed python, so neither pip or pip3 is working in my prompt. I viewed a few post online but I didn't find anything regarding how to add conda to my environment variables. I tried to create a PYTHONPATH variable which contained every single folder in Anaconda 3 though it didn't worked. My anaconda prompt isn't working too. :( so...How do I add conda and pip to my environment variables or path ?
has answer: http://stackoverflow.com/a/50909686
favorite count: 0
has answer: http://stackoverflow.com/a/77238587
has title: Add conda to my environment variables or path?
linked to: http://stackoverflow.com/q/45185057
upvote count: 8
tagged with: path
tagged with: python
has comment: http://stackoverflow.com/comment/88812072
has answer: http://stackoverflow.com/a/77758058
answer count: 4
type: AnsweredQuestion
score: 7
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/50906179
accepted answer: http://stackoverflow.com/a/50906179
tagged with: anaconda
possible better answer: http://stackoverflow.com/a/77758058
tagged with: environment-variables

http://stackoverflow.com/comment/118845001
type: Comment
has text: @alexei The first one works for your case. I just fixed a typo. Try it.
comment on: http://stackoverflow.com/a/66226151
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88949307
score: 0
type: AnswerComment
type: Comment
has text: You can use prange, this would also eliminate the need of function calls, however whether it will speed-up your code is unclear. @Arash
comment on: http://stackoverflow.com/a/50953072

http://stackoverflow.com/q/50931907
tagged with: beautifulsoup
type: UnansweredQuestion
tagged with: python
has body: I'm trying to add an href for every word which is inside a webpage and then save it again with added href. To do it I'm using BeautifulSoup and this code is working fine: wordToSearch = "war" for text in soup2.find_all(text=True): if re.search(r'(\w*)%s\b' %wordToSearch, text): text.replaceWith(BeautifulSoup(re.sub(r'(\w*)%s\b' % wordToSearch, r'%s' %(wordToSearch, wordToSearch), text, re.UNICODE), 'html.parser')) And then I write the new file with this code: with open("output1.html", "w") as file: file.write(str(soup)) This is working fine only if I need to add href to a single specific word, but I don't know how to do it if I want to add href for a list of words: listOfWords = ["war", "love"] for text in soup2.find_all(text=True): for a in listOfWords: if re.search(r'(\w*)%s\b' %a, text): text.replaceWith(BeautifulSoup(re.sub(r'(\w*)%s\b' %a, r'%s' %(a, a), text, re.UNICODE), 'html.parser')) This is what I get when I run it: Traceback (most recent call last): File "./test.py", line 110, in <module> text.replaceWith(BeautifulSoup(re.sub(r'(\w*)%s\b' % wordToSearch, r'%s' %(wordToSearch, wordToSearch), text, re.UNICODE), 'html.parser')) File "/Library/Python/2.7/site-packages/bs4/element.py", line 235, in replace_with "Cannot replace one element with another when the" ValueError: Cannot replace one element with another when theelement to be replaced is not part of a tree
score: 0
has title: Add a link for every word in a webpage using BeautifulSoup
has answer: http://stackoverflow.com/a/50936233
type: Question
answer count: 1

http://stackoverflow.com/a/50957408
has body: You could easily use pandas and its read_csv function to read the file and indeed matplot to plot the heat map. The first column (index column) may be the thing that is causing you trouble. You could either delete it (and use panda's brand new indexes) from you data, or, when you call the function, use it as your index_col in the read_csv function. import pandas as pd import matplotlib.pyplot as plt path_to_csv= "insert here the path to your csv file" df= pd.read_excel(path_to_csv ,index_col=0) plt.imshow(df,cmap='hot',interpolation='nearest') plt.show() I tried this script here with your data and it worked, I hope it helps you!
downvote count: 0
answers question: http://stackoverflow.com/q/50955504
type: Answer
upvote count: 7
score: 7

http://stackoverflow.com/q/50959385
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88916460
type: Question
has title: Importing a module from same directory 'unresolved reference'
linked to: http://stackoverflow.com/q/11725519
tagged with: setuptools
has answer: http://stackoverflow.com/a/50959432
has answer: http://stackoverflow.com/a/50959499
answer count: 2
score: 0
tagged with: python
has body: Update: found answer How can I import MyClass from classmodule? directory structure: /project /datagenerator __init__.py __main__.py classmodule.py setup.py Ran the program: python datagenerator Traceback (most recent call last): File "C:\Users\Matt\AppData\Local\Programs\Python\Python36-32\lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "C:\Users\Matt\AppData\Local\Programs\Python\Python36-32\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "datagenerator\__main__.py", line 2, in &lt;module&gt; from .classmodule import MyClass ImportError: attempted relative import with no known parent package __main__.py importing MyClass import sys from .classmodule import MyClass from .funcmodule import my_function def main(): print('in main') args = sys.argv[1:] print('count of args :: {}'.format(len(args))) for arg in args: print('passed argument :: {}'.format(arg)) my_function('hello world') my_object = MyClass('Thomas') my_object.say_name() if __name__ == '__main__': main() I tried this: from classmodule import MyClass Even though __main__.py and classmodule are in the same directory there is unresolved reference Unresolved reference 'classmodule'
tagged with: pycharm

http://stackoverflow.com/a/50993760
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/50911726
has body: This is an interesting question. I didn't know snakemake would not be able to solve this on it's own. A hack would be to tell snakemake which rule produces the files for refit_model rule refit_model: input: rules.process_x_and_y.output output: 'predictions_refit.txt' However, you can still get in trouble in a more complicated workflow, or if you try to run snakemake refit_model predict_model. Does the hack solve the problem for you? For a real solution i think snakemake would have to prune the DAG after creating it. I suggest you open a new issue here.
has comment: http://stackoverflow.com/comment/89029602
has comment: http://stackoverflow.com/comment/89030175
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/89029405

http://stackoverflow.com/q/50878618
type: AnsweredQuestion
type: Question
has body: I'm trying to create a python program that starts from a file.docx and a file.csv creates multiple .docx files. The problem is that the original file contains hyperlinks that are lost in the creation of new files this is my python program from docx import Document from docx.shared import Inches import csv import os f = open('file.csv') nometofind = '[nome]' cognometofind = '[cognome]' reader = csv.reader(f) next(reader) for row in reader: cognome=row[0] nome=row[1] nometoreplace = nome cognometoreplace = cognome document = Document('OriginalFile.docx') for par in document.paragraphs: par.text = par.text.replace(nometofind, nometoreplace) par.text = par.text.replace(cognometofind, cognometoreplace) document.save(nome+cognome+'.docx') f.close() and this is an example of may original docx [nome][cognome] email example@example.com the output files are like these output file 1-&gt; john smith email output file 2-&gt; mario rossi email
accepted answer: http://stackoverflow.com/a/50881025
has title: create multi file docx from a template within hyperlink in python
answer count: 1
tagged with: python-docx
score: 0
has answer: http://stackoverflow.com/a/50881025
tagged with: python

http://stackoverflow.com/a/51001668
answers question: http://stackoverflow.com/q/51000516
has body: In python, when a function returns nothing explicitly, it returns None. A function like print does an action but is not supposed to return anything, so it returns None. The print function could be something like this: import sys def print(*args, sep=' ', end='\n', file=sys.stdout, flush=False) for arg in args: file.write(str(arg)) if arg is not args[-1]: file.write(str(sep)) file.write(str(end)) if flush: sys.stdout.flush() Which is equivalent to: def print(*args, sep=' ', end='\n', file=sys.stdout, flush=False): # The same code return None And in both cases you will get &gt;&gt;&gt; print('Hello world') Hello world &gt;&gt;&gt; print(print('Hello world')) Hello world None Hope this helps.
downvote count: 0
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/comment/88947353
has text: Maybe I need to convert the bytes to a string first but how can I do that?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50974374

http://stackoverflow.com/a/50903110
upvote count: 3
accepted answer of: http://stackoverflow.com/q/50902939
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50902939
downvote count: 0
score: 3
type: Answer
has body: You code tries to create an unconnected FTP instance and then change in this unconnected instance to a directory called ftp://ftp.cdc.noaa.gov/Datasets/cpc_global_precip/. There are several things wrong with it: first you need to connect to the server, then you need to login (anonymous login in this case) and then you can change to the real directory instead of some URL used as directory name: import ftplib ftp = ftplib.FTP('ftp.cdc.noaa.gov') ftp.login('ftp','user@example.com') ftp.cwd('/Datasets/cpc_global_precip/') print(ftp.retrlines('LIST'))

http://stackoverflow.com/comment/88967101
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50963534
has text: The numbers will not overlap

http://stackoverflow.com/q/50956886
tagged with: qthread
type: Question
score: 2
type: AnsweredQuestion
has title: PyQt - Main hangs on QThread
tagged with: pyqt
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/50957788
accepted answer: http://stackoverflow.com/a/50957788
has body: I have a Python QT application that connects to a CG server (CasparCG). The QT application triggers a QThread which listens for hotkeys using the module pynput - and sends a command to CasparCG to playback different video files for each of the keys pressed. In the Main GUI, I can assign video files to a list of hotkeys, and I trigger the HotKey listening thread from a submenu item. self.actionStart_Hotkeys = QtWidgets.QAction(MainWindow) self.menuCasparCG.addAction(self.actionStart_Hotkeys) self.actionStart_Hotkeys.triggered.connect(self.StartHotkeys) The Main app and Ui_Window code is very long and has no problems - it functions like it should. Videos also playback as I would expect when the HotKeys are activated by pressing keys, but the Main window of the application freezes after a few video files are played - and I'm not sure why the main GUI is not responding to input after the HotKey thread is started. The code up until now looks like this.. from pynput import keyboard class HotKeys(QThread): def __init__(self, parent): QThread.__init__(self, parent) self.COMBINATIONS = [ {keyboard.KeyCode(char='0')}, {keyboard.KeyCode(char='1')}, {keyboard.KeyCode(char='2')}, {keyboard.KeyCode(char='3')}, ] self.caspar = None self.current = set() self.Connect() self.Listen() def exit(self, i): if not self.caspar == None: self.caspar.close sys.exit(i) def Connect(self): try: self.caspar = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.caspar.connect(("127.0.0.1", 5250)) print("Connected to caspar") except socket.error: print("CasparCG not running, or incorrect settings.xml") self.exit(0) def execute(self, k=None): # k is videofile movie = bytes("PLAY 1-20 {} \r\n".format(k), 'utf8') self.caspar.send(movie) def on_press(self, key): if any([key in COMBO for COMBO in self.COMBINATIONS]): self.current.add(key) if any(all(k in self.current for k in COMBO) for COMBO in self.COMBINATIONS): self.execute(key) def on_release(self, key): if any([key in COMBO for COMBO in self.CO…
upvote count: 2
tagged with: pyqt5

http://stackoverflow.com/a/51013277
downvote count: 0
answers question: http://stackoverflow.com/q/51010492
type: Answer
score: 1
has body: This line: print(" os.getcwd() " + os.getcwd()) showed that when Docker was running the CWD was /app. I added the settings folder to the sys.path: sys.path.append("/app/") sys.path.append("/app/smored/") sys.path.append("/app/smored/settings/") Then I was able to simplify DJANGO_SETTINGS_MODULE: os.environ['DJANGO_SETTINGS_MODULE'] = 'settings.test' django.setup() And then things finally worked. Hope this save someone the hours of headache this caused me.
upvote count: 1

http://stackoverflow.com/comment/89006544
type: Comment
type: QuestionComment
has text: Take a look at what seem to be similar questions in stackoverflow to see if they help you and let us know. https://stackoverflow.com/questions/29846087/microsoft-visual-c-14-0-is-required-unable-to-find-vcvarsall-bat and https://stackoverflow.com/questions/38949519/error-while-installing-lxml-through-pip-microsoft-visual-c-14-0-is-required and https://stackoverflow.com/questions/27670365/python-pip-install-error-unable-to-find-vcvarsall-bat-tried-all-solutions and https://stackoverflow.com/questions/39537303/error-microsoft-visual-c-10-0-is-required-unable-to-find-vcvarsall-bat-whi
score: 0
comment on: http://stackoverflow.com/q/51005141

http://stackoverflow.com/comment/90336927
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50958986
has text: Yep, this works. I did have some problems with the restart script sometimes not finding the `test.py` script (`can't open file 'c:\program': [Errno 2] No such file or directory`). I don't know why it's looking there, so I hard-coded the path to the script for now.

http://stackoverflow.com/comment/88833523
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50892578
has text: Is the tfrecords file created by the file writer empty? Are you pointing tensorboard to the directory in which this file is?
score: 0

http://stackoverflow.com/comment/88931351
score: 0
has text: Wow. This worked. Very weird though, why am I getting this error in python 2 and not in 3? Also, what's the difference between the two? (sorry, I don't have enough points to accept the answer)
type: Comment
comment on: http://stackoverflow.com/a/50967282
type: AnswerComment

http://stackoverflow.com/comment/89209775
type: Comment
type: QuestionComment
score: 0
has text: @Bird I have modified my code, moving the m2m to the room to mirror your example https://dpaste.de/kHGB, here is a template with the room and occupants, https://dpaste.de/3qGU
comment on: http://stackoverflow.com/q/50996038

http://stackoverflow.com/comment/114190608
score: 0
comment on: http://stackoverflow.com/a/50912377
has text: I was trying to upload a photo/video on ig but I need it to work on ramote debian server and autoit works with windows only + only gui, need help.
type: Comment
type: AnswerComment

http://stackoverflow.com/q/50994389
tagged with: python
has body: EDIT: replaced the example file with a real example; replaced the nbratoms variable by nbrbonds. Beginner question. I would like to optimize the following script for huge files (100G+). I've discovered the existence of itertools yesterday but don't have a clue. f = open(sys.argv[1], "r") out = open(sys.argv[2], 'w') lines = f.read().split('\n@&lt;TRIPOS&gt;MOLECULE') for i in lines: ii=i.split('\n@&lt;TRIPOS&gt;',4) header=ii[0] infos=header.split('\n')[2] nbrbonds=infos.split(' ')[2] if str(nbrbonds) in ii[2]: out.write('\n@&lt;TRIPOS&gt;MOLECULE'+str(i)) out.close() f.close() The processed file is composed of concatenated 200,000+ single MOL2 files (last example below). The idea of the script is to first split the input file into items delimited by two @&lt;TRIPOS&gt;MOLECULE (=first line of a new MOL2 file); then to split these items according to lines starting with @&lt;TRIPOS&gt; into 4 parts (i.e.,@&lt;TRIPOS&gt;MOLECULE, @&lt;TRIPOS&gt;ATOM, @&lt;TRIPOS&gt;BOND and @&lt;TRIPOS&gt;ALT_TYPE). For each single MOL2 file, I want to check if the value at the location of (the second)14 in the header (different in each single MOL2 file) @&lt;TRIPOS&gt;MOLECULE Z1198223644 14 14 0 0 0 USER_CHARGES occurs in the 3rd part (below) of the single file: @&lt;TRIPOS&gt;BOND 1 1 2 1 2 2 3 1 3 2 4 1 4 2 5 1 5 5 6 ar 6 5 11 ar ... If it does -> print it to outputfile with \n@&lt;TRIPOS&gt;MOLECULE as first line (essentially just the way a single MOL2 file looks). It seems to work as it is, but I fear it's way too amateur. Additionally, I don't know how to implement a step that would avoid that the output file starts with a double header mark like this @&lt;TRIPOS&gt;MOLECULE@&lt;TRIPOS&gt;MOLECULE Z1198223644 ... Any help welcome! I joined a file containing 6 concatenated MOL2 files; odd files are correct; even files - wrong. @&lt;TRIPOS&gt;MOLECULE Z1198223644 14 14 0 0 0 USER_CHARGES @&lt;TRIPOS&gt;ATOM 1 F1 23.5932 2.0831 -52.2012 F 1 LIG -0.15900 2 C2 22.4195 1.3866 -52.421…
has comment: http://stackoverflow.com/comment/88985342
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51000051
has comment: http://stackoverflow.com/comment/88985175
type: Question
tagged with: split
has comment: http://stackoverflow.com/comment/88984119
tagged with: python-itertools
answer count: 1
has comment: http://stackoverflow.com/comment/88984787
score: 0
has title: Optimize script for huge concatenated files / loop to discard defective items from list of files
has answer: http://stackoverflow.com/a/51000051

http://stackoverflow.com/q/51001782
tagged with: web-scraping
accepted answer: http://stackoverflow.com/a/51002141
has comment: http://stackoverflow.com/comment/88997987
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51002141
type: Question
has comment: http://stackoverflow.com/comment/88997895
tagged with: stocks
answer count: 1
has comment: http://stackoverflow.com/comment/88997844
has title: BeautifulSoup Scraping U.S. News Today Stock
tagged with: beautifulsoup
score: 0
has body: Using Python, I am trying to scrap a table of stocks under $10 from U.S. Today Money Stocks Under $10. And then add each element to a list (so that I can iterate through each stock). Currently, I have this code: resp = requests.get('https://money.usnews.com/investing/stocks/stocks-under-10') soup = bs.BeautifulSoup(resp.text, "lxml") table = soup.find('table', {'class': 'table stock full-row search-content'}) tickers = [] for row in table.findAll('tr')[1:]: ticker = str(row.findAll('td')[0].text) tickers.append(ticker) I keep getting the error: Traceback (most recent call last): File "sandp.py", line 98, in &lt;module&gt; sandp(0) File "sandp.py", line 40, in sandp for row in table.findAll('tr')[1:]: AttributeError: 'NoneType' object has no attribute 'findAll'
linked to: http://stackoverflow.com/q/47148872
tagged with: python
has comment: http://stackoverflow.com/comment/88997703

http://stackoverflow.com/comment/88768622
score: 1
comment on: http://stackoverflow.com/q/50883180
type: Comment
type: QuestionComment
has text: Even if you could get the source code there is no guarantee that the code would be portable, there is an awful lot of Microsoft specific APIs commonly used in C and C++ on Windows.

http://stackoverflow.com/q/50924878
has comment: http://stackoverflow.com/comment/88849775
has comment: http://stackoverflow.com/comment/88849160
type: UnansweredQuestion
tagged with: python
tagged with: interpreter
has comment: http://stackoverflow.com/comment/88849659
answer count: 0
has title: How to check a python 2 script for errors without execution
type: Question
tagged with: compilation
has body: Is there a way to check whether a python 2 script has any errors ? I need to check it using terminal! For python 3 I found python3 -m py_compile source.py and python3 -m compileall source.py and catching the result in a file will do the thing. and it works just fine from terminal, but not with python 2. I've Python 2.7.15rc1 installed.
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/88849084
score: 0

http://stackoverflow.com/comment/88826142
comment on: http://stackoverflow.com/a/50912638
has text: The idea is that you use the `json.load` to read a file into a dictionary in the `on_ready` event, and save to file with `json.dump` (You should glance through the documentation for these functions, but we don't use any of the fancy stuff). Which part are you having trouble with?
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/51082267
has comment: http://stackoverflow.com/comment/89246693
has comment: http://stackoverflow.com/comment/89245922
has comment: http://stackoverflow.com/comment/89247016
has comment: http://stackoverflow.com/comment/126009883
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89214301
has comment: http://stackoverflow.com/comment/89247081
score: 27
has body: The docs are a bit confusing. When describing the signature of the function that you pass to feval, they call its parameters preds and train_data, which is a bit misleading. But the following seems to work: from sklearn.metrics import f1_score def lgb_f1_score(y_hat, data): y_true = data.get_label() y_hat = np.round(y_hat) # scikits f1 doesn't like probabilities return 'f1', f1_score(y_true, y_hat), True evals_result = {} clf = lgb.train(param, train_data, valid_sets=[val_data, train_data], valid_names=['val', 'train'], feval=lgb_f1_score, evals_result=evals_result) lgb.plot_metric(evals_result, metric='f1') To use more than one custom metric, define one overall custom metrics function just like above, in which you calculate all metrics and return a list of tuples. Edit: Fixed code, of course with F1 bigger is better should be set to True.
upvote count: 27
accepted answer of: http://stackoverflow.com/q/50931168
answers question: http://stackoverflow.com/q/50931168
type: Answer
has comment: http://stackoverflow.com/comment/89153312
downvote count: 0

http://stackoverflow.com/comment/128878101
score: 1
has text: How do you load the cert file ?
type: AnswerComment
comment on: http://stackoverflow.com/a/51742931
type: Comment

semaphore
type: Tag
tags question: http://stackoverflow.com/q/50870061
tag name: semaphore

http://stackoverflow.com/comment/88927298
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50963466
has text: Ah, thanks. Those look great. For others reading this and not yet using Python3.7, there appears to be a backport available here: https://github.com/ericvsmith/dataclasses

http://stackoverflow.com/a/50935261
has comment: http://stackoverflow.com/comment/88869520
accepted answer of: http://stackoverflow.com/q/50934908
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/88875041
has body: Track all the occurences and print the 3rd one from the last. Can be optimized by using heapq. def run(): try: logfile = open('log.txt', 'r') ip_address_line_number = dict() for index,line in enumerate(logfile,1): x1 = line.split()[0] log_time = line.split()[4] if x1 in ip_address_line_number : ip_address_line_number[x1].append((index,log_time)) else: ip_address_line_number[x1] = [(index,log_time)] if x1 in ip_address_line_number and len(ip_address_line_number.get(x1,None)) &gt; 2: print('Last Line: '+ ip_address_line_number[x1][-3].__str__()) else: print(x1 + ' has 0-2 occurences') logfile.close except OSError as e: print (e) run()
type: AcceptedAnswer
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/88869695
has comment: http://stackoverflow.com/comment/88869993
has comment: http://stackoverflow.com/comment/88870261
answers question: http://stackoverflow.com/q/50934908
has comment: http://stackoverflow.com/comment/88869565

http://stackoverflow.com/q/50896452
has answer: http://stackoverflow.com/a/50896545
upvote count: 1
has body: most of the solutions which i submit in hackerrank are thrown timeout error, so i tried to find the execution time for one of the codes in sublime text 3 in my pc,and resulted in [finished in 220.5 sec] for an input of 2 million input. problem statement: https://www.hackerrank.com/challenges/py-the-captains-room/problem my solution: n=int(input()) l_list=list(map(int,(input().split()))) l_set=set(l_list) for i in l_set: c=l_list.count(i) if c==1: print(i) please help me in optimizing the code or is my system too slow???
linked to: http://stackoverflow.com/q/2600191
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52677160
downvote count: 0
score: 1
favorite count: 0
tagged with: python-3.x
type: Question
has title: execution time for python program
answer count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/88793789

http://stackoverflow.com/comment/88776038
has text: @PM2Ring thanks for confirming, I just had a hunch ;)
score: 0
comment on: http://stackoverflow.com/a/50887345
type: Comment
type: AnswerComment

http://stackoverflow.com/q/50986068
has title: Sort one column in ascending (alphabetically) but on the values of the other column in descending order? Look at the expected output carefully
downvote count: 1
type: Question
tagged with: sorting
upvote count: 3
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/50986230
favorite count: 0
has body: I have a dataframe like this: name value ray 20 sun 20 mom 10 ate 10 pea 7 kite 6 dance 5 I want to arrange this like: ray 20 sun 20 ate 10 mom 10 pea 7 kite 6 dance 5
has comment: http://stackoverflow.com/comment/88966893
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88967119
tagged with: python
score: 2
has answer: http://stackoverflow.com/a/50986352

http://stackoverflow.com/q/50870189
has comment: http://stackoverflow.com/comment/88742541
linked to: http://stackoverflow.com/q/53696243
has title: Changing font family in OpenCV Python using PIL
has comment: http://stackoverflow.com/comment/88747331
linked to: http://stackoverflow.com/q/37191008
type: Question
tagged with: opencv
tagged with: python-imaging-library
linked to: http://stackoverflow.com/q/47726854
has body: The above answer doesn't solve my problem. I am using cv2.putText() to put text over a video. This works as expected, but I am attempting to use a different font (not available in OpenCV). I understand that OpenCV is limited to the cv2.FONT_HERSHEY fonts, so I am using PIL with OpenCV to achieve this. I used this method with images and that experiment was successful. But I am failing when I try something similar on a video. import cv2 from PIL import ImageFont, ImageDraw, Image camera = cv2.VideoCapture('some_video.wmv') while cv2.waitKey(30) < 0: rv, frame = camera.read() if rv: font = ImageFont.truetype("calibrii.ttf", 80) cv2.putText(frame, 'Hello World!', (600, 600), font, 2.8, 255) cv2.imshow('Video', frame) I have the "calibrii.ttf" in the same directory and as I mentioned, this approach worked with images. Here is the error: cv2.putText(frame, 'Hello World!', (600, 600), font, 2.8, 255) TypeError: an integer is required (got type FreeTypeFont)
has comment: http://stackoverflow.com/comment/100264538
has answer: http://stackoverflow.com/a/50921014
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/88742157
score: 8
favorite count: 0
upvote count: 8
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/50984397
has title: Return value curve_fit
has comment: http://stackoverflow.com/comment/88964153
has comment: http://stackoverflow.com/comment/88963656
has body: Supposing that I have a function such as: def Gaussian(x,I,sigma): return I/(np.sqrt(2*np.pi*sigma))*np.exp(-x*x/(2*sigma*sigma)) If I use: popt, pcov = curve_fit(Gaussian, xVal, yVal) and then I print popt and pcov, I obtain respectively popt= [2.47388884 1.09054634] pcov= [[ 2.31740586e-04 -3.06314407e-06] [-3.06314407e-06 1.04053180e-04]] Could someone explain me what curve_fit of scipy.optimize returns? Reading online I've understand that pcov is the covariance matrix, but it's not to much clear what are the values of popt, with reference to the posted function. Thanks!
score: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88964775
answer count: 0
type: Question

http://stackoverflow.com/q/50906150
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88812338
type: Question
has comment: http://stackoverflow.com/comment/88818778
has comment: http://stackoverflow.com/comment/88812287
tagged with: if-statement
has comment: http://stackoverflow.com/comment/88814170
score: 0
has comment: http://stackoverflow.com/comment/88812631
answer count: 1
has comment: http://stackoverflow.com/comment/88812889
has answer: http://stackoverflow.com/a/50906473
has title: Python - Print out once when hit the if-else statement
tagged with: logic
has body: So I have been trying to play around abit with monitor - For those who doesn't know what monitoring is - basically what it means is that you are checking something etc element, url or whatever in a certain time and check again if it has been changed. What I want to do is that the program is doing a requests from the beginning to get the website URL - The url will automatic be redirected either to /password or without it. Then what I do is to check if password contains the URL - If it does.. Make a print out that password page is up and then send to discord only ONCE while it can print out password page is up as command but it should only print out to discord ONCE! Then opposite if the password changes from /password to no password - it should say password page is down and then print out that it is down and send to discord ONCE that is has been down This is what I have done and url = 'mrcnoir' while True: try: password_page = requests.get('https://{}.com'.format(url)) password_page.raise_for_status() except: print('Error checking password page! - https://{}.com'.format(url)) continue else: # *************---If password up---************** if ('password' in password_page.url): # Password page is up print('Password page is up! - ' + 'https://{}.com'.format(url)) if not ('password' in password_page.url): # No password page -&gt; password page # *************---Send to discord---************** print("SENDING...1") #Discord function will be added later time.sleep(random.randint(6, 12)) # *************---If password down---************** else: # Password page is down print('Password page is down! - ' + 'https://{}.com'.format(url)) if ('password' in password_page.url): # Password page -&gt; no password page # *************---Send---************** print("SENDING...2") #Discord function will be added laterthis print... time.sleep(random.randint(6, 12)) # *************---Retry between 6-12 random.---************** finally: time.sleep(random.randint(6, 12)) The problem im havi…
tagged with: while-loop

http://stackoverflow.com/comment/89124218
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50985811
has text: @LefterisS Thanks for the response. Yes, i actually went around and messed with BeautifulSoup but quickly caught 403Errors and looked through terms of services etc. I think you are not allowed to scrape off of google translate. Fortunately, i found a solution using [PyDictionary](https://pypi.org/project/PyDictionary/) which solved the issue easily. I have however encountered a problem in the next part of my program which I have trouble solving, you are welcome to try and answer it if you like.
score: 0

http://stackoverflow.com/comment/89594143
score: 0
type: AnswerComment
has text: I forgot to tag you :) @Ben.T
type: Comment
comment on: http://stackoverflow.com/a/50911248

http://stackoverflow.com/comment/88907077
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50953377
has text: I just go to example.com and then executescript

http://stackoverflow.com/a/50974709
score: 0
type: Answer
has body: I fixed this by giving an exit command that ends the loop and saves the JSON only once. During the loop itself only the data is aquired but no JSON saved. If you guys want the whole code, let me know.
answers question: http://stackoverflow.com/q/50954317
accepted answer of: http://stackoverflow.com/q/50954317
type: AcceptedAnswer

http://stackoverflow.com/comment/121675943
comment on: http://stackoverflow.com/q/50955005
has text: When it comes to mypy vs pycharm, I'm slowly finding that neither are perfect; which of course is frustrating. While mypy tends to be the standard it's annoying to have to go outside the IDE to have to utilize. I'm slowly starting to come around to this way of thinking.
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/89075230
type: AnswerComment
type: Comment
score: 0
has text: Thanks, that kind of what I wanted!! Just not sure about how the for loop works: `data = [line.strip() for line in parsed.stripped_strings]`
comment on: http://stackoverflow.com/a/50970069

http://stackoverflow.com/comment/89329508
score: 0
type: AnswerComment
has text: OK..thats a nice obsrvation anyway,, I will take it into consideration,thanks buddy
type: Comment
comment on: http://stackoverflow.com/a/51167398

http://stackoverflow.com/comment/88968416
type: Comment
score: 0
type: QuestionComment
has text: I don't understand? Do you want to put a tree in all the views (python functions, your application logic) or in all templates (HTML files, the visible part for the end user) ?
comment on: http://stackoverflow.com/q/50984980

http://stackoverflow.com/q/50986813
answer count: 1
has title: Error when using ffprobe with Django - Python2
score: 0
has answer: http://stackoverflow.com/a/50987109
type: UnansweredQuestion
tagged with: django
tagged with: ffprobe
tagged with: python
has body: I use Django and ffprobe to get duration of video thanks to this instruction but it have some issues. What can I try to fix it? My code: def getLength(filename): result = subprocess.Popen(['ffprobe', filename], stdout = subprocess.PIPE, stderr = subprocess.STDOUT) return [x for x in result.stdout.readlines() if "Duration" in x] class VideoListSerializer(ModelSerializer): class Meta: model = Video fields = [ 'id', 'user', 'video_file', 'video_name', ] def get_duration(self, obj): // print video_file --> '/users/2/videos/9.mp4' result = getLength(obj.video_file) return result Error I get: CreateProcess() argument 2 must be string without null bytes or None, not str Traceback error: Traceback: File "C:\Python27\lib\site-packages\django\core\handlers\exception.py" in inner 41. response = get_response(request) File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Python27\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view 58. return view_func(*args, **kwargs) File "C:\Python27\lib\site-packages\django\views\generic\base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "C:\Python27\lib\site-packages\rest_framework\views.py" in dispatch 489. response = self.handle_exception(exc) File "C:\Python27\lib\site-packages\rest_framework\views.py" in handle_exception 449. self.raise_uncaught_exception(exc) File "C:\Python27\lib\site-packages\rest_framework\views.py" in dispatch 486. response = handler(request, *args, **kwargs) File "C:\Python27\lib\site-packages\rest_framework\generics.py" in get 201. return self.list(request, *args, **kwargs) File "C:\Python27\lib\site-packages\rest_framework\mixins.py" in list 45. return self.get_paginated_response(serializer.data) File "C:\Python27\lib\…
linked to: http://stackoverflow.com/q/3844430
type: Question

http://stackoverflow.com/q/50958876
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88916301
has body: Ive just been starting out on the Tkinter module. Ive been trying to make a pop-up box that displays some text. Everytime i run it this error pops up: Canvas object has no attribute 'createtext' Here's the code: from tkinter import Tk, Canvas from datetime import date, datetime root= Tk() c = Canvas(root, width=500, height=500, bg='black') c.pack() c.createtext(100, 50, anchor=w, fill='red', font='Arial 28 bold underline', text='Final Countdown')
has comment: http://stackoverflow.com/comment/88915200
has title: Tkinter 'Canvas object has no attribute createtext' Error
score: 0
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
tagged with: tkinter
answer count: 0
has comment: http://stackoverflow.com/comment/88915630

http://stackoverflow.com/comment/89308876
type: Comment
has text: my point is you can't assume it's real - it has 12 possible non-real values.
comment on: http://stackoverflow.com/a/51120113
type: AnswerComment
score: 0

http://stackoverflow.com/a/50968643
answers question: http://stackoverflow.com/q/50963534
has body: Where your dataframe is df: I have assumed that all the values in the dataframe are strings, i.e. that is 01 is really "01" df Out[]: From To 0 01 02 1 02 03 2 03 04 3 04 05 # Make a copy of the df dataframe res = df.copy() # Set the 'final value' column to be equal to the maximum numerical value of the df dataframe res['final_value'] = df.values.astype(int).max() res Out[]: From To final_value 0 01 02 5 1 02 03 5 2 03 04 5 3 04 05 5 Now whenever df is updated, if you run: res = df.copy() res['final_value'] = df.values.astype(int).max() Then the result dataframe res will also be updated
score: 0
has comment: http://stackoverflow.com/comment/88965614
type: Answer

http://stackoverflow.com/comment/88952796
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50977971
type: QuestionComment
has text: Hmm... it's still pulling the entire paragraph. Could this potentially be happening because I am trying to parse out that string while scraping the site in beautiful soup?

http://stackoverflow.com/comment/88912424
has text: @DanielRoseman thanks for your comment, I'm a beginner coder in Python, can you please explain what it means?
comment on: http://stackoverflow.com/q/50957382
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50906128
tagged with: postgresql
score: 0
tagged with: relationship
has title: SQLAlchemy PostgreSQL row_to_json relationship
tagged with: python
has answer: http://stackoverflow.com/a/50914306
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/37010083
has comment: http://stackoverflow.com/comment/88820585
tagged with: http://stackoverflow.com/tag/json
tagged with: sqlalchemy
type: Question
has body: I wanted to know if it's possible to wrap the relationship using the server function jsonb or row_to_json instead of translatting the result in json using python. When I retrieves the Documentation, I want to have the Image object as a json. class Documentation(Base): __tablename__ = 'documentation' id = Column(UUID, server_default=text("uuid_generate_v4()"), primary_key=True) url = Column(String, nullable=False) description = Column(String) name = Column(String) image_id = Column(UUID,ForeignKey(Image.id)) image = relationship(Image,backref="image_data",lazy="subquery") class Image(Base): __tablename__ = 'image' id = Column(UUID, server_default=text("uuid_generate_v4()"), primary_key=True) name = Column(VARCHAR(128), nullable=False) info = Column(JSONB) image = Column(BYTEA) Exemple of the sql request that I want to translate using sqlalchemy: select doc.*, row_to_json(image.*) as image from documentation doc left join image on doc.image_id = image.id; SQLAlchemy (current request) q = Session.query(Documentation).all() Is it possible to do it using sqlalchemy serverside (on postgresql) ? (for performance issues) Thanks
has comment: http://stackoverflow.com/comment/88843442
answer count: 1

http://stackoverflow.com/a/50970342
accepted answer of: http://stackoverflow.com/q/50970170
has body: You can set the Mock.side_effect to be the original method. from unittest.mock import MagicMock class A(): def tmp(self): print("hi") def b(a): a.tmp() a = A() a.tmp = MagicMock(side_effect=a.tmp) b(a) a.tmp.assert_called() When side_effect is a function (or a bound method in this case, which is a kind of function), calling the Mock will also call the side_effect with the same arguments. The Mock() call will return whatever the side_effect returns, unless it returns the unnittest.mock.DEFAULT singleton. Then it will return Mock.return_value instead.
answers question: http://stackoverflow.com/q/50970170
has comment: http://stackoverflow.com/comment/88937118
has comment: http://stackoverflow.com/comment/88937099
score: 47
has comment: http://stackoverflow.com/comment/88937244
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/110556749
type: Answer
upvote count: 47
has comment: http://stackoverflow.com/comment/132729604
downvote count: 0
has comment: http://stackoverflow.com/comment/132728619

http://stackoverflow.com/q/50974070
score: 2
has answer: http://stackoverflow.com/a/50976463
downvote count: 0
has title: What is the most efficient way to sum a dict with multiple keys by one key?
accepted answer: http://stackoverflow.com/a/50976140
tagged with: python-2.7
possible better answer: http://stackoverflow.com/a/50976463
type: AnsweredQuestion
favorite count: 0
type: Question
upvote count: 2
tagged with: python
has answer: http://stackoverflow.com/a/50976140
tagged with: python-collections
has comment: http://stackoverflow.com/comment/88944457
answer count: 3
has comment: http://stackoverflow.com/comment/88944573
has comment: http://stackoverflow.com/comment/88946763
has body: I have the following dict structure. product1 = {'product_tmpl_id': product_id, 'qty':product_uom_qty, 'price':price_unit, 'subtotal':price_subtotal, 'total':price_total, } And then a list of products, each item in the list is a dict with the above structure list_ = [product1,product2,product3,.....] I need to sum the item in the list, group by the key product_tmpl_id ... I'm using dictcollections but it only sum the qty key, I need to sum key except the product_tmpl_id which is the criteria to group by c = defaultdict(float) for d in list_: c[d['product_tmpl_id']] += d['qty'] c = [{'product_id': id, 'qty': qty} for id, qty in c.items()] I know how to do it with a for iteration but trying to look for a more pythonic way thanks EDIT: What is need is to pass from this: lst = [ {'Name': 'A', 'qty':100,'price':10}, {'Name': 'A', 'qty':100,'price':10}, {'Name': 'A', 'qty':100,'price':10}, {'Name': 'B', 'qty':100,'price':10}, {'Name': 'C', 'qty':100,'price':10}, {'Name': 'C', 'qty':100,'price':10}, ] to this group_lst = [ {'Name': 'A', 'qty':300,'price':30}, {'Name': 'B', 'qty':100,'price':10}, {'Name': 'C', 'qty':200,'price':20}, ]
has answer: http://stackoverflow.com/a/51765803

http://stackoverflow.com/q/50969583
has answer: http://stackoverflow.com/a/77814798
has answer: http://stackoverflow.com/a/50970844
score: 4
tagged with: urllib
answer count: 2
has title: Pandas raises ssl.CertificateError when using method read_html for HTTPS resources
has comment: http://stackoverflow.com/comment/88937597
favorite count: 0
tagged with: pandas
tagged with: python
upvote count: 4
type: AnsweredQuestion
has body: I have a code that reads the contents of a web page using a url address. Earlier my code worked well, now there is a problem with the site security certificate. To solve the problem with IE, I completed importing the certificate to trusted sites, and the problem is solved. But when I run this code: df = pd.read_html(i,header=0)[0] I get an error: Traceback (most recent call last): File "D:\Distrib\Load_Data_from_Flat_ver_1.py", line 95, in &lt;module&gt; df = pd.read_html(i,header=0)[0] File "C:\Program Files\Python36\lib\site-packages\pandas\io\html.py", line 915, in read_html keep_default_na=keep_default_na) File "C:\Program Files\Python36\lib\site-packages\pandas\io\html.py", line 749, in _parse raise_with_traceback(retained) File "C:\Program Files\Python36\lib\site-packages\pandas\compat\__init__.py", line 385, in raise_with_traceback raise exc.with_traceback(traceback) ssl.CertificateError: hostname '10.89.174.12' doesn't match 'localhost' Can anyone help me with this problem?
downvote count: 0
accepted answer: http://stackoverflow.com/a/50970844
tagged with: python-requests
type: Question
possible better answer: http://stackoverflow.com/a/77814798
tagged with: ssl

nan
tags question: http://stackoverflow.com/q/50957993
tags question: http://stackoverflow.com/q/50890989
tags question: http://stackoverflow.com/q/50876425
tags question: http://stackoverflow.com/q/50876484
tags question: http://stackoverflow.com/q/50989814
tags question: http://stackoverflow.com/q/50993025
tag name: nan
tags question: http://stackoverflow.com/q/50966435
tags question: http://stackoverflow.com/q/50877663
type: Tag
tags question: http://stackoverflow.com/q/50910867

http://stackoverflow.com/comment/88772435
has text: I've added the output to that in my edit. I'm assuming it's saying the URL is wrong..? However `https://pypi.org/simple/pip/` still seems to be fine.
score: 0
comment on: http://stackoverflow.com/a/50885319
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50880284
tagged with: python
tagged with: matplotlib
type: Question
has answer: http://stackoverflow.com/a/50880867
has body: Ive created a simple histogram/KDE plot with seaborn and Im trying to add custom labels to the x-axis as follows: plt.title("Cond Density") plt.xlabel("Cond") plt.ylabel("Density") plt.xticks = (['Bob','Alex','Steve','Gwen','Darren']) sns.distplot(rawData['Conditions'], bins=20) sns.kdeplot(rawData['Conditions'], shade=True) plt.show() There are only 5 int elements in rawData['Conditions'], but the x-axis justs reflects the values in rawData['Conditions'], which are just [0,1,2,3,4]. What am I missing?
score: 0
answer count: 1
has title: Seaborn -xtick labels in KDE plot
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88762878

http://stackoverflow.com/q/51005829
has comment: http://stackoverflow.com/comment/90035730
has title: Press Ctrl+C to stop WebAgg server
answer count: 0
upvote count: 2
downvote count: 1
type: Question
has body: I'm running my code remotely using ssh -X command, but the prompt tells me to Press Ctrl+C to stop WebAgg server anytime the code gets to a plot command, and so my plot doesn't show at all. Is there a way to fix this? I have set matplotlib.use('TkAgg'), but it doesn't correct it either. Thanks
tagged with: matplotlib
tagged with: python-2.7
score: 1
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92265252
tagged with: python
linked to: http://stackoverflow.com/q/3453188

http://stackoverflow.com/comment/88889687
comment on: http://stackoverflow.com/a/50946145
type: Comment
score: 1
type: AnswerComment
has text: Nice dict comprehension answer! I just wanted to add, this solution has the further advantage on top of Rakesh's one that the fields with several '=' characters are correctly not split after the first (thanks to i.split('=', 1) as opposed to i.split('=')[1]).

http://stackoverflow.com/a/51004310
answers question: http://stackoverflow.com/q/51003611
accepted answer of: http://stackoverflow.com/q/51003611
upvote count: 4
type: AcceptedAnswer
downvote count: 0
score: 4
has body: by default parser.add_argument will use GET params (location='args'). To get POST data, you need to specify location='form' in its arguments: parser.add_argument('file', location='form')
type: Answer
has comment: http://stackoverflow.com/comment/89090164

http://stackoverflow.com/q/50946298
has body: I need to select the list that has a minimum value for each unique name after specifying the lists that have first priority for example The original nested list: lst=[[['ahmad','a',5],['ahmad','a',6],['ahmad','c',4],['Emme','b',5],['Emme','b',4]],[['ahmad','b',5],['ahmad','b',6],['ahmad','c',6],['ahmad','c',5],['Meno','c',4],['Emme','b',5],['Moo','b',4],['Moo','a',7],['Moo','a',5]]] Each list is expressed as: ['name', 'priority term', value]. The priority is for 'a' then 'b' and then 'c'. The desired result: new_lst=[[['ahmad','a',5],['Emme','b',4]],[['ahmad','b',5],['Meno','c',4],['Emme','b',5],['Moo','a',5]]] Update: If the list : lst=[[['ahmad','red',5,20,'a'],['ahmad','red',6,21,'a'],['ahmad','blue',4,15,'c'],['Emme','red',5,30,'b'],['Emme','red',4,12,'b']],[['ahmad','blue',5,10,'b'],['ahmad','blue',6,13,'b'],['ahmad','blue',6,15,'c'],['ahmad','blue',5,30,'c'],['Meno','green',4,40,'c'],['Emme','green',5,35,'b'],['Moo','red',4,7,'b'],['Moo','red',7,3,'a'],['Moo','red',5,18,'a']]] Each list is expressed as: ['name','color',value, trivial number, 'priority term']. the desired result: new_list=[[['ahmad','red',5,20,'a'],['ahmad','blue',4,15,'c'],['Emme','red',4,12,'b']],[['ahmad','blue',5,10,'b'],['Meno','green',4,40,'c'],['Emme','green',5,35,'b'],['Moo','red',5,18,'a']]]
type: AnsweredQuestion
score: 2
tagged with: list
downvote count: 0
has title: Filtering a nested list by select a list that have minimum value after determine the lists that have first priority?
type: Question
upvote count: 2
tagged with: sorting
tagged with: filter
answer count: 1
favorite count: 0
tagged with: nested-lists
has answer: http://stackoverflow.com/a/50946476
tagged with: python
accepted answer: http://stackoverflow.com/a/50946476

http://stackoverflow.com/comment/89008994
has text: Float16 would work, but with internal changes to defaults, like Epsilon you've mentioned. Although, unless you're on strict constraints with memory, I'd recommend using float32 or float64, because there might be other ops that would natively expect the input to be in that format.
type: Comment
comment on: http://stackoverflow.com/a/50984516
score: 0
type: AnswerComment

http://stackoverflow.com/a/50903150
has body: You'll need pivot_table (or pivot) and then a little housekeeping to reorder the axes and levels. (df1.pivot_table(index='def_desc', columns='J_col') .swaplevel(0, 1, axis=1) .sort_index(axis=1, level=[0,1], ascending=[False,True]) .fillna('') ) J_col us ca az desc_bal valid desc_bal valid desc_bal valid def_desc item1 45000 False item2 -120000 True item3 53000 True 2000 True item4 100 False item5 1000 True
accepted answer of: http://stackoverflow.com/q/50903077
type: Answer
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50903077
type: AcceptedAnswer

http://stackoverflow.com/comment/88841180
type: Comment
comment on: http://stackoverflow.com/q/50920805
score: 0
type: QuestionComment
has text: you need to use `.apply()` with a function inside, otherwise you are trying to make a list. please see https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html

http://stackoverflow.com/q/50886269
tagged with: merge
answer count: 4
has title: Efficient way to merge multiple large DataFrames
linked to: http://stackoverflow.com/q/58077949
has body: Suppose I have 4 small DataFrames df1, df2, df3 and df4 import pandas as pd from functools import reduce import numpy as np df1 = pd.DataFrame([['a', 1, 10], ['a', 2, 20], ['b', 1, 4], ['c', 1, 2], ['e', 2, 10]]) df2 = pd.DataFrame([['a', 1, 15], ['a', 2, 20], ['c', 1, 2]]) df3 = pd.DataFrame([['d', 1, 10], ['e', 2, 20], ['f', 1, 1]]) df4 = pd.DataFrame([['d', 1, 10], ['e', 2, 20], ['f', 1, 15]]) df1.columns = ['name', 'id', 'price'] df2.columns = ['name', 'id', 'price'] df3.columns = ['name', 'id', 'price'] df4.columns = ['name', 'id', 'price'] df1 = df1.rename(columns={'price':'pricepart1'}) df2 = df2.rename(columns={'price':'pricepart2'}) df3 = df3.rename(columns={'price':'pricepart3'}) df4 = df4.rename(columns={'price':'pricepart4'}) Create above are the 4 DataFrames, what I would like is in the code below. # Merge dataframes df = pd.merge(df1, df2, left_on=['name', 'id'], right_on=['name', 'id'], how='outer') df = pd.merge(df , df3, left_on=['name', 'id'], right_on=['name', 'id'], how='outer') df = pd.merge(df , df4, left_on=['name', 'id'], right_on=['name', 'id'], how='outer') # Fill na values with 'missing' df = df.fillna('missing') So I have achieved this for 4 DataFrames that don't have many rows and columns. Basically, I want to extend the above outer merge solution to MULTIPLE (48) DataFrames of size 62245 X 3: So I came up with this solution by building from another StackOverflow answer that used a lambda reduce: from functools import reduce import pandas as pd import numpy as np dfList = [] #To create the 48 DataFrames of size 62245 X 3 for i in range(0, 49): dfList.append(pd.DataFrame(np.random.randint(0,100,size=(62245, 3)), columns=['name', 'id', 'pricepart' + str(i + 1)])) #The solution I came up with to extend the solution to more than 3 DataFrames df_merged = reduce(lambda left, right: pd.merge(left, right, left_on=['name', 'id'], right_on=['name', 'id'], how='outer'), dfList).fillna('missing') This is causing a MemoryError. I do not know what to …
has answer: http://stackoverflow.com/a/50998275
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50923275
has comment: http://stackoverflow.com/comment/88895933
score: 10
has answer: http://stackoverflow.com/a/50911015
tagged with: dataframe
upvote count: 10
type: Question
linked to: http://stackoverflow.com/q/37756991
has comment: http://stackoverflow.com/comment/88891098
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/51006726
has answer: http://stackoverflow.com/a/51006726
tagged with: out-of-memory
tagged with: pandas
has answer: http://stackoverflow.com/a/50923275
tagged with: python

http://stackoverflow.com/a/50995617
type: Answer
has comment: http://stackoverflow.com/comment/88998553
has comment: http://stackoverflow.com/comment/89003620
has body: Menu List: ScrollView + StackLayout - orientation='rl-tb' To create a scrollable stack of menu list with orientation from right to left, and then top to bottom, In kv file, set the stacklayout's width to window's width, width: Window.width In Python code, set the size_hint=(None, None) for the widgets that will be added dynamically. Please refer to the example for details. Note The attribute, orientation: 'vertical' is not a valid orientation for StackLayout. Stack Layout » orientation orientation Orientation of the layout. orientation is an OptionProperty and defaults to ‘lr-tb’. Valid orientations are ‘lr-tb’, ‘tb-lr’, ‘rl-tb’, ‘tb-rl’, ‘lr-bt’, ‘bt-lr’, ‘rl-bt’ and ‘bt-rl’. Example main.py from kivy.app import App from kivy.uix.relativelayout import RelativeLayout from kivy.uix.button import Button class RootWidget(RelativeLayout): def __init__(self, **kwargs): super(RootWidget, self).__init__(**kwargs) for i in range(100): btn = Button(text=str(i), size_hint=(None, None), width=40 + i * 5, height=90) self.ids.menu_list_scroll.add_widget(btn) class TestApp(App): title = "Kivy Scrollable StackLayout Orientation='rl-tb' Demo" def build(self): return RootWidget() if __name__ == "__main__": TestApp().run() test.kv #:kivy 1.10.0 #:import Window kivy.core.window.Window &lt;RootWidget&gt;: ScrollView: bar_width: 10 bar_color: 0, 1, 0, 1 # green bar_inactive_color: 1, 0, 0, 1 # red effect_cls: "ScrollEffect" scroll_type: ['bars'] size_hint: (1, None) size: (Window.width, Window.height) StackLayout: id: menu_list_scroll spacing: 5 size_hint_y: None width: Window.width height: self.minimum_height orientation: 'rl-tb' Output
score: 1
has comment: http://stackoverflow.com/comment/89013713
upvote count: 1
has comment: http://stackoverflow.com/comment/88998408
has comment: http://stackoverflow.com/comment/89017543
answers question: http://stackoverflow.com/q/50878126
has comment: http://stackoverflow.com/comment/88996147
downvote count: 0

http://stackoverflow.com/a/50963597
has body: A couple of things here. Firstly, you can do date calculations using datetime.timedelta. And secondly, you don't want to check that the date is equal to "today - 7", you want to check it is greater than that and less than or equal to today. So: seven_days_ago = today - timedelta(days=7) for x in query: if seven_days_ago &lt; x[1].date() &lt;= today: ...
answers question: http://stackoverflow.com/q/50963451
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/88923868
has comment: http://stackoverflow.com/comment/88923967
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50963451
type: Answer

http://stackoverflow.com/a/50928094
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50927751
has body: import os path = '.' lines = tuple(open('systems.txt', 'r')) print lines for system in lines: os.mkdir(os.path.join(path,(system)))

http://stackoverflow.com/q/50999001
accepted answer: http://stackoverflow.com/a/50999084
has answer: http://stackoverflow.com/a/50999348
has title: Can't create a class, Python3 (I'm a beginner)
has body: I want some help for the following question. I created this class. &gt;&gt;&gt;class CountFromBy: pass But I can't create objects from it. I want to make an increment counter. So input these codes, but they doesn't work in the way I assume. Like this: &gt;&gt;&gt;c = CountFromBy() &gt;&gt;&gt;c 0 &gt;&gt;&gt;c.increase() &gt;&gt;&gt;c.increase() &gt;&gt;&gt;c.increase() &gt;&gt;&gt;c 3 But, actually the result is: &gt;&gt;&gt;c = CountFromBy() &gt;&gt;&gt;c &lt;__main__.CountFromBy object at 0x042647F0&gt; How can I get the expected result?
upvote count: 7
possible better answer: http://stackoverflow.com/a/50999077
type: Question
has answer: http://stackoverflow.com/a/50999077
downvote count: 5
has comment: http://stackoverflow.com/comment/88991995
tagged with: class
answer count: 3
has answer: http://stackoverflow.com/a/50999084
favorite count: 0
has comment: http://stackoverflow.com/comment/88992172
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
score: 2

http://stackoverflow.com/q/50864935
has title: Error - Attempting to do parallel computing without protecting your import on a system that does not support forking.
has comment: http://stackoverflow.com/comment/88732791
answer count: 0
upvote count: 2
type: UnansweredQuestion
score: 2
type: Question
has body: I am using GridSearchCV in a Jupyter Notebook on a cluster. I have 128 cores that I'd like to use for the gridsearchcv, so i've set n_jobs = -1 Now I get an error, "ImportError: [joblib] Attempting to do parallel computing without protecting your import on a system that does not support forking. To use parallel-computing in a script, you must protect your main loop using "if name == 'main'". Please see the joblib documentation on Parallel for more information" I have since wrapped my code as suggested so in my Jupyter code chuck but it still gives the same error. How exactly do I apply the " "if name == 'main'" statement in my Jupyter notebook?
downvote count: 0
tagged with: python
favorite count: 0
tagged with: jupyter-notebook
has comment: http://stackoverflow.com/comment/90855505

http://stackoverflow.com/a/60517247
score: 4
has body: Had a bunch of weird encoding issues and also odd behavior with api gateway, originally received the body of the request at bytes and then after redeploying started to receive them as base64. Anyway this is the code that ended up working for me. import json import base64 import boto3 from requests_toolbelt.multipart import decoder s3client = boto3.client("s3") def lambda_handler(event, context): content_type_header = event['headers']['content-type'] postdata = base64.b64decode(event['body']).decode('iso-8859-1') imgInput = '' lst = [] for part in decoder.MultipartDecoder(postdata.encode('utf-8'), content_type_header).parts: lst.append(part.text) response = s3client.put_object( Body=lst[0].encode('iso-8859-1'), Bucket='test', Key='mypicturefinal.jpg') return {'statusCode': '200','body': 'Success', 'headers': { 'Content-Type': 'text/html' }}
answers question: http://stackoverflow.com/q/50925083
type: Answer
upvote count: 4
downvote count: 0

http://stackoverflow.com/q/50931232
has comment: http://stackoverflow.com/comment/88861444
has comment: http://stackoverflow.com/comment/88861806
favorite count: 0
has answer: http://stackoverflow.com/a/50931690
has answer: http://stackoverflow.com/a/50931617
tagged with: python
answer count: 4
type: AnsweredQuestion
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50932918
type: Question
has body: I have the following function def foo(a, b=None, c=None, d=None) where of the optional parameters b, c, and d one and only one should be set to a numeric value (zero not allowed). The function should also accept other optional parameters, which I left out of the definition for the sake of clarity. To check this, I get the lists of the parameter values and names as such: def foo(a, b=None, c=None, d=None): print(locals().keys()) print(locals().values()) which gives e.g.: foo(a=1, b=2) - dict_keys(['d', 'c', 'b', 'a']) dict_values([None, None, 2, 1]) as expected. The following list comprehension should then check the optional parameters against their value and only return the parameter with a true value. fov_arg = [(arg, list(locals().values())[i]) for i, arg in enumerate(locals().keys() \ if arg in ['b', 'c', 'd'] and list(locals().values())[i]] I could then assert len(fov_arg) == 1 to see that one and only one of the optional parameters was set. The locals().values() is wrapped into the list() call as I am using python3.6, where locals().values() returns a dict view, not a list. However, running the function with the list comprehension def foo(a, b=None, c=None, d=None): print(locals().keys()) print(locals().values()) fov_arg = [(arg, list(locals().values())[i]) for i, arg in enumerate(locals().keys() \ if arg in ['b', 'c', 'd'] and list(locals().values())[i]] foo(a=1, b=2) outputs the following: dict_keys(['d', 'c', 'b', 'a']) dict_values([None, None, 2, 1]) [('d', 'd'), ('c', 1), ('b', &lt;enumerate object at 0x7fd90c43ba20&gt;)] I expected the output to be [(b, 2)]. I do not understand why d and c are in this list, as their values are None. In addition, both of them show the wrong values, and the value of b is an enumerate object. To figure out what is going wrong, I rewrote the list comprehension into for i, arg in enumerate(locals().keys()): if arg in ['b', 'c', 'd']: if list(locals().values())[i]: print(arg, list(locals().values())[i]) Calling the function wit…
possible better answer: http://stackoverflow.com/a/50931690
has title: Check that one and only one optional function parameter is set and get its value
score: 1
has comment: http://stackoverflow.com/comment/88861575
has comment: http://stackoverflow.com/comment/88862008
has comment: http://stackoverflow.com/comment/88861608
upvote count: 1
tagged with: function
has answer: http://stackoverflow.com/a/50931418
accepted answer: http://stackoverflow.com/a/50931418
has comment: http://stackoverflow.com/comment/88861698
downvote count: 0

http://stackoverflow.com/a/50917738
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88857434
type: Answer
has comment: http://stackoverflow.com/comment/89094480
has comment: http://stackoverflow.com/comment/88870504
upvote count: 2
has comment: http://stackoverflow.com/comment/88871126
score: 2
answers question: http://stackoverflow.com/q/50911868
has comment: http://stackoverflow.com/comment/89115187
accepted answer of: http://stackoverflow.com/q/50911868
has body: Looks like selenium will let you do this by creating your own class. Check out the documentation here: http://selenium-python.readthedocs.io/waits.html Here's a quick example for your case. Note the key is to have a method named __call__ in your class that defines the check you want. Selenium will call that function every 500 milliseconds until it returns True or some not null value. class title_is_either(object): def __init__(self, locator, string1, string2): self.locator = locator self.string1 = string1 self.string2 = string2 def __call__(self, driver): element = driver.find_element(*self.locator) # Finding the referenced element title = element.text if self.string1 in title or self.string2 in title return element else: return False # Wait until an element with id='ID-of-title' contains text from one of your two strings somestring = "Title 1" somestring2 = "Title 2" wait = WebDriverWait(driver, 10) element = wait.until(title_is_either((By.ID, 'ID-of-title'), somestring, somestring2))

http://stackoverflow.com/a/50930299
has body: An alternative to strip for removing spaces at the beginning and end.. import re sentence = re.sub("^\s+|\s+$", "", sentence, flags=re.UNICODE)
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/50930190
downvote count: 0
score: 1

http://stackoverflow.com/comment/88902924
comment on: http://stackoverflow.com/q/50944475
has text: Such an array contains pointers to objects elsewhere in memory.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50960520
score: 5
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50960451
upvote count: 5
has comment: http://stackoverflow.com/comment/88917858
has body: import itertools for k in itertools.product(*lst): print(k)
answers question: http://stackoverflow.com/q/50960451
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/88917994

http://stackoverflow.com/a/50989628
has body: What I would do is keep everything within the class. Using an outside function just makes things harder to manage. That said you should use IntVar() instead of string var as this will aid us in keeping track of the time. My below code will check first if the timer is at 60. If so then start count down and add to counter. When the counter reaches zero the button has its command disabled and it no longer adds to the counter. The other thing I changed was adding a manager method for the timer. Because we are now using IntVar() all we need to do is a get() command followed by a -1 and an after() statement to keep the timer running until zero. I also cleaned up your code a little to follow the PEP8 standard. import tkinter as tk class Application(tk.Frame): def __init__(self,master): super(Application,self).__init__(master) self.bttn_clicks = 0 self.labelvariable = tk.IntVar() self.create_widgets() def create_widgets(self): self.labelvariable.set(60) self.thelabel = tk.Label(self, textvariable=self.labelvariable, font=('Helvetica',50)) self.thelabel.pack(side=tk.TOP) self.firstButton = tk.Button(self, text="Start", command=self.update_count) self.firstButton.pack(side=tk.TOP) def update_count(self): if self.labelvariable.get() == 60: self.manage_countdown() if self.labelvariable.get() != 0: self.bttn_clicks += 1 self.firstButton.config(text="Counter: {}".format(self.bttn_clicks)) else: self.firstButton.config(command=None) def manage_countdown(self): if self.labelvariable.get() != 0: self.labelvariable.set(self.labelvariable.get() - 1) self.after(1000, self.manage_countdown) if __name__ == '__main__': root = tk.Tk() root.title("Timer") app = Application(root).pack() root.mainloop()
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/50988574
accepted answer of: http://stackoverflow.com/q/50988574
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/q/50992019
tagged with: python
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/50992091
has body: I have a dataframe df user amount 1 18.90 2 1092.22 2 293.01 1 40.00 And I want to divide each users amount by the norm of that users amount. So, the resulting dataframe would be df user amount 1 0.4272 2 0.9658 2 0.2591 1 0.9042 Because the norm of user 1 is norm1=sqrt(18.90^2+40^2)=44.24, so we divide all user 1's amounts by norm1; and the norm of user 2 is norm1=sqrt(1092.22^2+293.01^2)=1130.84 so we divide all of user 2's amounts by norm2. So far, I have norms = df.groupby(['user'])['amount'].apply(lambda x: np.sqrt(np.sum(x**2))).values df.groupby(['user'])['amount'].divide(norms) &gt;&gt;&gt; AttributeError: Cannot access callable attribute 'divide' of 'SeriesGroupBy' objects, try using the 'apply' method but this gives the error above. norms is indeed calculated correctly, but then I can't seem to use the .divide() method on each users amount. How can I divide each users amount by the users amount norm?
score: 0
tagged with: pandas
has title: How to normalize a SeriesGroupBy object in pandas?
answer count: 1
accepted answer: http://stackoverflow.com/a/50992091

http://stackoverflow.com/a/50930909
downvote count: 0
type: Answer
upvote count: 2
answers question: http://stackoverflow.com/q/50930821
score: 2
has body: You are on track to do it properly. Just make sure step 3 in done in a datamigration (certainly not through django shell). This way you won't forget to run it on production. I'm pretty sure you can't do both add the column and setting the value to be the same as another column. To convince yourself, you can search for vanilla SQL implementation like https://stackoverflow.com/a/13250005/1435156
has comment: http://stackoverflow.com/comment/88860739

http://stackoverflow.com/q/50992063
tagged with: tuples
has comment: http://stackoverflow.com/comment/88979219
tagged with: pandas
has body: I'm trying to set a pandas column name to a tuple. Little notice: The column name is already a tuple that I'm trying to replace with another tuple. enter image description here I tried thistab.rename(columns = {valeur[0] : cle}, inplace = True ) 'cle' is my new tuple (6, 9), and 'valeur[0]' is the column name (7.25, 7.35). I'm getting the error : 'Names should be list-like for a MultiIndex'
upvote count: 2
has answer: http://stackoverflow.com/a/50992314
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88979204
tagged with: dataframe
type: Question
answer count: 2
score: 2
has answer: http://stackoverflow.com/a/50992227
has title: Set a tuple as column name in Pandas
downvote count: 0
favorite count: 0

http://stackoverflow.com/a/69978607
downvote count: 0
has body: Shortening @hpauli answer: your_2d_arry = np.stack(arr_of_arr_object)
type: Answer
answers question: http://stackoverflow.com/q/50971123
score: 15
upvote count: 15

http://stackoverflow.com/comment/128662342
type: Comment
comment on: http://stackoverflow.com/a/53672281
score: 0
type: AnswerComment
has text: A way that worked for me to find the path on Windows: First, go to "Add or Remove Programs" in settings and ATTEMPT to uninstall Tesseract. It will ask you if you want to uninstall Tesseract from this location, and you can copy that location down. Then, cancel uninstallation

http://stackoverflow.com/comment/89059155
has text: Thanks! This worked! Not enough upvotes yet to upvote your answer, but I tagged your answer as correct
type: AnswerComment
comment on: http://stackoverflow.com/a/50993941
score: 0
type: Comment

http://stackoverflow.com/q/50913166
has answer: http://stackoverflow.com/a/50913255
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: django
tagged with: python
has body: I'm new to Python and Django. This is a very basic question, but I can't find a straight answer: When writing my Django app, do I have to design the app itself differently if it's going to support WSGI? In other words, is WSGI purely a deployment decision, or does the app itself have to support WSGI by design? Can I just write an app without thinking about whether it's WSGI or not and flip a WSGI switch later on, or does WSGI stuff go deeper?
score: -1
downvote count: 1
type: Question
upvote count: 0
tagged with: wsgi
has title: Are WGSI and non-WSGI Django apps designed/written differently?

http://stackoverflow.com/comment/88856062
has text: Sorry Mac OS is my local distribution. I'm not sure how to find out the linux distribution on my AWS RDS.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/50918010
type: AnswerComment

http://stackoverflow.com/comment/88924200
has text: @sudonym- It is hours. In one day hours ends with 23 and starts with 00 and need to split this data day wise.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50962722

http://stackoverflow.com/q/50892817
has body: I wanna do some gitlab operation via python and gitlab-api. there is only one file called pg.py in my repository. url = 'http://xx.xx.xx.xx/api/v3/projects/4/repository/commits' data = {"id":4, "branch_name":"master","commit_message":"commit via api","actions":[{"action":"update","file_path":"pg.py"}]} files = {'file':('pg.py',open('/opt/commitapp/pg.py','rb'),'text/x-python',{'Expires':'0'})} headers = {"PRIVATE-TOKEN":"xxxx"} r = requests.post(url=url,data=data,files=files,headers=headers) but I got the reply: r.text u'{"error":"actions is invalid"}' besides, it this the right way to upload files?
answer count: 1
tagged with: gitlab
tagged with: gitlab-api
has title: how to commit a update via gitlab api?
type: UnansweredQuestion
tagged with: python
tagged with: python-gitlab
type: Question
has answer: http://stackoverflow.com/a/50893062
score: 0

http://stackoverflow.com/q/50949270
tagged with: mapnik
accepted answer: http://stackoverflow.com/a/50953096
tagged with: python
has answer: http://stackoverflow.com/a/50953096
type: AnsweredQuestion
has title: Mapnik stroke error
has body: I'm getting the following error when I run the program: AttributeError: 'module' object has no attribute 'stroke_linecap' sym = mapnik.LineSymbolizer() sym.stroke = mapnik.Stroke(mapnik.Color(171,158,137), 0.5) sym.stroke_width = 2 sym.stroke_linecap = mapnik.stroke_linecap.ROUND #Error is here
type: Question
has comment: http://stackoverflow.com/comment/88896311
score: 0
answer count: 1

http://stackoverflow.com/a/50936116
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/50936001
has body: you can add 3 additional columns to your dataframe by ranking from the 3 indexes for each row. df'1st', '2nd', '3rd' = df.iloc[:, [3,4,5]].apply(lambda x: pd.Series(x.sort_values(ascending=False).index), axis=1) outputs: Date Count_Doc Sum_Words ... 1st 2nd 3rd 0 2017-02-16 0.069946 3.839240 ... Russel 2000 S&amp;P 500 Nasdaq 1 2017-04-12 1.655428 3.667811 ... S&amp;P 500 Nasdaq Russel 2000 2 2017-04-19 2.371889 2.110689 ... Nasdaq Russel 2000 S&amp;P 500 3 2017-04-20 3.261538 2.995514 ... S&amp;P 500 Nasdaq Russel 2000 4 2017-05-02 0.738549 2.197852 ... S&amp;P 500 Nasdaq Russel 2000 here, i'm picking only the 3 columns whose names we want to sort, then applying a function row-wise which takes a series, sorts it, gets its indexes (i.e. names) and returns the indexes as a new series. this is then assigned to the new columns ['1st', '2nd', '3rd']. note, the sort order I used is descending, whereas in your example output you've just shown a random order.
upvote count: 1
type: Answer

http://stackoverflow.com/comment/88852134
has text: Is that your real code? If so, you have a typo in your `file_get_contents()`, you are concatenating variables instead of sending 3 parameters; you need commas.
comment on: http://stackoverflow.com/q/50926412
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88960434
has text: The criteria I was thinking about is the looping between 2 or more steps. Sorry for not being clear enough. I do not ask questions often here..
comment on: http://stackoverflow.com/q/50969793
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50999282
tagged with: string
favorite count: 0
has body: I am new in programming...My code is very simple. Let's say my number is '123' then i want to get 'abc' .please check where i am wrong def number2char(number): search_array = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"] replace_array = ["a", "b", "c", "d", "d", "e", "f", "g", "h", "i"] num_2_char = number.replace(search_array, replace_array); return num_2_char; I am getting an error here like this num_2_char = number.replace(search_array, replace_array); TypeError: expected a character buffer object Please help me...
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50999309
has comment: http://stackoverflow.com/comment/88992591
tagged with: python
has answer: http://stackoverflow.com/a/50999327
score: 1
has comment: http://stackoverflow.com/comment/88992701
has title: Each character replace from string in python
type: Question
has comment: http://stackoverflow.com/comment/88992584
tagged with: replace
upvote count: 2
answer count: 3
downvote count: 1
has answer: http://stackoverflow.com/a/50999317

http://stackoverflow.com/a/50959387
downvote count: 1
has body: This is what i tried using JS See if this works for you in the similar way using python var resultTimestampLen = 0; arrLen = JSON.parse(sTot_resuts.results.length); for(var i = 0; i&lt;arrLen; i++){ speakerLablefrom = sTot_resuts.speaker_labels[resultTimestampLen].from; speakerLabelto = sTot_resuts.speaker_labels[resultTimestampLen].to; speakerId = sTot_resuts.speaker_labels[resultTimestampLen].speaker; var findSpeaker = new Array(); findSpeaker = sTot_resuts.results[i].alternatives[0].timestamps[0]; var timeStampFrom = findSpeaker[1]; var timeStampto = findSpeaker[2]; if(timeStampFrom === speakerLablefrom &amp;&amp; timeStampto === speakerLabelto){ console.log('Speaker '+sTot_resuts.speaker_labels[resultTimestampLen].speaker + ' ' + sTot_resuts.results[i].alternatives[0].transcript); var resultsTimestamp = new Array(); resultsTimestamp = sTot_resuts.results[i].alternatives[0].timestamps.length; resultTimestampLen = resultsTimestamp+resultTimestampLen; }else{ console.log('resultTimestampLen '+resultTimestampLen + 'speakerLablefrom '+speakerLablefrom + 'speakerLabelto '+speakerLabelto + 'timeStampFrom '+timeStampFrom + 'timeStampto '+timeStampto); } }
type: Answer
answers question: http://stackoverflow.com/q/50900340
score: 0
upvote count: 1

http://stackoverflow.com/comment/88968743
type: QuestionComment
has text: So, if I understand you correctly, you propose to just always run `process_x_and_y` and then dispose of `processed_y.txt`. This would indeed be an easy solution, but it is incomplete. I am interested in a solution where `process_x_and_y` is only executed when strictly necessary. For example, take into account that processing both x and y is more computationally expensive than just processing x. Another easy solution would be to have a `process_y` rule instead of a `process_x_and_y` rule, but also that doesn't work in my situation.
comment on: http://stackoverflow.com/q/50911726
score: 0
type: Comment

http://stackoverflow.com/a/51002805
answers question: http://stackoverflow.com/q/51001405
has comment: http://stackoverflow.com/comment/89003151
has comment: http://stackoverflow.com/comment/89003331
score: 2
has body: Because you are deploying with the bokeh server you can use the python handlers as described in the documentation about widgets. div = Div(text="&lt;img src='myapp/static/images/myimg.jpg'&gt;") menu = [("Img 1", "&lt;img src='myapp/static/images/myimg.jpg'&gt;"), ("Img 2", "&lt;img src='myapp/static/images/myimg2.jpg'&gt;")] def handler(attr, old, new): div.text = new dropdown = DropDown(labels="Images", menu=menu) dropdown.on_change("value", handler)
upvote count: 2
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/51001405
has comment: http://stackoverflow.com/comment/89001592
downvote count: 0

http://stackoverflow.com/comment/88749345
score: 2
comment on: http://stackoverflow.com/q/50873958
type: Comment
has text: This doesn't have anything to do with OOP, you're simply trying to iterate over a value of `None`.
type: QuestionComment

http://stackoverflow.com/q/50959172
tagged with: python
duplicate of: http://stackoverflow.com/q/39922986
accepted answer: http://stackoverflow.com/a/50959196
downvote count: 1
type: AnsweredQuestion
tagged with: dataframe
score: -1
type: Question
has body: Say I have a pandas data frame like the following: test = pd.DataFrame({'name':['John', 'David', 'John', 'Bob', 'Bob', 'Tim'], 'count' : [4, 5, 3, 2, 2, 1]}) How can I make a new data frame which merges the count values (adds) based on the values in the name column? The final result for this example should be: count name 0 7 John 1 5 David 2 4 Bob 3 1 Tim
upvote count: 0
has title: Merge count and row in pandas data frame if value in column matches
favorite count: 0
linked to: http://stackoverflow.com/q/39922986
has answer: http://stackoverflow.com/a/50959196
tagged with: pandas
answer count: 1

http://stackoverflow.com/q/50985856
tagged with: code-injection
type: Question
answer count: 2
has body: Is there any way that the following is dangerous? As in, can code get executed if someone prints this exception to stdout? def somefunc(val_from_untrusted_source): if val_from_untrusted_source == 'something_we_except': # do something useful pass else: raise RuntimeException('unknown input: {}'.format(val_from_untrusted_source))
tagged with: security
score: 0
has answer: http://stackoverflow.com/a/50986277
has title: Is it safe to put information from an untrusted source as python exception message?
possible better answer: http://stackoverflow.com/a/50986277
tagged with: python
has answer: http://stackoverflow.com/a/50987249
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50987249

http://stackoverflow.com/comment/88955471
type: AnswerComment
score: 0
type: Comment
has text: Thanks @Matt.G for the answer
comment on: http://stackoverflow.com/a/50979749

http://stackoverflow.com/q/50939088
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
tagged with: rasterio
score: 2
has title: 'rasterio._io.RasterReader' object has no attribute 'xy'
has comment: http://stackoverflow.com/comment/103853884
answer count: 0
tagged with: gis
type: Question
tagged with: tiff
has comment: http://stackoverflow.com/comment/89911264
has body: I'm trying to pull coordinate and pixel value data from a .TIF using rasterio. In recently updated documentation (April 2018) there appears to be a .xy() function to get the spatial coordinates of a pixel, with an example: &gt;&gt;&gt; dataset.xy(dataset.width // 2, dataset.height // 2) (476550.0, 4149150.0) However, when I run the same example: import rasterio dataset = rasterio.open('image.tif') dataset.xy(dataset.width // 2, dataset.height // 2) I receive error: "AttributeError: 'rasterio._io.RasterReader' object has no attribute 'xy'". Am I misinterpreting the documentation or is this something like pre-documentation for a future version? Is there another method for this in current release / official documentation that I haven't seen? Thank you!
downvote count: 0

http://stackoverflow.com/comment/89011151
has text: Welcome to SO. Please provide a **[mcve]**.
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51009146

http://stackoverflow.com/q/50988588
has answer: http://stackoverflow.com/a/50988838
score: -4
type: Question
accepted answer: http://stackoverflow.com/a/50988838
downvote count: 4
tagged with: pandas
upvote count: 0
has comment: http://stackoverflow.com/comment/88971836
answer count: 1
favorite count: 0
has title: Read in a csv file as a variable in python
tagged with: http://stackoverflow.com/tag/csv
has body: I wrote a Python Script which analyses CSV files. I want to implement a file picker, so when I execute the script it should open Windows Explorer and let me choose my file which it should analyse. So far it reads 1 file manually: import pandas as pd df= pd.read_csv('file1.csv', usecols=['col1', 'col2']) I want to replace file1.csv with a variable, so everytime I execute the script I can choose a different File. file = open.windowsexplorer (choose file from directory) df=pd.read_csv (' ' + file', usecols='col1', 'col2']) Furthermore I would like to do the same with the columns. So I can type in the column names I want to choose. In case in other Files the columns are named differently: column1 = type in here column2 = type in here (as a windows alert)
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/50957010
score: 0
has comment: http://stackoverflow.com/comment/88911509
answer count: 3
has comment: http://stackoverflow.com/comment/88913823
has comment: http://stackoverflow.com/comment/88913625
has comment: http://stackoverflow.com/comment/88913634
has comment: http://stackoverflow.com/comment/88911565
linked to: http://stackoverflow.com/q/39086
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50957153
has body: I have a txt file, k1=np.linspace(0,1,10) k2=np.linspace(0,2,10) k3=np.linspace(0,3,10) k4=np.linspace(0,4,10) np.savetxt('k.txt',np.transpose([k1,k2,k3,k4])) Now I wanna replace the second column (k2) to a new array k5=np.linspace(0,5,10) How to efficiently replace the column without reusing np.savetxt or a loop?
has comment: http://stackoverflow.com/comment/88911534
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88913670
has comment: http://stackoverflow.com/comment/88913733
has answer: http://stackoverflow.com/a/51000173
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/88913790
tagged with: arrays
has answer: http://stackoverflow.com/a/50958336
has title: How to replace a column in a txt file?
tagged with: replace

http://stackoverflow.com/comment/88768206
type: Comment
comment on: http://stackoverflow.com/a/50882960
type: AnswerComment
has text: Thanks a lot !, I will also look into the docs.
score: 0

http://stackoverflow.com/comment/97145987
type: Comment
comment on: http://stackoverflow.com/a/54875304
type: AnswerComment
has text: Thank you @C. Dautermann . By any chance have you come across a recent Python API for Instagram? I have not unfortunately. I'd like to backup all my pictures, posts and DM at once
score: 0

http://stackoverflow.com/comment/88990565
comment on: http://stackoverflow.com/q/50998203
score: 1
has text: Either use selenium webdriver, or pyautogui to do the cmd-r/ctrl-r keystroke
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50971385
type: Answer
has body: If the columns have the same name, you can get where you want with stack + pivot_table setting the aggregation function to sum. Setup import pandas as pd df = pd.DataFrame({'id1': [1,1,1,2], 'id2': [1,2,3,1], '1': [1,1,1,1], '2': [0,0,1,1], '3': [0,1,0,0], '4': [0,0,0,0], '5': [1,1,0,0], '6': [0,1,0,0]}) df = df.set_index(['id1', 'id2']) df.columns=['aaa','aaa','aaa','bbb','bbb','bbb'] aaa aaa aaa bbb bbb bbb id1 id2 1 1 1 0 0 0 1 0 2 1 0 1 0 1 1 3 1 1 0 0 0 0 2 1 1 1 0 0 0 0 Stack and pivot stacked = df.stack().reset_index() df = pd.pivot_table(stacked, index=['id1', 'id2'], columns='level_2', values=0, aggfunc='sum') df.columns.name=None print(df) aaa bbb id1 id2 1 1 1 1 2 2 2 3 2 0 2 1 2 0
score: 0
answers question: http://stackoverflow.com/q/50970063

http://stackoverflow.com/q/50923069
has body: I have two problem with this code. First, it doesn't remove the '\n' at the end of the list row. So I tried printing x to see what is going on but then I ran into the second issue which is that x doesn't get printed. It seems that some line breaks and '51' gets printed, but why only those but not others? How can this happen? I have absolutely no clue. Edit: This is NOT a duplicate. I want to know why it doesn't remove but ALSO why it doesn't print. @Aran-Fey Read the question before you mark it as duplicate. row = ['\n', '2017-18 ', '\n', 'GSW', '\n', '\n', '51', '\n', '32.0', '\n', '26.4', '\n', '8.4', '\n', '16.9', '\n', '49.5', '\n', '4.2', '\n', '9.8', '\n', '42.3', '\n', '5.5', '\n', '5.9', '\n', '92.1', '\n', '0.7', '\n', '4.4', '\n', '5.1', '\n', '6.1', '\n', '3.0', '\n', '1.6', '\n', '0.2', '\n', '2.2', '\n', '43.8', '\n', '5', '\n', '0', '\n', '9.5', '\n'] i = 0 for x in row: print(i,":", x) if x in ('\n', '°', '%'): row.remove(x) i+=1 print(row) The output of this is 0 : 1 : 2 : 3 : 51 4 : 5 : 6 : 7 : 8 : 9 : 10 : 11 : 12 : 13 : 14 : 15 : 16 : 17 : 18 : 19 : 20 : 21 : 22 : 23 : 24 : 25 : 26 : 27 : ['2017-18 ', 'GSW', '51', '32.0', '26.4', '8.4', '16.9', '49.5', '4.2', '9.8', '42.3', '5.5', '5.9', '92.1', '0.7', '4.4', '5.1', '6.1', '3.0', '1.6', '0.2', '2.2', '43.8', '5', '0', '9.5', '\n'] You can run this code here: https://repl.it/@leonardchoo/listnotworking
has comment: http://stackoverflow.com/comment/88846853
has comment: http://stackoverflow.com/comment/88846367
type: Question
score: 0
answer count: 2
tagged with: for-loop
has answer: http://stackoverflow.com/a/50923137
has comment: http://stackoverflow.com/comment/88846716
has comment: http://stackoverflow.com/comment/88846445
has comment: http://stackoverflow.com/comment/88847108
has title: Why can't I remove character from the list? Also why can't I even print the element?
has comment: http://stackoverflow.com/comment/88845397
linked to: http://stackoverflow.com/q/8312829
has comment: http://stackoverflow.com/comment/88847572
tagged with: python
has answer: http://stackoverflow.com/a/50923633
tagged with: list
has comment: http://stackoverflow.com/comment/88847777
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/6260089

http://stackoverflow.com/a/50876656
has comment: http://stackoverflow.com/comment/88766232
has comment: http://stackoverflow.com/comment/88763983
type: Answer
upvote count: 1
has body: Your problem is that you're never writing anything to your output, as if self.ok == 'T' will never evaluate to true. You should change it to just if self.ok, the same thing you did with ret. def update(self): ret, frame = self.video.read() if self.ok: self.out.write(frame) if ret: self.photo = PIL.ImageTk.PhotoImage(image=PIL.Image.fromarray(frame)) self.canvas.create_image(0, 0, image=self.photo, anchor=tkinter.NW) self.window.after(self.delay, self.update)
score: 1
answers question: http://stackoverflow.com/q/50875911
has comment: http://stackoverflow.com/comment/88759762
downvote count: 0

http://stackoverflow.com/comment/127552661
has text: While code-only answers might answer the question, you could significantly improve the quality of your answer by providing context for your code, a reason for why this code works, and some references to documentation for further reading. Brevity is acceptable, but fuller explanations are better
comment on: http://stackoverflow.com/a/72189491
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88873053
score: 0
type: QuestionComment
has text: Welcome to SO. As other said please post a [mcve](https://stackoverflow.com/help/mcve)
type: Comment
comment on: http://stackoverflow.com/q/50937231

http://stackoverflow.com/a/50974180
score: 10
has comment: http://stackoverflow.com/comment/88972093
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50971832
has comment: http://stackoverflow.com/comment/88952450
upvote count: 10
has body: You don't spell out the named tuple, reference just the name of the type in your List[] type: List[firefoxprofile] Put the type hint after a colon but before the = when used in an assignment, following PEP 526 Variable Annotations syntax: ffprofiles: List[firefoxprofile] = [] This sets ffprofiles to an empty list, and tells any type hint checkers that the contents of the list must be instances of the firefoxprofile type. If you wanted to provide some initial profiles in that list, just include them in the list literal, no need to append them afterwards. You assigned the class generated by namedtuple() to the name firefoxprofile so that’s what the rest of your code would use to reference it, and not by the name Profile. You may want to assign the namedtuple() result to the same name you passed in as the first argument, though, so Profile = namedtuple('Profile', ...). However, you probably also want to use the typing.NamedTuple class to define your typed named tuple instead; the post you linked to covered this but here it is applied to your example: from typing import Optional, NamedTuple, List class FirefoxProfile(NamedTuple): name: str path: str is_relative: bool default: Optional[str] ffprofiles: List[FirefoxProfile] = [ FirefoxProfile('Jason', 'Profiles/er5rtak4.Jason', True, None), # ... and more ] Defining a class that’s a subclass of typing.NamedTuple has the same result as using the namedtuple() function, except the syntax is a lot cleaner, you get to add types for the fields, and you can optionally add a docstring and additional attributes or methods (almost anything that's not a type-hinted attribute or a namedtuple method goes). Now the type hinting machinery will know much more about what is expected. Not only is it now clear what type of instances the list will contain, the above also documents what attributes the named tuple class supports and what type each those attributes have. I made some educated guesses as to what those types might be. I also used …
accepted answer of: http://stackoverflow.com/q/50971832
has comment: http://stackoverflow.com/comment/88978794

http://stackoverflow.com/comment/88852764
has text: Which version of PyQt is this?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50926888

http://stackoverflow.com/comment/88935698
comment on: http://stackoverflow.com/a/50969501
type: AnswerComment
score: 1
type: Comment
has text: Please no. Repeated string concatenations with `reduce` make the code both hard to read and inefficient.

http://stackoverflow.com/comment/88891890
has text: what does the original response look like, the r.text value ?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50939068
type: Comment

http://stackoverflow.com/comment/88906625
type: Comment
comment on: http://stackoverflow.com/a/50953482
score: 1
has text: You don't need to change it to a csv file first. Eliminate that part and I will mark it as answered.
type: AnswerComment

pymongo
tags question: http://stackoverflow.com/q/50969750
tags question: http://stackoverflow.com/q/50931571
tags question: http://stackoverflow.com/q/50922760
tags question: http://stackoverflow.com/q/50930535
tags question: http://stackoverflow.com/q/50936444
tags question: http://stackoverflow.com/q/50865125
type: Tag
tag name: pymongo
tags question: http://stackoverflow.com/q/50934212
tags question: http://stackoverflow.com/q/50944128
tags question: http://stackoverflow.com/q/50862291
tags question: http://stackoverflow.com/q/50921048

http://stackoverflow.com/a/50996172
answers question: http://stackoverflow.com/q/50995842
score: 5
has body: You can use the keyword_keys argument: edn_format.dumps({'a': 1}, keyword_keys=True) # =&gt; {:a 1} Or the Keyword constructor: edn_format.dumps({edn_format.Keyword('a'): 1}) # =&gt; {:a 1}
upvote count: 5
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50995842

calibration
tag name: calibration
tags question: http://stackoverflow.com/q/50909786
type: Tag

http://stackoverflow.com/comment/88765430
comment on: http://stackoverflow.com/q/50881505
score: 0
has text: @Ywapom could you use either of those to cleanly create a new "column" in a python nested list?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88778382
score: 0
type: Comment
type: QuestionComment
has text: Why there is no emoticon in the expected output?
comment on: http://stackoverflow.com/q/50888252

http://stackoverflow.com/q/50956724
has comment: http://stackoverflow.com/comment/88912105
upvote count: 5
has answer: http://stackoverflow.com/a/50969499
has body: Basic rundown of what I want the program to do: Aubio prints the frequency (pitch) and volume (volume) from what's being input from the microphone I want to iterate over the dictionary, and based on which frequency is output, print the color matching which key in the dictionary the frequency from samples is being put out I keep getting this error: Traceback (most recent call last): TypeError: '>' not supported between instances of 'numpy.ndarray' and 'str' Would anyone be able to help me? The code in question is the for statement import aubio import numpy as num import pyaudio import sys # Some constants for setting the PyAudio and the # Aubio. BUFFER_SIZE = 2048 CHANNELS = 1 FORMAT = pyaudio.paFloat32 METHOD = "default" SAMPLE_RATE = 44100 HOP_SIZE = BUFFER_SIZE//2 PERIOD_SIZE_IN_FRAME = HOP_SIZE index = 0 def main(args): # Initiating PyAudio object. pA = pyaudio.PyAudio() # Open the microphone stream. mic = pA.open(format=FORMAT, channels=CHANNELS, rate=SAMPLE_RATE, input=True, frames_per_buffer=PERIOD_SIZE_IN_FRAME) # Initiating Aubio's pitch detection object. pDetection = aubio.pitch(METHOD, BUFFER_SIZE, HOP_SIZE, SAMPLE_RATE) # Set unit. pDetection.set_unit("Hz") # Frequency under -40 dB will considered # as a silence. pDetection.set_silence(-40) # Infinite loop! while True: # Always listening to the microphone. data = mic.read(PERIOD_SIZE_IN_FRAME) # Convert into number that Aubio understand. samples = num.fromstring(data, dtype=aubio.float_type) # Finally get the pitch. pitch = pDetection(samples)[0] # Compute the energy (volume) # of the current frame. volume = num.sum(samples**2)/len(samples) # Format the volume output so it only # displays at most six numbers behind 0. volume = "{:6f}".format(volume) answer = pitch_detection(samples) # Finally print the pitch and the volume. print(str(pitch) + " " + str(volume) + (str(answer))) def pitch_detection(samples): colordict = { (0.0, 13.99): "Red", (14.00, 250.00): "Blue", } for index, key in enumerate(colordict,…
answer count: 2
downvote count: 4
has comment: http://stackoverflow.com/comment/88910948
has comment: http://stackoverflow.com/comment/88911086
favorite count: 0
tagged with: aubio
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
score: 1
has comment: http://stackoverflow.com/comment/88910978
has answer: http://stackoverflow.com/a/50956821
has title: TypeError: '>' not supported between instances of 'numpy.ndarray' and 'str'
has comment: http://stackoverflow.com/comment/88910938
type: Question

http://stackoverflow.com/q/50868589
answer count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/88770073
tagged with: dataset
has comment: http://stackoverflow.com/comment/88777808
has body: I am learning Machine Learning and trying to write a code from myself using the Iris Dataset. I open the dataset with pandas and then I am trying to pass a dictionary in my dataset to convert the last column from Strings into Int but when try this: dataset.columns = ['sepal length', 'sepal width', 'petal length', 'petal width', 'class'] class_mapping = {'Iris-setosa': 1, 'Iris-versicolor': 2, 'Iris-virginica': 3} for classe in dataset : classe['class'] = classe['class'].map(class_mapping) PyCharm returns me this: TypeError: string indices must be integers
linked to: http://stackoverflow.com/q/10973766
has title: Python try to use .map()
tagged with: python
tagged with: dictionary
possible better answer: http://stackoverflow.com/a/58783968
tagged with: indices
has answer: http://stackoverflow.com/a/50883169
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/58783968
type: Question
has comment: http://stackoverflow.com/comment/88752922
linked to: http://stackoverflow.com/q/1993840
has comment: http://stackoverflow.com/comment/88739141
accepted answer: http://stackoverflow.com/a/50883169
score: 0

http://stackoverflow.com/q/50880179
has body: I've been testing reading from the Graph API with an app I'm working on for a while. I've been reading events directly from their /{id} endpoints using the Python package. When I attempted this today, however, it didn't work. The response was as follows, when attempted using the Graph API Explorer. { "error": { "message": "Unsupported get request. Object with ID 'XXXXXXXXXXX' does not exist, cannot be loaded due to missing permissions, or does not support this operation. Please read the Graph API documentation at https://developers.facebook.com/docs/graph-api", "type": "GraphMethodException", "code": 100, "error_subcode": 33, "fbtrace_id": "HAli25GZ3N4 " } } The Explorer itself seems to know somehow that the object in question is an event, as the field options it gives in the left sidebar are all specific to Event objects. I'm aware you need to go through App Review to be able to read public Events, but I haven't needed to thus far. What's the issue? I've also checked the changelogs, that state nothing breaking has occured today in that instance. One thing to note was that I was briefly demoted to Moderator of the Page I'm trying to read from. I've tried using my personal Access Token and that of the Page too.
has comment: http://stackoverflow.com/comment/88807662
has comment: http://stackoverflow.com/comment/88763288
type: Question
has comment: http://stackoverflow.com/comment/88807864
score: 0
has title: Unable to retrieve events via the Facebook Graph API
tagged with: facebook-graph-api
answer count: 0
type: UnansweredQuestion
tagged with: facebook
has comment: http://stackoverflow.com/comment/88795740
tagged with: python

http://stackoverflow.com/q/50899028
type: UnansweredQuestion
tagged with: raspberry-pi
score: 2
downvote count: 0
favorite count: 0
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/50899908
upvote count: 2
tagged with: gpio
answer count: 1
has body: def callback(channel): print("WARNING! FLAME DETECTED!!!\n") pygame.mixer.music.play() firebase.post("/Report/Location", alamat) firebase.post("/Report/Time", masa) lcd_string(" FIRE DETECTED ",LCD_LINE_1) lcd_string(masa,LCD_LINE_2) print ("SUCCESSFULL REPORTED\n" +"Time : " + masa + "\nLocation : " + alamat) GPIO.add_event_detect(channel, GPIO.FALLING, bouncetime=300) # let us know when the pin goes HIGH or LOW GPIO.add_event_callback(channel, callback) # assign function to GPIO PIN, Run function on change # infinite loop while True: time.sleep(10) lcd_init() Hello, can someone explain me why this code above loop the function 2 time. This is more confusing me when i removed firebase.post("/Report/Location", alamat) firebase.post("/Report/Time", masa) the code doesn't loop the function.
has title: Function callback loop 2 times

http://stackoverflow.com/comment/88868550
type: QuestionComment
has text: @Leo Thank you! That was it. Problem solved. Since this is in a comment and not an answer I'm not sure how to upvote/mark as answer for you. This is my first question on stackoverflow. If you make an answer, I'll mark it.
score: 0
comment on: http://stackoverflow.com/q/50933983
type: Comment

http://stackoverflow.com/comment/88976639
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50981713
type: Comment
has text: I would like to thank you for this answer since you answered it and I'm still reading it :D

http://stackoverflow.com/q/50868723
answer count: 0
type: UnansweredQuestion
score: 0
type: Question
has comment: http://stackoverflow.com/comment/88759548
tagged with: image
has comment: http://stackoverflow.com/comment/88759491
has title: Compressing and formatting photos added into Word document with Python
has body: I want to automate adding photos into a word document using Python but sometimes run into issues with having too many photos and thus running into issues with Word freezing. Is there a way to compress the photos with the Document library? I also would like to have 6 photos to a page, but the end result with my current code places them as a single column. This is my code so far: import os from docx import Document from docx.shared import Inches file_list=[] for (dirname, dirs, files) in os.walk('.'): for filename in files: if filename.endswith('.jpeg'): file_list.append(filename) document = Document() for i in range(len(file_list)): document.add_picture(file_list[i],width=Inches(3.2))
has comment: http://stackoverflow.com/comment/88779897
tagged with: python
tagged with: ms-word

http://stackoverflow.com/comment/88924226
comment on: http://stackoverflow.com/q/50955275
type: Comment
score: 0
has text: [root@ora12c Python-3.6.5]# yum info openssl Installed Packages Name : openssl Arch : x86_64 Version : 1.0.1e Release : 48.el6 Size : 4.0 M Repo : installed [root@ora12c Python-3.6.5]# ssh -V OpenSSH_5.3p1, OpenSSL 1.0.1e-fips 11 Feb 2013
type: QuestionComment

http://stackoverflow.com/comment/89003451
type: QuestionComment
has text: A possible duplicate https://stackoverflow.com/questions/1779288/how-do-i-use-python-to-convert-a-string-to-a-number-if-it-has-commas-in-it-as-tho
comment on: http://stackoverflow.com/q/51004556
score: 0
type: Comment

http://stackoverflow.com/q/50904088
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/50698834
has answer: http://stackoverflow.com/a/50904820
score: 1
linked to: http://stackoverflow.com/q/6407362
type: Question
tagged with: time-series
answer count: 2
possible better answer: http://stackoverflow.com/a/50906623
has answer: http://stackoverflow.com/a/50906623
downvote count: 0
accepted answer: http://stackoverflow.com/a/50904820
has title: Deleting the same outliers in two timeseries
favorite count: 0
tagged with: outliers
has body: I have a question about eliminating outliers from two-time series. One time series includes spot market prices and the other includes power outputs. The two series are from 2012 to 2016 and are both CSV files with the with a timestamp and then a value. As example for the power output: 2012-01-01 00:00:00,2335.2152646951617 and for the price: 2012-01-01 00:00:00,17.2 Because the spot market prices are very volatile and have a lot of outliers, I have filtered them. For the second time series, I have to delete the values with the same timestamp, which were eliminated in the time series of the prices. I thought about generating a list with the deleted values and writing a loop to delete the values with the same timestamp in the second time series. But so far that has not worked and I'm not really on. Does anyone have an idea? My python code looks as follow: import pandas as pd import matplotlib.pyplot as plt power_output = pd.read_csv("./data/external/power_output.csv", delimiter=",", parse_dates=[0], index_col=[0]) print(power_output.head()) plt.plot(power_output) spotmarket = pd.read_csv("./data/external/spotmarket_dhp.csv", delimiter=",", parse_dates=[0], index_col=[0]) print(spotmarket.head()) r = spotmarket['price'].pct_change().dropna() * 100 print(r) plt.plot(r) Q1 = r.quantile(.25) Q3 = r.quantile(.75) q1 = Q1-2*(Q3-Q1) q3 = Q3+2*(Q3-Q1) a = r[r.between(q1, q3)] print(a) plt.plot(a) Can somebody help me?
upvote count: 1
tagged with: python

pca
tag name: pca
tags question: http://stackoverflow.com/q/50969962
type: Tag
tags question: http://stackoverflow.com/q/51008752
tags question: http://stackoverflow.com/q/50877791

http://stackoverflow.com/q/50955777
has title: Error when reading from input line in Python
duplicate of: http://stackoverflow.com/q/18332801
has body: Uses python3 import sys input = sys.stdin.read() tokens = input.split() a = int(tokens[0]) b = int(tokens[1]) print(a + b) I am trying to compile this simple code in Python. HOwever it gives me Index Error:List Index out of range. I just need to compile this code and then feed 2 digits to it at input line.
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/50955880
favorite count: 0
has answer: http://stackoverflow.com/a/50955804
tagged with: python
accepted answer: http://stackoverflow.com/a/50955880
type: AnsweredQuestion
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/50955804
upvote count: 1
downvote count: 1
type: Question
linked to: http://stackoverflow.com/q/18332801
has comment: http://stackoverflow.com/comment/88909178

http://stackoverflow.com/q/50981879
downvote count: 1
type: AnsweredQuestion
has title: Grouping of rows in a dataframe based on the date column
tagged with: group-by
has answer: http://stackoverflow.com/a/51311089
type: Question
score: 0
answer count: 1
favorite count: 0
tagged with: pandas-groupby
tagged with: pandas
accepted answer: http://stackoverflow.com/a/51311089
tagged with: python
has body: I am trying to use groupby to group the below data based on similar date rows with the following code but it doesn't work: df = df.reset_index() df = df.groupby(on='date') I am not able to get the correct syntax to work: Input: Expecting Result: Can someone provide me some pointers please?
tagged with: python-3.x
upvote count: 1

http://stackoverflow.com/comment/88901532
score: 0
type: Comment
type: QuestionComment
has text: As an update I discovered that when url_for() is used the issue occurs but if I hard code the links it seems to be a quick workaround.
comment on: http://stackoverflow.com/q/50910967

http://stackoverflow.com/a/50991095
score: 0
type: Answer
has body: You can use sets even if you do care about order. Just sort it: &gt;&gt;&gt; &gt;&gt;&gt; str1 = 'abcdefg' &gt;&gt;&gt; str2 = 'efghijk' &gt;&gt;&gt; ''.join(sorted(set(str1) &amp; set(str2), key = str1.index)) 'efg' &gt;&gt;&gt; ''.join(set(str1) &amp; set(str2)) 'egf' &gt;&gt;&gt; str2 = 'egfhijk' &gt;&gt;&gt; ''.join(set(str1) &amp; set(str2)) 'egf' &gt;&gt;&gt; ''.join(sorted(set(str1) &amp; set(str2), key = str1.index)) 'efg' &gt;&gt;&gt;
answers question: http://stackoverflow.com/q/50990854

http://stackoverflow.com/comment/88946198
type: Comment
score: 0
comment on: http://stackoverflow.com/a/50951846
has text: I can’t see your project so I can’t tell you what is going on with those other calls. I do note that you have *two* registrations for the `register/` route, one of which is never going to be used; perhaps you have more such anomalies in your project.
type: AnswerComment

http://stackoverflow.com/a/50866243
has body: Another alternative would be to create a function that returns a Series with your desired columns. Full example: import pandas as pd df = pd.DataFrame({ 'type':['A','A','A', 'B','B','B', 'C'], 'state':['NY','CA','NY', 'NY','CA','CA', 'WY'], 'date':['2018-01-02','2018-01-04','2018-02-06', '2018-01-01','2018-01-24','2018-02-10','2018-01-24'] }) df['date_ym'] = pd.to_datetime(df['date']).dt.strftime('%Y%#m') # switch # with - on linux def func(x): cnt = len(x) cnt_A = sum(x == 'A') return pd.Series({ 'total_count': cnt, 'total_type_A': cnt_A, 'percentage': cnt_A/cnt*100 }) df = df.groupby(['date_ym','state'])['type'].apply(func).unstack().reset_index() print(df) Returns: date_ym state total_count total_type_A percentage 0 20181 CA 2.0 1.0 50.0 1 20181 NY 2.0 1.0 50.0 2 20181 WY 1.0 0.0 0.0 3 20182 CA 1.0 0.0 0.0 4 20182 NY 1.0 1.0 100.0
answers question: http://stackoverflow.com/q/50865860
score: 2
accepted answer of: http://stackoverflow.com/q/50865860
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 2

http://stackoverflow.com/comment/88974976
type: Comment
type: QuestionComment
has text: are you on linux or windows ? do you know the path to the spark directory?
comment on: http://stackoverflow.com/q/50989747
score: 0

http://stackoverflow.com/a/50945929
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50945734
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/88889210
has body: You do not need to use pd.DataFrame.apply with a custom function. Instead, using vectorised methods available in Pandas: cols = cols_to_norm df_sub = df.loc[:, cols] df.loc[:, cols] = (df_sub - df_sub.min()) / (df_sub.max() - df_sub.min())
accepted answer of: http://stackoverflow.com/q/50945734

http://stackoverflow.com/q/50912844
has comment: http://stackoverflow.com/comment/88826414
has comment: http://stackoverflow.com/comment/88826238
answer count: 1
has answer: http://stackoverflow.com/a/50915413
type: UnansweredQuestion
tagged with: python
tagged with: parallel-processing
tagged with: c++
has comment: http://stackoverflow.com/comment/88826434
has title: How to use parallelism in cython
tagged with: cython
type: Question
tagged with: openmp
has body: I'm trying to apply parallelism to the following algorithm. This should be easily parallelizable, as the calculations are independent for the first three dimensions (b, i, j). def nb_forward(np.ndarray[FLOAT64, ndim=4] inputv, np.ndarray[FLOAT64, ndim=4] kernels, np.ndarray[FLOAT64, ndim=1] bias, tuple stride): cdef unsigned int kernel_size0 = kernels.shape[1], kernel_size1 = kernels.shape[2], \ stride0 = stride[0], stride1 = stride[1], \ num_dim = kernels.shape[0], \ num_filters = kernels.shape[3], \ batch_size = inputv.shape[0] cdef unsigned int out_size0 = (inputv.shape[1] - kernel_size0) / stride0 + 1, \ out_size1 = (inputv.shape[2] - kernel_size1) / stride1 + 1 cdef double[:, :, :, :] out = np.empty(shape=[batch_size, out_size0, out_size1, num_filters], dtype=np.float64) cdef unsigned int b, i, j, m, kw, kh, n cdef unsigned int iin, jin cdef double acc with nogil, parallel(): for b in prange(batch_size): for i in range(out_size0): for j in range(out_size1): iin = i*stride0 jin = j*stride1 for n in range(num_filters): acc = 0. for kw in range(kernel_size0): for kh in range(kernel_size1): for m in range(num_dim): acc += inputv[b, iin + kw, jin + kh, m] * kernels[m, kw, kh, n] out[b, i, j, n] = acc + bias[n] return out Error: Cannot read reduction variable in loop body Initially I tried to parallelize only at the level of b, since parallelizing at level b, i, j is at the pixel level and I do not know if it is worth generating as many threads. But I have not succeeded. I tried to use a temporary array out_batch, but being a numpy array, it is giving me a lot of problems and Error: malloc problems I have also tried instead of using numpy array using double arrays (double [:,:,:]) but it gives: Error: Memoryview slices can only be shared in parallel sections Does anyone have an idea? Is there any way to apply nogil at the level of b, i, j (or only b) and then compact the data?
score: 0

http://stackoverflow.com/comment/88901772
has text: Man... Thanks. I actually tried to use j2 with this : `for key in j2: value = j2[key]` But I got the `list indices must be integers or slices, not dict`
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50951774

http://stackoverflow.com/comment/88840365
has text: this maybe works for my case, but in my case the `name` are almost fixed, so, whether there is a better way for doing this? Such as if the length is not fixed, can not use `1, 6` for substr.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50920142
score: 1

http://stackoverflow.com/comment/88814864
comment on: http://stackoverflow.com/q/50906708
score: 0
type: QuestionComment
has text: How do I do that? Any link or code that you can write?
type: Comment

http://stackoverflow.com/a/50899381
type: Answer
has body: The authors do have a unique ID in Neo4j, the node ID. That can be used to identify the node and then the set the properties. Maybe something like this: Match (a:Author{LastName:'xxx',ForeName:'yyy'}) with a, id(a) as ID where ID &gt; -1 match (b) where id(b)=ID set b.first_name = author.ForeName, b.affiliation = author.AffiliationInfo.Affiliation The node's ID is not necessarily stable or predictable, so you have to access it directly before using it. Because you are using python code, you might to better with a global query to pull down the author node data: match (a:Author{LastName:'xxx',ForeName:'yyy'}) return a.LastName,a.ForeName,id(a) as ID then, you can write a csv file to bulk upload the desired info. The csv could look like this: &gt; "ID","ForeName","LastName","Affiliation" "26","David","Smith","Johns Hopkins" etc. The python code could do the filtering of nodes that do not need processing. Then load the file: LOAD CVS with HEADER file:///'xxx.csv' as line match (a) where id(a)=toInteger(line.ID) set a.Affiliation=line.toString(line.Affiliation")
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/88900237
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88992829
answers question: http://stackoverflow.com/q/50893573
upvote count: 1
has comment: http://stackoverflow.com/comment/88842674
accepted answer of: http://stackoverflow.com/q/50893573

http://stackoverflow.com/comment/88811200
comment on: http://stackoverflow.com/a/50905206
has text: @user2413548: not exactly, if you see `frequencies` is having different `keys` for every iteration. However, if there comes the same key then data will be overwritten. So, in that scenario I agree `append` should be intended, but if the user is sure that there won't be duplicate lines, then there shouldn't be any issue.
type: AnswerComment
type: Comment
score: 2

http://stackoverflow.com/a/50925882
answers question: http://stackoverflow.com/q/50925806
has comment: http://stackoverflow.com/comment/88850988
has comment: http://stackoverflow.com/comment/88850933
has comment: http://stackoverflow.com/comment/88851046
accepted answer of: http://stackoverflow.com/q/50925806
has comment: http://stackoverflow.com/comment/88851129
has body: Use the modulo % operator my_list = ['cleaner', 'list', 'cycle'] return my_list[(my_list.index(my_var) + 1) % len(my_list)]
has comment: http://stackoverflow.com/comment/88850993
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88850888
has comment: http://stackoverflow.com/comment/88850837
type: Answer
score: 7
has comment: http://stackoverflow.com/comment/88850861
upvote count: 7

http://stackoverflow.com/a/51022348
type: AcceptedAnswer
has body: after matplotlib import setting mpl.use('TkAgg') # or whatever other backend that you want solves the problem. As @Nils Werner added, unisntalling from conda and using pip solved the issue
answers question: http://stackoverflow.com/q/50969278
type: Answer
downvote count: 0
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50969278

http://stackoverflow.com/comment/89190029
score: 0
type: AnswerComment
type: Comment
has text: @Ach - you seem to try to redact my answer so the website-url and other site specific stuff is deleted from SO. What's that about?
comment on: http://stackoverflow.com/a/51023704

http://stackoverflow.com/comment/88773696
has text: you don't understand I guess... The root node parameter is like "Pearsons Ratio >= 1.0" and then, there are the two node child, for true and false... but this condition can never be true... still, there are [7, 53] in the corresponding True child node - 7 of class A and 53 of class B.
comment on: http://stackoverflow.com/q/50875274
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88907297
has text: yes, `+` a string/bytes object in a loop should have quadratic behavior. Recent versions try to optimize this, but it isn't always successful, and is a well known anti-pattern that you should avoid. Use `.join` Note, in Python 2, `bytes` is merely an alias for `str`
comment on: http://stackoverflow.com/q/50954839
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/a/58567829
has body: u,sigma,v = numpy.linalg.svd(A) is equal to u,sigma,v = scipy.sparse.linalg.svds(A,k=min(A.shape[0],A.shape[1])) u = -u[:,::-1] v = -v[::-1,:] sigma = sigma[::-1]
has comment: http://stackoverflow.com/comment/103454038
type: Answer
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/103453580
answers question: http://stackoverflow.com/q/50884533
upvote count: 3

http://stackoverflow.com/comment/88972284
score: 0
has text: @ukemi yes value is the attribute i want to filter, when `item=="stamp"`, `value` is equal to a timestamp in second, but in database it stored as TEXT and not INTEGER. @Ralf How can i convert `value` if `item==stamp` in the `QuerySet` ? you are right `str(100) < str(90)` and i think it can cause some problems. But if i inverse the `QuerySet`and begin by:`records=Record.objects.using("statool").filter(propertie__item="stamp", propertie__value__gt=str(int(timestamp_from.total_seconds())), propertie__value__lt=str(int(timestamp_to.total_seconds())),)` the query works but not if i apply a second
comment on: http://stackoverflow.com/q/50984298
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88896251
has text: To gather more information, try that: remove the ctypes import and the windll.user32 lines in your code. Recompile and see if the exe is thought to be a virus. Antiviruses use heuristic to detect if a file might be a new virus. It is possible that this access to clipboard is a frequent feature in known virus and that the antivirus is somehow able to detect it.
score: 0
comment on: http://stackoverflow.com/q/50949254
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50874729
score: 0
tagged with: tensorflow
type: Question
has title: Keras+tensorflow batch image classification
accepted answer: http://stackoverflow.com/a/50874914
answer count: 1
tagged with: keras
has body: I have service which should make response on classification of 10-20 images per request. now I process then one by one: with model_store.some_graph.as_default(): with model_store.some_session.as_default(): for i in images: x = image.img_to_array(i) x = preprocess_input(x) x = np.expand_dims(x, axis=0) pred = model_store.top_model.predict(x)[0] It takes 3-4 seconds( On CPU instance ) Is it possible to process them at one call? And if yes can it give any performance boost?
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50874914

http://stackoverflow.com/comment/88967745
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50965517
has text: @jpp So would you say that `newdict.get(x, np.nan)` is a faster solution if you want to handle unmapped values (instead of replace)?
score: 0

http://stackoverflow.com/comment/88808773
has text: `df.replace('\\','/')` escape a backslash when you wan't to use it
score: 1
comment on: http://stackoverflow.com/q/50904474
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50938988
type: AnsweredQuestion
favorite count: 0
has answer: http://stackoverflow.com/a/50939081
type: Question
tagged with: pandas
score: 3
tagged with: python
answer count: 1
downvote count: 1
accepted answer: http://stackoverflow.com/a/50939081
has body: Given the following sample df: Other1 Other2 Name Value 0 0 1 Johnson C 1 0 0 Johnson NaN 2 1 1 Smith R 3 1 1 Smith NaN 4 0 1 Jackson X 5 1 1 Jackson NaN 6 1 1 Jackson NaN I want to be able to fill the NaN values with the df['Value'] value associated with the given name in that row. My desired outcome is the following, which I know can be achieved like so: df['Value'] = df['Value'].fillna(method='ffill') Other1 Other2 Name Value 0 0 1 Johnson C 1 0 0 Johnson C 2 1 1 Smith R 3 1 1 Smith R 4 0 1 Jackson X 5 1 1 Jackson X 6 1 1 Jackson X However, this solution will not achieve the desired result if the names are not followed by one another in order. I also cannot sort by df['Name'], as the order is important. Is there an efficient means of simply filling a given NaN value by it's associated name value and assigning it to that? It's also important to note that a given Name will always only have a single value associated with it. Thank you in advance.
has title: Pandas Dataframe fillna() using other known column values
tagged with: dataframe
upvote count: 4

http://stackoverflow.com/q/50876332
has answer: http://stackoverflow.com/a/50904103
has comment: http://stackoverflow.com/comment/88768028
type: Question
has title: Flask backend not responding to JS frontend
has body: I want to able to send data from a Javascript frontend to a Flask python backend, and have the flask backend return the data. problem is that even though I can see the http post request arrives the post request is failed and nothing happens. frontend: button I want this to send the data to the server hosted at 127.0.0.1:5000 the backend: from flask import Flask, jsonify, render_template, request app = Flask(__name__) @app.route('/dostuff') def add_numbers(): a = request.args.get('url') return str(a) @app.route('/') def index(): return "hello world" nothing happens when the button is pressed even though the command line in which the flask server is running shows this when i press the button: 127.0.0.1 - - [15/Jun/2018 15:51:43] "POST /dostuff?url=15 HTTP/1.1" 200 -
tagged with: flask
score: 0
accepted answer: http://stackoverflow.com/a/50904103
answer count: 1
tagged with: web-applications
tagged with: python
has comment: http://stackoverflow.com/comment/88754630
type: AnsweredQuestion

http://stackoverflow.com/q/50878792
has title: Error with run Python program (Newbie)
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88759729
has body: I'm sorry if there was such a topic but I could not find an answer. So, let's start: someone created such a code for me, but unfortunately he did not tell me how to run it and the mess itself and not write back. I tried to solve the problem myself but unfortunately my knowledge is not yet at this level. Well, when I try to fire the code in VSC I see such a mistake c:\Users\XXX\AppData\Local\Programs\Python\Python36-32\Scripts&gt;main.py dane.xlsx Traceback (most recent call last): File "C:\Users\XXX\AppData\Local\Programs\Python\Python36-32\Scripts\main.py",line 21, in &lt;module&gt; if __name__ == "__main__": main() File "C:\Users\XXX\AppData\Local\Programs\Python\Python36-32\Scripts\main.py", line 8, in main xl = pd.ExcelFile(input("dane.xlsx")) File "C:\Users\XXX\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pandas\io\excel.py", line 394, in __init__ self.book = xlrd.open_workbook(self._io) File "C:\Users\XXX\AppData\Local\Programs\Python\Python36-32\lib\site-packages\xlrd\__init__.py", line 116, in open_workbook with open(filename, "rb") as f: FileNotFoundError: [Errno 2] No such file or directory: Here I give the code of 2 files, maybe there is a mistake in them: main.py from wp import wp import time import pandas as pd from selenium import webdriver def main(): chromedriver = "chromedriver.exe" xl = pd.ExcelFile(input("C:\Praca\dane.xlsx")) # Print the sheet names driver = webdriver.Chrome(executable_path=chromedriver) # Load a sheet into a DataFrame by name: df1 df1 = xl.parse('Sheet1') for data in df1.index: _wp = wp(driver,df1['Strona'][data]) _wp._login() _wp._send_data(df1['Tytul'][data],df1['Tresc'][data],df1['Data'][data],df1['Logo'][data],df1['Medium'][data],df1['Link'][data],df1['LinkA'][data]) if __name__ == "__main__": main() wp.py from datetime import datetime import time def get_time(): return str(datetime.now().strftime('[%H:%M:%S] ')) class wp(): def __init__(self,driver,base_url): self.base_url = base_url self.login = "xxx" self.p…
has comment: http://stackoverflow.com/comment/88759660
has answer: http://stackoverflow.com/a/50879036
has answer: http://stackoverflow.com/a/50878865
type: Question
score: 0
answer count: 2
tagged with: python

http://stackoverflow.com/a/50882542
type: Answer
answers question: http://stackoverflow.com/q/50878862
has body: It seems you have embedded null byte (\x00) somewhere in requirements.txt.
score: 0

http://stackoverflow.com/a/51008937
type: Answer
has body: The hostname is added to the message by the local syslog server, i.e. is not set inside Python at all. Thus, your local system needs to be configured properly in order to send the correct hostname when forwarding syslog messages to other systems.
score: 0
answers question: http://stackoverflow.com/q/51008666

http://stackoverflow.com/a/50905367
type: Answer
has comment: http://stackoverflow.com/comment/88861436
has comment: http://stackoverflow.com/comment/88917624
answers question: http://stackoverflow.com/q/50905121
has comment: http://stackoverflow.com/comment/88917603
has comment: http://stackoverflow.com/comment/88840834
has comment: http://stackoverflow.com/comment/88817581
has body: try with this code : submit_button_incidents = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.XPATH, "//span[contains(text(),'My Group'])"))) submit_button_incidents.click() and do not use implicit wait too many times in code. Implicit wait is set for life time of web driver instance. Reference : Selenium official document for wiats Xpath tutorial cssSelector tutorial UPDATE : As OP has shared the HTML code. As per the requirement you can go ahead with this code. As there are two elements with text as My Groups's queue. For first one you can write XPATH as : //a[@class='scbdtext']/span[contains(text(),'My Group')] Code: submit_button_incidents = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//a[@class='scbdtext']/span[contains(text(),'My Group')]"))) submit_button_incidents.click() For second one you can write XPATH as : //a[@class='scbdtextfoc']/span[contains(text(),'My Group')] Code : submit_button_incidents = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.XPATH, "//a[@class='scbdtextfoc']/span[contains(text(),'My Group')]"))) submit_button_incidents.click() Hope this will help.
has comment: http://stackoverflow.com/comment/88817499
has comment: http://stackoverflow.com/comment/88841135
score: 0

http://stackoverflow.com/comment/88963964
score: 0
comment on: http://stackoverflow.com/q/50984418
type: Comment
type: QuestionComment
has text: maybe another way to read it is: the vertices mentioned in row one of the index array get the forces from row one added. So the vertices 0 and 1 get the force (3 6) added/substracted - and so on.

http://stackoverflow.com/comment/89003255
has text: OT: It's good practice to put **tl;dr:** on top of a question as well an answer, followed by details :)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51004860
score: 1

http://stackoverflow.com/q/50888683
possible better answer: http://stackoverflow.com/a/68507142
tagged with: python-2.7
answer count: 2
has answer: http://stackoverflow.com/a/50888763
favorite count: 0
has title: Meaning of re.compile(r"[\w']+") in Python
has body: I am new to python and trying to work on big data code but not able to understand what the expression re.compile(r"[\w']+") means.Anyone has any idea regarding this? This is the code that i m using. from mrjob.job import MRJob import re WORD_REGEXP = re.compile(r"[\w']+") class MRWordFrequencyCount(MRJob): def mapper(self, _, line): words = WORD_REGEXP.findall(line) for word in words: yield word.lower(), 1 def reducer(self, key, values): yield key, sum(values) if __name__ == '__main__': MRWordFrequencyCount.run()
has comment: http://stackoverflow.com/comment/88779095
tagged with: python
upvote count: 6
has answer: http://stackoverflow.com/a/68507142
has comment: http://stackoverflow.com/comment/88778632
linked to: http://stackoverflow.com/q/452104
has comment: http://stackoverflow.com/comment/88778734
downvote count: 2
has comment: http://stackoverflow.com/comment/88778664
tagged with: bigdata
type: Question
has comment: http://stackoverflow.com/comment/88778970
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88778822
accepted answer: http://stackoverflow.com/a/50888763
score: 4
tagged with: mapreduce

http://stackoverflow.com/comment/88909260
type: Comment
type: QuestionComment
has text: you can still do it for the 3 inner loops. and define `dmax` at the start (not that it takes too much time, but still...)
comment on: http://stackoverflow.com/q/50955427
score: 0

http://stackoverflow.com/comment/88944812
comment on: http://stackoverflow.com/a/50974181
type: AnswerComment
score: 0
type: Comment
has text: It worked beautifully! Thank you so much good sir :)

http://stackoverflow.com/comment/88813541
type: Comment
has text: @DebanjanB I think you're missing the point. I don't have a teardown function. I just want to keep the browsers open after the console is closed without using a ridiculous method like time.sleep(10000).
comment on: http://stackoverflow.com/q/50899417
score: 0
type: QuestionComment

http://stackoverflow.com/comment/88907411
type: Comment
comment on: http://stackoverflow.com/q/50954885
score: 1
type: QuestionComment
has text: `somethingmustbehere = None or somethingishere`

http://stackoverflow.com/q/50908946
has body: I would like to run bash commands using a python function as follows : def ExtractData(data, type_list): for i in type_list : os.system("sed -n '/\t{}\t/p' {} &gt; raw_extract_{}.tsv".format(i, data, i)) os.system("cut -d$'\t' -f2,4,8,46,63,65,66 raw_extract_{}.tsv &gt; extract_{}_reduced.tsv".format(i, i)) return "Done !" ExtractData("data.tsv", [2201, 2202]) However, even if the "sed" part worked fine, I got no result with the "cut" commands, it returned an exit status 1. I tried to type it myself in the console and I got the expected result, so the commands are correct. Can someone see what is wrong with this program ? Ps : I know os.system is deprecated, I tried subprocess.call as well but I got the exact same error.
has comment: http://stackoverflow.com/comment/88822706
downvote count: 0
has answer: http://stackoverflow.com/a/50909252
tagged with: bash
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50909252
tagged with: os.system
score: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/88821500
tagged with: python
answer count: 1
upvote count: 1
has title: Failed to execute bash commands using python

http://stackoverflow.com/q/50951308
has title: Boto3 put_object() is very slow
tagged with: elasticsearch
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/88913385
upvote count: 7
linked to: http://stackoverflow.com/q/8829468
has body: TL;DR: Trying to put .json files into S3 bucket using Boto3, process is very slow. Looking for ways to speed it up. This is my first question on SO, so I apologize if I leave out any important details. Essentially I am trying to pull data from Elasticsearch and store it in an S3 bucket using Boto3. I referred to this post to pull multiple pages of ES data using the scroll function of the ES Python client. As I am scrolling, I am processing the data and putting it in the bucket as a [timestamp].json format, using this: s3 = boto3.resource('s3') data = '{"some":"json","test":"data"}' key = "path/to/my/file/[timestamp].json" s3.Bucket('my_bucket').put_object(Key=key, Body=data) While running this on my machine, I noticed that this process is very slow. Using line profiler, I discovered that this line is consuming over 96% of the time in my entire program: s3.Bucket('my_bucket').put_object(Key=key, Body=data) What modification(s) can I make in order to speed up this process? Keep in mind, I am creating the .json files in my program (each one is ~240 bytes) and streaming them directly to S3 rather than saving them locally and uploading the files. Thanks in advance.
type: AnsweredQuestion
tagged with: amazon-s3
tagged with: boto3
type: Question
has answer: http://stackoverflow.com/a/50972740
linked to: http://stackoverflow.com/q/27478568
has comment: http://stackoverflow.com/comment/88913160
answer count: 1
downvote count: 0
score: 7
accepted answer: http://stackoverflow.com/a/50972740
tagged with: line-profiler

http://stackoverflow.com/q/50964041
has comment: http://stackoverflow.com/comment/88924729
accepted answer: http://stackoverflow.com/a/50964100
tagged with: class
has body: Look at code in my python file: class Point: def __init__(self): """ Create a new point at the origin """ self.x = 0 self.y = 0 p = Point() p.x = 4 p.y = 4 I want to create another object q which contains all the values of p Yes,we can do it like this: q = Point.objects.create(q.x = p.x,q.y = p.y) But, I don't want to refer to all the variables inside the class Point How can I do it ?
score: 2
answer count: 1
downvote count: 0
favorite count: 0
has title: How to create an object with same contents as another object in python?
upvote count: 2
tagged with: python
has answer: http://stackoverflow.com/a/50964100
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88924674
linked to: http://stackoverflow.com/q/4794244
type: Question
tagged with: object

http://stackoverflow.com/a/50977618
score: 0
has comment: http://stackoverflow.com/comment/89091420
type: Answer
has body: You can do something like this (not tested) from django import forms set_a = (("a", "A"), ("b", "B"),) set_b = (("c", "C"), ("d", "D"),) class Test(forms.Form): group_a = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=set_a) group_a = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=set_b)
answers question: http://stackoverflow.com/q/50976740

http://stackoverflow.com/a/50972870
score: 4
has body: Actually, your m is the time delta between the time of a row and the time at the end of the 'block' and the mprev is the same thing but with the time at the previous row (so it's actually shift of m). My idea is to create a column containing the time at the end of the block, by first identifying each block, then merge with the last time when using groupby on block . Then calculate the difference for creating a column 'm' and use the np.where and shift to finally fill the column 10mMark. # a column with incremental value for each block end df['block'] = df.InvInstance[df.InvInstance ==1].cumsum() #to back fill the number to get all block with same value of block df['block'] = df['block'].bfill() #to back fill the number # now merge to create a column time_last with the time at the end of the block df = df.merge(df.groupby('block', as_index=False)['Time'].last(), on = 'block', suffixes=('','_last'), how='left') # create column m with just a difference df['m'] = df['Time_last'] - df['Time'] # now you can use np.where and shift on this column to create the 10mMark column df['10mMark'] = np.where((df['m'] &lt; 10) &amp; (df['m'].shift() &gt;= 10),1,0) #just drop the useless column df = df.drop(['block', 'Time_last','m'],1) your final result before dropping, to see what as been created, looks like Time InvInstance block Time_last m 10mMark 0 5 5 1.0 20 15 0 1 8 4 1.0 20 12 0 2 9 3 1.0 20 11 0 3 19 2 1.0 20 1 1 4 20 1 1.0 20 0 0 5 3 3 2.0 13 10 0 6 8 2 2.0 13 5 1 7 13 1 2.0 13 0 0 in which the column 10mMark has the expected result It is not as efficient as with the solution of @MaxU with Numba, but with a df of 8000 rows as he used, I get speed up factor of about 350.
type: Answer
accepted answer of: http://stackoverflow.com/q/50970476
upvote count: 4
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50970476

http://stackoverflow.com/comment/88992697
type: Comment
comment on: http://stackoverflow.com/a/50999309
score: 0
type: AnswerComment
has text: What is point 2 about? The OP says the input is `123'`, which is a string. Plus, if it _weren't_ a string, he wouldn't get the `TypeError` he got, he'd get an `AttributeError`.

http://stackoverflow.com/q/50883254
has comment: http://stackoverflow.com/comment/88768660
tagged with: python
favorite count: 0
tagged with: python-3.x
tagged with: spacy
has body: I have multiple pythons installed in my machine, 2.7, 3.5, 3.6, etc and I installed the library called spacy. And it seems like this library keeps referring to the old version of python which is 3.5. at /usr/local/lib/python3.5/dist-packages. Python 3.6.5 (default, Mar 29 2018, 03:28:50) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import spacy Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/local/lib/python3.5/dist-packages/spacy/__init__.py", line 4, in &lt;module&gt; from . import util File "/usr/local/lib/python3.5/dist-packages/spacy/util.py", line 4, in &lt;module&gt; import ujson ModuleNotFoundError: No module named 'ujson' Regardless of this specific library 'spacy', I'd like to know what is the best way to make library to point to upgraded python which is 3.6, not 3.5. Which path variable should I update? Please help... I've been wasting too much time on this issue.
type: UnansweredQuestion
has title: library referring to wrong version of Python
has answer: http://stackoverflow.com/a/50883662
has comment: http://stackoverflow.com/comment/88768779
tagged with: python-3.6
type: Question
upvote count: 4
answer count: 1
downvote count: 0
score: 4
has comment: http://stackoverflow.com/comment/88768794

http://stackoverflow.com/comment/88790587
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/50892579
has text: It's easier to do: `img = qrcode.make("some data")` and then `img.save("QR.ext")`

http://stackoverflow.com/comment/88911057
type: AnswerComment
score: 0
has text: Thanks, again for the followup. I had tried printing the list in a few spots too, and I can see the files. If I run upto your debugging line, I can see the list of all the files in all the subdirectories. As soon as I try to run the code through to the largest - max() line and print (largest) line it gives me the "ValueError: max() arg is an empty sequence". If I nest the largest variable and the print (largest) lines all the way to the left, it will print the largest filename of the final directory. Everywhere else I put these two lines of code, it is giving me the ValueError.
type: Comment
comment on: http://stackoverflow.com/a/50952062

http://stackoverflow.com/a/50938559
type: Answer
score: 25
upvote count: 25
accepted answer of: http://stackoverflow.com/q/50938519
type: AcceptedAnswer
downvote count: 0
has body: .loc is an indexer. It looks for an entry in the index, but the column name is not an index. It is simply a column. The following solutions would work: df.loc[4, 'rating'] = 100 # Because 4 is in the index, but how do you know? or: df.loc[df['name']=='cheerio', 'rating'] = 100 # Find the row by column or: df.set_index('name', inplace=True) # Make 'name' the index df.loc['cheerios', 'rating'] = 100 # Use the indexer
answers question: http://stackoverflow.com/q/50938519

http://stackoverflow.com/comment/88735516
comment on: http://stackoverflow.com/q/50866385
has text: In your desired dict, which of those items are variables, and which are string? I can't test on your posted code, since you failed to provide a [Minimal, complete, verifiable example](http://stackoverflow.com/help/mcve). We cannot effectively help you until you post your MCVE code and accurately describe the problem. We should be able to paste your posted code into a text file and reproduce the problem you described.
score: 2
type: Comment
type: QuestionComment

epub
type: Tag
tags question: http://stackoverflow.com/q/50965671
tag name: epub

http://stackoverflow.com/comment/88987113
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50996286
score: 0
has text: @Barmar By running `import platform platform.platform()` I get `Darwin-17.6.0-x86_64-i386-64bit`

http://stackoverflow.com/q/50914658
answer count: 1
tagged with: mysql-python
tagged with: string
has body: I have defined a Database class as follows:- class Database(object): """ Implements all interactions with the DB. """ def __init__(self, id_a, id_b, config): self.config = config self.id_a = id_a self.id_b = id_b self.db_connection = None self.cursor = None self.__init_db(config) def __init_db(self, config): """ Initializes the MySQL Connector using the settings specified in the system configuration. """ self.db_connection = mysql.connector.connect(user=config['database_user'], password=config['database_password'], host=config['database_host'], database=config['database_name']) self.cursor = self.db_connection.cursor(dictionary=True,buffered=True) self.cursor.execute('SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;') Now, when i define the below function to return the values fetched from the Mysql database i get an error def get_func(self): sql = "SELECT c_id FROM table \ WHERE id_a = {} ".format(self.id_a) self.cursor.execute(sql) rows = self.cursor.fetchone() if rows: for row in rows: ls1 = row['id_number'] return ls1 ls1 = row['id_number'] TypeError: string indices must be integers
tagged with: byte
tagged with: python
type: UnansweredQuestion
type: Question
has title: Mysql.connector in Python TypeError
tagged with: python-2.7
score: 0
has answer: http://stackoverflow.com/a/50914692

http://stackoverflow.com/q/50959658
type: Question
has answer: http://stackoverflow.com/a/50960705
score: -1
answer count: 2
tagged with: indentation
upvote count: 0
has answer: http://stackoverflow.com/a/50960507
has body: I am having some trouble with my [Python 3.6] code. I'm not sure whats wrong, and I have tried many ways to fix it but none work. The problem is at the line where it says "Class Mainarchive:", I think its an indenting error import time print("Welcome to Code Vault Abraxis") time.sleep(1) class Username: print() username1 = input("Username: ") username2 = ("AbraxisUser") while username1 != username2: time.sleep(1) print() username1 = input("Username does not exist. Username: ") class Password: time.sleep(1) print() password1 = input("Password: ") password2 = ("cats") while password1 != password2: time.sleep(1) print() password1 = input("Wrong Password! Try again. Password: ") This is where the problem is class Mainarchive: def secrets(sec): time.sleep(2) print("1.") print("2.") print("3.") print("4.") print("5.") def projects(pro): time.sleep(2) print("1.") print("2.") print("3.") print("4.") print("5.") continued from class mainarchive block1 = input() while block1 == ("a") print("Stored Data is shown below.") return sec time.sleep(1) secrets() while block1 == ("b") print("Stored Data is shown below.") return pro time.sleep(1)
favorite count: 0
has comment: http://stackoverflow.com/comment/88916765
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has title: Why is my code not indenting correctly?
has comment: http://stackoverflow.com/comment/88916450
downvote count: 1

http://stackoverflow.com/q/50995345
type: UnansweredQuestion
has body: Given a list of column names, for example: cols = ['a', 'b', 'c'] I'd like to build a sqlalchemy ORM query which is equivalent to: q = db.query(Foo.a, Foo.b, Foo.c) Of course I could just use the query: q = db.query(Foo) ..., convert each result row to a dict, and extract the values from that using the list of column names from above as keys. I'd rather not do that because I need only a few columns from a large table and I'd like to avoid the overhead.
has comment: http://stackoverflow.com/comment/88985430
upvote count: 1
type: Question
has title: Select based on column name list in sqlalchemy
has answer: http://stackoverflow.com/a/70329438
score: 1
tagged with: sqlalchemy
answer count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/88985608
favorite count: 0
has answer: http://stackoverflow.com/a/78560793
tagged with: python
has answer: http://stackoverflow.com/a/50995502

http://stackoverflow.com/q/50931528
has comment: http://stackoverflow.com/comment/88862532
has comment: http://stackoverflow.com/comment/88862591
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/88862307
has comment: http://stackoverflow.com/comment/88862974
has comment: http://stackoverflow.com/comment/88862742
has answer: http://stackoverflow.com/a/50931771
type: Question
answer count: 2
has body: I am asking for help in transforming values into date format. I have following data structure: ID ACT1 ACT2 ACT3 ACT4 1 154438.0 154104.0 155321.0 155321.0 2 154042.0 154073.0 154104.0 154104.0 ... The number in columns ACT1-4 need to be converted. Some rows contain NaN values. I found that following function helps me to get a Gregorian date: from datetime import datetime, timedelta gregorian = datetime.strptime('1582/10/15', "%Y/%m/%d") modified_date = gregorian + timedelta(days=154438) datetime.strftime(modified_date, "%Y/%m/%d") It would be great to know how I can apply this transformation to all columns except for "ID" and whether the approach is correct (or could be improved). After the transformation is applied, I need to extract the order of column items, sorted by date in ascending order. For instance ID ORDER 1 ACT1, ACT3, ACT4, ACT2 2 ACT2, ACT1, ACT3, ACT4 Thank you!
accepted answer: http://stackoverflow.com/a/50931771
has title: Python: Convert columns into date format and extract order
tagged with: date
has comment: http://stackoverflow.com/comment/88862659
has answer: http://stackoverflow.com/a/50932561
has comment: http://stackoverflow.com/comment/88862131
tagged with: converters
possible better answer: http://stackoverflow.com/a/50932561
tagged with: datetime
tagged with: python
has comment: http://stackoverflow.com/comment/88862162

http://stackoverflow.com/a/50958206
has comment: http://stackoverflow.com/comment/88913841
answers question: http://stackoverflow.com/q/50958065
has comment: http://stackoverflow.com/comment/88913793
has comment: http://stackoverflow.com/comment/88913913
accepted answer of: http://stackoverflow.com/q/50958065
type: AcceptedAnswer
downvote count: 0
has body: With Pandas, a function applied explicitly to each row typically cannot be vectorised. Even implicit loops such as pd.Series.apply will likely be inefficient. Instead, you should use true vectorised operations, which lean heavily on NumPy in both functionality and syntax. In this case, you can use numpy.where: df1[3] = np.where(df1[2] &gt; 3, df1[2] + 5, df1[2]) Alternatively, you can use pd.DataFrame.loc in a couple of steps: df1[3] = df1[2] df1.loc[df1[2] &gt; 3, 3] = df1[2] + 5 In each case, the term df1[2] &gt; 3 creates a Boolean series, which is then used to mask another series. Result: print(df1) 0 1 2 3 0 1 2 3 3 1 5 7 8 13 2 2 5 4 9
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/q/50942548
downvote count: 1
type: Question
score: -1
tagged with: ascii
has answer: http://stackoverflow.com/a/50951899
upvote count: 0
answer count: 1
tagged with: expect
tagged with: telnetlib
has body: python telnet conn send {msg}, recv msg log, 1 : ^[]0;ABCD - ABCD - file=/tmp/1234^GConnected to 123.123.123.123 (test=test_ROOT_MO,Context=ABCD,ManagedElement=ABCD)^M 2 : ^M 3 : Last MO: 11668. Loaded 11668 . Total: 11669 MOs.^M 4 : ^M 5 : ^[[1;32mABCD^[[0m&gt; this msg(^[[1;32mABCD^[[0m>) in log , but telnet conn, and send msg ABCD&gt; msg ABCD - ABCD - file=/tmp/1234^GConnected to 123.123.123.123 (test=test_ROOT_MO,Context=ABCD,ManagedElement=ABCD) Last MO: 11668. Loaded 11668 . Total: 11669 MOs. *ABCD&gt;* last ABCD> is colorfull(green) Q). I want find " ^[[1;32mABCD^[[0m> " (ABCD is always change) I try under code, but failed --> self.teln.read_until('\^[.\^[.>.*',300)
has title: how to telnet expect ascii character cli - python 2.7
favorite count: 0
has comment: http://stackoverflow.com/comment/88883738
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/a/50920056
has body: You can use itertools.groupby, and select the minimum value in each grouping: import itertools d = [('A', 'B', 1), ('C', 'D', 1), ('B', 'D', 2), ('A', 'B', 3), ('A', 'D', 3), ('B', 'C', 4), ('A', 'C', 5), ('B', 'C', 8)] new_d = [min(list(b), key=lambda x:x[-1]) for _, b in itertools.groupby(sorted(d, key=lambda x:x[:-1]), key=lambda x:x[:-1])] Output: [('A', 'B', 1), ('A', 'C', 5), ('A', 'D', 3), ('B', 'C', 4), ('B', 'D', 2), ('C', 'D', 1)]
answers question: http://stackoverflow.com/q/50920045
type: Answer
upvote count: 1
score: 1
downvote count: 0

http://stackoverflow.com/q/50918905
type: Question
score: 1
has title: Using pywinauto for uninstalling a program (Windows)
tagged with: ui-automation
tagged with: automation
answer count: 1
downvote count: 0
tagged with: pywinauto
has body: Code snippet and resulting uninstaller window on execution I am attempting to use Pywinauto to automate the uninstallation of 'Microsoft NET Framework' using a template provided by Vasily Ryabov. I am able to get to the point where I hit 'Uninstall' in the control panel and the corresponding Uninstaller shows up (please see image) I can't figure out how to transfer control to the resulting window, select the 'Remove' radio button and click the 'Next' button. Any help would be much appreciated!
tagged with: python
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
upvote count: 1
has answer: http://stackoverflow.com/a/50922051

http://stackoverflow.com/q/50859188
answer count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/10901085
tagged with: colors
has body: I'm new to coding and I'm really confused. From the code below, I'm trying to print out every single colour in the RGB spectrum from (0,0,0) to (255,255,255) so technically there should be 256^3 images printed with all the colours. I've kind of done it below which only does it for the red or blue or green spectrum and not the combinations. What I'm trying to do with all the colours that are printed out is to stitch them all together pixel by pixel in this format. I don't want to print out all the images but get the combined version at the end. Any help would be greatly appreciated! Thank you so much for the help! I would like to get all the combinations of the 3 variables from 0 to 255. For example, the output from print axis would be: (0,0,0) (1,0,0) (2,0,0) ... (255,0,0) (0,1,0) (0,2,0) ... (0,255,0) (0,0,1) (0,0,2) ... (0,0,255) (1,0,1) ... so basically all the different combinations of the 3 numbers until 255. I tried using the one below but what I'm trying to do is a bit different where each pixel I want is different and stitched together in a pixel by pixel format by looping through the values. Range values to pseudocolor from PIL import Image import sys im = Image.new("RGB", (1, 1)) pix = im.load() red=0 green=0 blue=0 j=0 while red&lt;255 and green&lt;255 and blue&lt;255: j+=1 red +=1 #green +=1 #blue+=1 for x in range(1): for y in range(1): axis = (red,green,blue) pix[x,y] = axis print axis im.save('Test {}.png'.format(j), "PNG") #stitching images together images = map(Image.open, ['Test 1.png', 'Test 255.png', 'Test 100.png']) widths, heights = zip(*(i.size for i in images)) total_width = sum(widths) max_height = max(heights) new_im = Image.new('RGB', (total_width, max_height)) x_offset = 0 for im in images: new_im.paste(im, (x_offset,0)) x_offset += im.size[0] new_im.save('test.jpg')
tagged with: python
has title: Looping through all the RGB values and stitching images together
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50859247
downvote count: 0
accepted answer: http://stackoverflow.com/a/50859247
type: Question
tagged with: python-imaging-library
tagged with: rgb
upvote count: 2

http://stackoverflow.com/q/50976373
has body: I have an array with the next distribution array -&gt; shape(878,) one element inside array shape(313,313,3) What I have to do to get the next result? shape(878,313,313,3) thanks
has answer: http://stackoverflow.com/a/50976559
type: Question
has comment: http://stackoverflow.com/comment/88948778
linked to: http://stackoverflow.com/q/50971123
tagged with: numpy
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/50976524
has comment: http://stackoverflow.com/comment/88948742
has title: Reshape an array using Numpy
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88948709
has comment: http://stackoverflow.com/comment/88948785
tagged with: python

http://stackoverflow.com/a/50881025
accepted answer of: http://stackoverflow.com/q/50878618
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50878618
score: 0
type: Answer
has body: Ciao, this is how to get a link inside DOCX file with "python-docx" library from docx import Document from docx.opc.constants import RELATIONSHIP_TYPE as RT document = Document('nameFile.docx') rels = document.part.rels def leggiLink(rels): for rel in rels: if rels[rel].reltype == RT.HYPERLINK: yield rels[rel]._target print('print link inside file: nameFile.docx') for i in leggiLink(rels): print(i)

http://stackoverflow.com/a/50959780
has comment: http://stackoverflow.com/comment/88916637
accepted answer of: http://stackoverflow.com/q/50959718
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/88916628
type: AcceptedAnswer
has body: Using the itertools module you can cycle and slice a string via an infinite generator: from itertools import cycle, islice from string import ascii_lowercase def gen(x, n): c = cycle(x) while True: yield list(islice(c, n)) G = gen(ascii_lowercase, 5) print(next(G)) # ['a', 'b', 'c', 'd', 'e'] print(next(G)) # ['f', 'g', 'h', 'i', 'j'] ... print(next(G)) # ['u', 'v', 'w', 'x', 'y'] print(next(G)) # ['z', 'a', 'b', 'c', 'd']
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/88916666
has comment: http://stackoverflow.com/comment/88916653
has comment: http://stackoverflow.com/comment/88916650
answers question: http://stackoverflow.com/q/50959718

http://stackoverflow.com/q/50877238
answer count: 1
has answer: http://stackoverflow.com/a/50883904
favorite count: 0
type: UnansweredQuestion
tagged with: python
downvote count: 0
type: Question
score: 1
has title: How to accept an indefinite number of options (and how to query their names/values) using click CLI framework?
has body: I want to pass an unlimited number of options to a click CLI. I don't know Option names either. I'm getting around this issue by using an option named conf. It accepts a string that is assumed to represent a JSON object. What I've done: @click.command() @click.option('--conf', type=str) def dummy(conf): click.echo('dummy param {}'.format(conf)) How I use it: &gt;python main.py dummy --conf='{"foo": "bar", "fizz": "buzz"}' What I want to do: @click.command() #some magic stuff def dummy(**kwargs): click.echo('dummy param {}'.format(**kwargs)) How I want to use it: &gt;python main.py dummy --foo=bar --fizz=buzz
tagged with: python-click
upvote count: 1

http://stackoverflow.com/comment/88822193
score: 0
type: Comment
type: QuestionComment
has text: Can you please share your expected output?
comment on: http://stackoverflow.com/q/50905487

http://stackoverflow.com/q/50952294
downvote count: 0
has comment: http://stackoverflow.com/comment/88902264
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88902346
has body: Say I have a DataFrame that looks something like this: A B key1 key2 0 A0 B0 K0 K0 1 A1 B1 K0 K1 2 A2 B2 K1 K0 3 A3 B3 K2 K1 4 A0 B0 K0 K0 I know that I can get the counts of unique values in the 'key1' column with this: df['key1'].value_counts() which returns something like this: K0 3 K1 1 K2 1 But what if I want to get counts of combinations between the two key columns. To return something like this: K0 K0 2 K0 K1 1 K0 K1 1 K0 K1 1
answer count: 0
type: Question
linked to: http://stackoverflow.com/q/47487753
score: 4
duplicate of: http://stackoverflow.com/q/47487753
upvote count: 4
tagged with: pandas
has title: Pandas value_counts using multiple columns

http://stackoverflow.com/comment/88861810
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50931416
has text: Did you try to search on [this website](http://google.com)?

http://stackoverflow.com/q/50888811
accepted answer: http://stackoverflow.com/a/50889604
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/88780287
tagged with: keras
favorite count: 0
tagged with: python
has title: keras custom ImageDataGenerator
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50889604
has comment: http://stackoverflow.com/comment/88784735
has body: Is there anyway we can add some functionality to the ImageDataGenerator, so that the ImageDataGenerator can take a list of filenames, and random sample images for each minibatch? I know that I can custom a class which inherit ImageDataGenerator class, but I still don't know the details how to do that. Here is what I have done: for epoch in range(epochs): print("epoch is: %d, total epochs: %f" % ((epoch+1), int(epochs))) print("prepare training batch...") train_batch = makebatch(filelist=self.train_files, img_num=img_num, slice_times=slice_times) print("prepare validation batch..") val_batch = makebatch(filelist=self.val_files, img_num=int(math.ceil(img_num*0.2)), slice_times=slice_times) x_train = train_batch y_train = x_train x_val = val_batch y_val = x_val print("generate training data...") train_datagen.fit(x_train) train_generator = train_datagen.flow( x=x_train, y=y_train, batch_size=16) val_datagen.fit(x_val) val_generator = val_datagen.flow( x=x_val, y=y_val, batch_size=16) print("start training..") history = model.fit_generator( generator=train_generator, steps_per_epoch=None, epochs=1, verbose=1, validation_data=val_generator, validation_steps=None, callbacks=self.callbacks) what I really want to obtain is that I can remove the for loop and the generator random sample images for each batch. Someone can help with that?
type: Question
score: 4
upvote count: 4

http://stackoverflow.com/comment/88982458
comment on: http://stackoverflow.com/a/50975690
has text: @Liviu Have you tried `async with merge(...) as stream:` and inside it `async for batch in stream: ...`?
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/52249260
answers question: http://stackoverflow.com/q/50923323
type: Answer
has body: I'm not sure this is the answer, and also I'm not sure you are still looking for the answer, but... So you have 100,000 python objects. If these objects are regular data (data sets), not an instance of some class, pass data as json string. Something like this: #!/usr/bin/env python import json import numpy as np from mpi4py import MPI comm = MPI.COMM_WORLD if comm.rank == 0: tasks = [ json.dumps( { 'a':1,'x':2,'b':3 } ), json.dumps( { 'a':3,'x':1,'b':2 } ), json.dumps( { 'a':2,'x':3,'b':1 } ) ] else: tasks = None # Scatter paramters arrays unit = comm.scatter(tasks, root=0) p = json.loads(unit) print "-"*18 print("-- I'm rank %d in %d size task" % (comm.rank,comm.size) ) print("-- My paramters are: {}".format(p)) print "-"*18 comm.Barrier() calc = p['a']*p['x']**2+p['b'] # gather results result = comm.gather(calc, root=0) # do something with result if comm.rank == 0: print "the result is ", result else: result = None note, that if you have only 8 nodes/cores, you have to create 8 records in the tasks list and sequentially scatter and gather all 100,000 data sets. If all your data set is in ALLDATA list, the code could look like this: def calc(a=0,x=0,b=0): return a*x**2+b if comm.rank == 0: collector = [] for xset in zip(*(iter(ALLDATA),) * comm.size): task = [ json.dumps(s) for s in xset ] comm.Barrier() unit = comm.scatter(task if comm.rank == 0 else None, root=0) p = json.loads(unit) res = json.dumps( calc(**p) ) totres = comm.gather(res, root=0) if comm.rank == 0: collector += [ json.loads(x) for x in totres ] if comm.rank == 0: print "the result is ", collector
score: 0

http://stackoverflow.com/comment/88879886
score: 0
has text: @hpaulj, in my real use-case I actually have strings in other array positions (as well as int and float as in my simplified example). I even have my own classes in other positions. What is common to all these classes is that they have a well defined \__add\__ method, hence it could be expected to allow this mixture of types in different entries in the array. I think I'll go back to pandas though, as suggested by anishtain4 and probably by pythonic883 too. Thank you all.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50931421

http://stackoverflow.com/a/50968614
has body: In broad terms, one way to determine the mean thickness of a line is as follows. Separate First, separate the line from the background - probably using the Hue (in HSV) space in your case. Skeletonize Now use some sort of skeletonising or thinning or pruning to get a single pixel wide representation of the line. Ratio Now you have a 1-pixel wide line and also the (fatter) line you want to measure, so the average thickness of your lines is somewhere close to the ratio of the means of the two images.
answers question: http://stackoverflow.com/q/50967808
downvote count: 0
has comment: http://stackoverflow.com/comment/88933900
upvote count: 2
type: Answer
score: 2

http://stackoverflow.com/comment/88759823
score: 0
type: QuestionComment
type: Comment
has text: Then I am not sure whether SO is the best place to ask; maybe better on [stats.stackexchange](https://stats.stackexchange.com/) or [signal processing](https://dsp.stackexchange.com/)?!
comment on: http://stackoverflow.com/q/50860512

http://stackoverflow.com/comment/88946859
has text: That sounds different from what I was going for, but sounds like it would give me the results I want. So you're suggesting I make the output array with a dtype=int, and use the array slices on phit and psit with conditionals to get out a straight array, that I can pass right into the appropriate slices of the output data array? Hope that sounds about right.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50974924

http://stackoverflow.com/comment/88789285
score: 0
has text: Thanks. Any reference where I can find derivation of this transformation.
comment on: http://stackoverflow.com/a/50894076
type: Comment
type: AnswerComment

typeerror
tags question: http://stackoverflow.com/q/50909786
tags question: http://stackoverflow.com/q/50922760
tags question: http://stackoverflow.com/q/50973033
tags question: http://stackoverflow.com/q/50913575
tag name: typeerror
tags question: http://stackoverflow.com/q/50892010
tags question: http://stackoverflow.com/q/51008555
tags question: http://stackoverflow.com/q/50897114
tags question: http://stackoverflow.com/q/50944376
tags question: http://stackoverflow.com/q/50973041
tags question: http://stackoverflow.com/q/50991531
tags question: http://stackoverflow.com/q/50923686
tags question: http://stackoverflow.com/q/50948727
tags question: http://stackoverflow.com/q/50919690
tags question: http://stackoverflow.com/q/50942606
tags question: http://stackoverflow.com/q/51000911
type: Tag
tags question: http://stackoverflow.com/q/50877893

http://stackoverflow.com/q/50957229
has comment: http://stackoverflow.com/comment/88912311
has answer: http://stackoverflow.com/a/50957378
has comment: http://stackoverflow.com/comment/88912001
possible better answer: http://stackoverflow.com/a/50957378
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50969718
tagged with: powershell
tagged with: virtualenv
type: Question
tagged with: python
has title: Creating a new virtualenv project and creating a virtualenv for existing project causes error
has body: I've tried to search for a solution or a thread handling this problem but I have a hard time expressing it in the first place since I'm fairly new to django, virtualenv, pip etc. I'm using windows 10 and I do everything below in powershell. When I started my first project, named fadderjobb, I didn't use virtualenv. I installed a couple of packages using pip install. Now when I started my second project, wingqvist, I installed virtualenv, made a virtual environment in a folder envs/wingqvist, installed Django and created a new Django project in another new folder webdev/wingqvist. Looking something like this. webdev |-- fadderjobb | `-- projectfiles for fadderjobb |-- wingqvist | `-- projectfiles for wingqvist `-- envs `-- wingqvist `-- virualenv files for wingqvist When I in my virtualenv (wingqvist) tried to run python manage.py migrate in webdev/wingqvist/ i got the following error: (wingqvist) PS C:\Users\Viktor Wingqvist\documents\webdev\wingqvist&gt; python manage.py migrate Traceback (most recent call last): File "manage.py", line 22, in &lt;module&gt; execute_from_command_line(sys.argv) File "C:\Users\Viktor Wingqvist\documents\webdev\envs\wingqvist\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Users\Viktor Wingqvist\documents\webdev\envs\wingqvist\lib\site-packages\django\core\management\__init__.py", line 347, in execute django.setup() File "C:\Users\Viktor Wingqvist\documents\webdev\envs\wingqvist\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Viktor Wingqvist\documents\webdev\envs\wingqvist\lib\site-packages\django\apps\registry.py", line 89, in populate app_config = AppConfig.create(entry) File "C:\Users\Viktor Wingqvist\documents\webdev\envs\wingqvist\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Users\Viktor Wingqvist\documents\webdev\envs\wingqvist\lib\importlib…
accepted answer: http://stackoverflow.com/a/50969718
score: 0
answer count: 2
tagged with: pip
tagged with: django

http://stackoverflow.com/comment/88960479
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50982651
has text: provide sample imput and expected output
score: 0

http://stackoverflow.com/comment/88943025
comment on: http://stackoverflow.com/q/50973342
type: QuestionComment
has text: You are comparing an entire series to `True`. You want to mask your series with `notnull()`
score: 2
type: Comment

http://stackoverflow.com/comment/88947497
type: Comment
score: 1
has text: 2.7G might not be enough. That error alone indicates that one chunk of memory being allocated is ~670M, and is a `realloc` call, which means it might be trying to size up an existing allocated block of similar size... so possibly 1-1.5G for just that one thing it's allocating. You data seems very reasonably sized, but that decision tree might just need more memory. Try killing some memory-hogging processes and/or rebooting, then trying again. Chrome, for example, can take a huge amount of memory if you have a lot of tabs open. 8G should be enough for this problem, though.
type: QuestionComment
comment on: http://stackoverflow.com/q/50975447

http://stackoverflow.com/comment/88850191
type: Comment
has text: but I want continuous output like this: 1234...
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50925430

http://stackoverflow.com/q/50878471
type: Question
has comment: http://stackoverflow.com/comment/88759652
has comment: http://stackoverflow.com/comment/88759570
tagged with: pandas
has title: Select dataframe rows defining a date range that contains a needle date
has comment: http://stackoverflow.com/comment/88759221
has comment: http://stackoverflow.com/comment/88759862
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88759730
has comment: http://stackoverflow.com/comment/88759235
answer count: 0
score: 0
has comment: http://stackoverflow.com/comment/91619247
has body: There are lots of answers which make it easy to select some date range and get the ones that fall into that range. I don't want that. I have data like this: id other_flags d_dt_start d_dt_end 0 28 ... 1993-02-12 1993-12-31 1 28 ... 1993-02-12 1993-12-31 2 46 ... 1986-01-15 1993-09-30 3 46 ... 1986-01-15 1993-09-30 4 46 ... 1986-01-15 1993-09-30 I want to select the ones that match when I have a date, say, 1986-06-15, thus giving me the subset of indices 2, 3, and 4. Currently, I'm doing this by something like this: subs = subs[(time &gt;= subs['d_dt_start1']) # later &amp; (time &lt;= subs['d_dt_end1'])] # before There has got to be a more elegant way to do this similar to the between command, just the opposite of that. Basically, instead of saying 'you have a date, I have a date range', 'you have a date range, I have a date'.

http://stackoverflow.com/q/50916834
score: 0
answer count: 1
tagged with: django-rest-framework
has body: I'm trying to raise a message when a condition is met (if ingrediente.saldo &lt;= ingrediente.saldo_minimo) to tell the user that a supply is almost out of stock. Can you help me figure out how to do that? views.py class CreateOrderView(generics.ListCreateAPIView): """Esta clase maneja los requests GET y POST.""" queryset = Order.objects.all() serializer_class = OrderSerializer def perform_create(self, serializer): """Guarda la info al crear una nueva ORDEN. RESTA del stock. Controla el saldo mínimo.Devuelve el precio sugerido.""" serializer.save() post = self.request.POST lista_productos = json.loads(post.get('productos')) precio_hora_trabajada = SystemParameters.objects.get(id=1).precio_hora_trabajada serializer.instance.costo_total = costo_total_orden(post) serializer.instance.save() horas_trabajadas_total = 0 for prod in lista_productos: producto = Product.objects.get(pk=prod['id']) Products.objects.create(order=serializer.instance, product=producto, cantidad=prod['cantidad']) for ingred in producto.supplies_set.all(): cantidad_por_ingrediente = producto.supplies_set.get(supply=ingred.supply_id).cantidad ingrediente = ingred.supply ingrediente.saldo -= cantidad_por_ingrediente*Decimal(prod['cantidad']) ingrediente.save() if ingrediente.saldo &lt;= ingrediente.saldo_minimo: alerta= 'Alerta: el supply llegó al stock mínimo' content = {'alerta': alerta} return Response(content) continue horas_trabajadas_total += producto.horas_trabajadas serializer.instance.precio_sugerido = (serializer.instance.costo_total*3)+(precio_hora_trabajada*horas_trabajadas_total) serializer.instance.save() Thank you!!
has title: Python. Django Rest Framework. How to get a custom Json response?
tagged with: python
accepted answer: http://stackoverflow.com/a/50944860
has answer: http://stackoverflow.com/a/50944860
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/json
type: Question

http://stackoverflow.com/q/50863275
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/88733224
score: 1
has body: I've tried several methods for installing Tensorflow (CPU-only) onto my Dragonboard 410c, and even though all other packages install just fine, Tensorflow installation always gives me the error tensorflow-1.3.0-... no matter whether I use pip or pip3. Things I've checked for: uname a outputs arm64 (64-bit) pip -V &amp;&amp; pip3 -V (both 10.0.1) sudo apt-get update Installing within a virtualenv Installing using native pip Installing using the links to the Tensorflow binaries Even after ensuring all three of these were good, I can't install Tensorflow.
tagged with: dragonboard
type: Question
upvote count: 1
tagged with: python
favorite count: 0
has title: (Debian) Dragonboard 410c: Tensorflow is not a supported wheel on this platform
answer count: 0
downvote count: 0
tagged with: qualcomm
type: UnansweredQuestion
tagged with: pip

http://stackoverflow.com/a/50864302
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50864103
has comment: http://stackoverflow.com/comment/88731385
downvote count: 0
has body: You need to use .apply() with axis=1 so as to access columns. As you go, you need to construct your dictionary. list(df.apply(lambda x: {'name': x['CATEGORY'], 'y': x['Users']}, axis=1)) Output: [{'name': 'Chrome', 'y': 550}, {'name': 'IE', 'y': 203}, {'name': 'FireFox', 'y': 25}, {'name': 'Safari', 'y': 305}, {'name': 'Opera', 'y': 15}, {'name': 'QQ', 'y': 132}] Thank fixes your approach. The ideal way however, would be to use to_dict() as below: df.rename(columns={'CATEGORY': 'name', 'Users': 'y'}).to_dict(orient='records') Output: [{'name': 'Chrome', 'y': 550}, {'name': 'IE', 'y': 203}, {'name': 'FireFox', 'y': 25}, {'name': 'Safari', 'y': 305}, {'name': 'Opera', 'y': 15}, {'name': 'QQ', 'y': 132}] This way your original df would be unaffected as well.

http://stackoverflow.com/comment/88996833
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51001397
has text: @OlivierMelançon Added assumption and provided a second solution as well to cater your comment.
type: Comment

http://stackoverflow.com/a/50986578
has comment: http://stackoverflow.com/comment/88968507
score: -1
has comment: http://stackoverflow.com/comment/88967893
downvote count: 1
has comment: http://stackoverflow.com/comment/88969789
answers question: http://stackoverflow.com/q/50986441
type: Answer
has comment: http://stackoverflow.com/comment/88969913
upvote count: 0
has comment: http://stackoverflow.com/comment/88968250
has comment: http://stackoverflow.com/comment/88970069
has body: When you do your loop for i in L : i+=1 You never ask Python to change your list L. In fact, you just update i. At first, i = L[0] = 1, You update i to 2. But L doesn't change because you didn't ask L[0] to be updated. As L includes numbers, when you do for i in L, then i is not the element of L itself, but a clone of it. A proper way to do it would be : for i in range(len(L)) : L[i] += 1 #you update L[i] itself this time or if you like a more compact way : L = [i+1 for i in L] I hope I was clear enough. Have a nice day ;-)

http://stackoverflow.com/comment/88973751
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/50951217
type: Comment
has text: @shuttle87 Yes.. I simply wrote `a = b = c = None` for the subsequent example.

http://stackoverflow.com/comment/88908394
score: 0
type: AnswerComment
type: Comment
has text: Ahh right. I see. But then why doesn't `[c for c in x for x in texts]` or `[c for c in (x for x in texts)]` work? It should give me a list of all the characters?
comment on: http://stackoverflow.com/a/50955369

http://stackoverflow.com/q/50914362
upvote count: 2
tagged with: python
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50914426
type: Question
accepted answer: http://stackoverflow.com/a/50914426
downvote count: 0
answer count: 1
has body: I'm trying to concatenate strings in a column based on the values in another column. While this inherently isn't difficult, here the order of the flags matter so I can't think of a pythonic method to accomplish this task (currently trying multiple counters/loops). Example table: text flag a 0 b 0 c 1 d 0 e 1 f 1 g 1 Example output: text flag ab 0 c 1 d 0 efg 1 I want to ''.join every string for consecutive flags until the next flag is hit. The only flags are 1 and 0. Any ideas? Here's a quick way to generate the example data so you don't have to do it yourself: import pandas as pd df = pd.DataFrame({'text':['a','b','c','d','e','f','g'], 'flag':[0,0,1,0,1,1,1]})
tagged with: pandas
favorite count: 0
has title: Pandas: concatenate strings in column based on a flag in another column until flag changes

http://stackoverflow.com/q/50916898
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/88835894
has title: Attaching NFA Fragments together (Thompson)
has comment: http://stackoverflow.com/comment/88835456
upvote count: 1
has comment: http://stackoverflow.com/comment/88835944
has comment: http://stackoverflow.com/comment/88835591
tagged with: algorithm
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88835206
has body: I've read a lot about NFA's and DFA's, and I wanted to implement one in Python. I chose Python because it is very useful when simulating algorithms. So, using Thompson's construction algorithm, I implemented States with their transitions and also built NFA Fragments that represent a different part of a regular expression. One for a symbol transition and one for concatenation. Except I got stuck at the concatenation part, because the states that I tried to "glue" together don't match, and they point to different objects. This is what it should be, but for me the q0 start node of N(s) doesn't transition into it's end node, which is the N(t) start node. Here is my code, all in one file for simplicity: class State(object): def __init__(self, label, isfinish, trans): self.label = label self.trans = trans self.isfinish = isfinish self.id = label + str(id(self)) NFA_SIMULATE_RUN = False class NFA(object): def __init__(self, tup): self.Q = tup[0] self.S = tup[1] self.start = tup[2] self.end = tup[3] self.table = {} for state in self.Q: trans_list = {} if not state.isfinish: for sym in state.trans.keys(): trans_list[sym] = state.trans[sym] self.table[state] = trans_list def move(self, state, sym): assert(state in self.Q),(state + " is not in state set") assert(sym in self.S),(sym + " is not in alphabet") if sym not in self.table.keys(): if '' in self.table.keys(): sym = '' possible_states = self.table[state][sym] if NFA_SIMULATE_RUN: i = random.randint(0, len(possible_states) - 1) chosen_state = possible_states[i] return chosen_state return possible_states def accepts(self, string): curstate = self.start for ch in string: curstate = self.move(curstate, ch) if curstate.isfinish: print(string + " accepted!") else: print(string + " rejected!") class SymbolNFA(NFA): def __init__(self, sym): self.end = State('qf', True, {}) self.start = State('q0', False, { sym: self.end }) self.Q = [self.start, self.end] self.S = [sym] super(SymbolNFA, self).__init__((self.Q, self.S, self.start,…
downvote count: 0
score: 1
favorite count: 0
tagged with: nfa
type: Question

bokeh
tags question: http://stackoverflow.com/q/50874445
tags question: http://stackoverflow.com/q/50934925
tags question: http://stackoverflow.com/q/50863650
type: Tag
tags question: http://stackoverflow.com/q/50886999
tags question: http://stackoverflow.com/q/50978080
tags question: http://stackoverflow.com/q/50993365
tags question: http://stackoverflow.com/q/50955353
tags question: http://stackoverflow.com/q/50953645
tags question: http://stackoverflow.com/q/50977195
tags question: http://stackoverflow.com/q/50937462
tags question: http://stackoverflow.com/q/50931998
tags question: http://stackoverflow.com/q/50868586
tags question: http://stackoverflow.com/q/50971553
tags question: http://stackoverflow.com/q/50899901
tags question: http://stackoverflow.com/q/51001405
tags question: http://stackoverflow.com/q/50878062
tags question: http://stackoverflow.com/q/50954606
tag name: bokeh

http://stackoverflow.com/comment/88758400
comment on: http://stackoverflow.com/q/50877291
type: Comment
type: QuestionComment
has text: @TarunLalwani {'Expect-Ct': ['max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"'], 'X-Powered-By': ['React/alpha'], 'Set-Cookie': ['user-id=w2t07lkjqpfan31v1xqv; Max-Age=7776000; HttpOnly; Domain=.www.backpack.tf; Path=/'], 'Date': ['Wed, 13 Jun 2018 15:16:31 GMT'], 'Cf-Ray': ['42a584caef8ca8b7-CDG']}, '\n \n \n \n \n \n<!-- have a nice day <3 -->\n cakedog&#039;s TF2 Backpack - backpack.tf... etc... It's a regular HTML page, but shouldn't parse_accounts() still work? Parse() does, and it has the same type of input
score: 0

http://stackoverflow.com/a/50911766
score: 1
answers question: http://stackoverflow.com/q/50911198
downvote count: 0
type: Answer
has body: Use set_index and cumcount: df.set_index([df['StartTime'].dt.floor('D'), df.groupby(df['StartTime'].dt.floor('D')).cumcount()])['Id'].unstack(0) OUtput: StartTime 2018-04-24 2018-04-25 2018-04-26 2018-04-27 0 aaa ccc ddd ggg 1 bbb aaa fff NaN
upvote count: 1

nonlinear-optimization
tags question: http://stackoverflow.com/q/50899741
tag name: nonlinear-optimization
tags question: http://stackoverflow.com/q/51005841
type: Tag

http://stackoverflow.com/q/50977683
tagged with: dataframe
has comment: http://stackoverflow.com/comment/88951955
has comment: http://stackoverflow.com/comment/88952205
score: 0
has comment: http://stackoverflow.com/comment/88951508
has comment: http://stackoverflow.com/comment/88951461
linked to: http://stackoverflow.com/q/1446370
has comment: http://stackoverflow.com/comment/88951541
has comment: http://stackoverflow.com/comment/88973456
has comment: http://stackoverflow.com/comment/88952108
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
has title: Pandas read_csv is reading everything into one column for only one file python
tagged with: python
tagged with: delimiter
has body: I have multiple .dat files that I am trying to read into pandas with read_csv(). They are comma-delimited. All of the files are being read in properly, except for one, which is not separating on the commas and placing all the data into one column. I am so lost as to why this is happening, there is no difference between this file and the other ones, and I have tried so many different parameters. Here is what I have: col_names=['faketime',"rn","counter","DepthCm","BattVolts","latdeg","latmin", "Longdeg","Longmin","fq","ns","HDOP","altB","DepthVolts","LatDDDDD", "LongDDDDD","month","day","hour","minute","second","year"] mo = pd.read_csv(i, names=col_names, skiprows=4, sep=',') and here is a portion of the file 2015-05-08 07:17:56.7,7591,100001,0.11,12.46,81,37.6641,12,1.9694,1,11,0.7,-1.3,0.01,0.627735,0.03282334,5,8,7.000,17,56,20000 2015-05-08 07:17:59.54,7592,100002,0.06,12.45,81,37.6636,12,1.9702,1,11,0.7,-0.8,0.00,0.6277267,0.03283666,5,8,7.000,17,58,860000 2015-05-08 07:18:06.45,7593,100003,30.61,12.44,81,37.6633,12,1.9684,1,11,0.7,-0.6,2.008,0.6277217,0.03280667,5,8,7.000,18,5,770000
has comment: http://stackoverflow.com/comment/88951745
answer count: 0
has comment: http://stackoverflow.com/comment/88951538
type: UnansweredQuestion
type: Question

http://stackoverflow.com/a/50895475
upvote count: 7
answers question: http://stackoverflow.com/q/50893267
has body: As explained by Ned Batchelder's answer, and by the docs for the id function: Two objects with non-overlapping lifetimes may have the same id() value. And the two objects have non-overlapping lifetimes. The fact that they're part of the same tuple expression doesn't change that, because it's not t+t and t*2 that are part of a tuple, it's id(t+t) and id(t*2). So, those two integer values returned by id have an overlapping lifetime, but the arguments passed to id do not. One way to understand this is to look at how CPython compiles the code: &gt;&gt;&gt; dis.dis('id(t+t), id(t*2)') 1 0 LOAD_NAME 0 (id) 2 LOAD_NAME 1 (t) 4 LOAD_NAME 1 (t) 6 BINARY_ADD 8 CALL_FUNCTION 1 10 LOAD_NAME 0 (id) 12 LOAD_NAME 1 (t) 14 LOAD_CONST 0 (2) 16 BINARY_MULTIPLY 18 CALL_FUNCTION 1 20 BUILD_TUPLE 2 22 RETURN_VALUE So, here's what happens. (I'm going to pick a value for t, say 1000, just to make this a bit easier to follow.) id, 1000, and 1000 get pushed on the stack. BINARY_ADD creates a 2000 value at location 42838592. id gets called on that value and returns a 42838592 value at location, say, 42838616. Since the 42838592 value is no longer on the stack and wasn't stored anywhere, id's parameter was the only reference to it, so when it gets decrefed at the end of the function, it's immediately deleted. id, 1000, and 2 get pushed on the stack. BINARY_MULTIPLY creates a new 2000 object. Since location 42838592 was just returned to the object pool, the new value reuses that location. id returns another 42838592, this time at location, say, 42838640. So, the two int values 4283592 and 4283592 have overlapping lifetimes (and the first one overlaps with the second 2000), the two 2000s do not overlap. And finally, notice that if t is a small number, &gt;&gt;&gt; t = 2 &gt;&gt;&gt; (t+t) is (t*2) True … because all 4 values (except in unusual cases) are references to the same object. And meanwhile, if t is a constant rather than a variable, 1000+1000 is 1000*2 may or may not be true, depending…
downvote count: 0
score: 7
type: Answer

http://stackoverflow.com/comment/88876987
type: AnswerComment
score: 0
type: Comment
has text: How to validate the `password`, bro?
comment on: http://stackoverflow.com/a/50928771

avsc
type: Tag
tags question: http://stackoverflow.com/q/50975360
tag name: avsc

http://stackoverflow.com/comment/88733998
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50865738
has text: What does `echo /usr/bin/python` display?

http://stackoverflow.com/q/50878588
tagged with: scikit-learn
answer count: 0
type: UnansweredQuestion
tagged with: python
has title: Getting a type error while trying to build a logistic model
has body: I am trying to create a Logistic Regression model with scikit-learn based off a clinical database I have, but I am getting a TypeError, and nothing I do seems to fix it. I am getting this error: TypeError: Cannot cast array data from dtype('float64') to dtype('&lt;U32') according to the rule 'safe' Thanks for the help in advance! from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.metrics import confusion_matrix import numpy as np import csv target = [] data = [] with open('TABAK_SCORE_BINS.csv', 'r')as f: This file contains a bunch of medical records. Basically rather they 'A' survived, or 'E' died, with a lot of different clinical variables. reader = csv.reader(f, delimiter=',') next(reader, None) for line in reader: if(line[1] == 'A'): line[1] contains the 'A' or 'E' which tells us if the patient survived or not target.append(0) if(line[1] == 'E'): target.append(1) Lines[55:] are all of the variables which I care about, and they are all 1s or 0s data.append(line[55:]) data_arr = np.asarray(data) Splitting the model x_train, x_test, y_train, y_test = train_test_split(data, target, train_size=0.7, random_state=0) log_reg = LogisticRegression() log_reg.fit(x_train, y_train) print(data_arr.shape) print(data_arr.dtype) The shape is outputted as (295359, 105) and the dtype is (less than sign)U1 All the code compiles up until this point when I try to predict with the trained model. for i in range(0, 10): print(log_reg.predict(data_arr[i].reshape(1, -1)))
score: 0
has comment: http://stackoverflow.com/comment/88763311
type: Question
has comment: http://stackoverflow.com/comment/88761204

http://stackoverflow.com/comment/88927016
type: Comment
comment on: http://stackoverflow.com/a/50962674
score: 0
type: AnswerComment
has text: this 3 line student.school_year = school_year , student.school_level = self.school_level and student.school_name = school_name are updating your last record if you don't want to update it please remove it from code.

http://stackoverflow.com/comment/88981994
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50992038
has text: I posted an identical solution as I didn't saw your edit. Maybe it was better to post your second solution as a different answer. The two approaches are completely different.
type: AnswerComment

http://stackoverflow.com/comment/88867668
comment on: http://stackoverflow.com/a/50933783
type: AnswerComment
has text: I tried this and it brings me the following errors: line 106, in <module> main() line 8, in main milestoKm(miles_km) line 34, in milestoKm if notFailedYet: UnboundLocalError: local variable 'notFailedYet' referenced before assignment
score: 0
type: Comment

http://stackoverflow.com/q/50955112
score: 0
has answer: http://stackoverflow.com/a/50959091
accepted answer: http://stackoverflow.com/a/50959091
answer count: 1
has title: matplotlib grouped bars in a bar graph
has body: I'm playing with matplotlib and pandas to create a bar graph. I have a dataframe of world cup teams and here is what df.head() shows I want to create a bar graph, where each bar is a unique team, and each team in a group are graphed close together, with unique groups between a noticeable distance apart. Here is what I currently have: caps_per_team_per_group = df.groupby(['group', 'team']).Caps.sum() caps_per_team_per_group.plot(kind='bar', figsize=(15,5)) and for visual purposes, I want it to look like this:
tagged with: pandas
tagged with: python
tagged with: jupyter-notebook
type: AnsweredQuestion
type: Question
tagged with: matplotlib

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

http://stackoverflow.com/comment/88729702
type: Comment
type: QuestionComment
has text: If you pull both data sets into Python, then you have to do the comparison in Python. If you pull one data set into the other database, then you can do the comparison using SQL. Depending on the complexity of the comparison(s), the latter approach might be preferable.
comment on: http://stackoverflow.com/q/50863413
score: 0

image-processing
tags question: http://stackoverflow.com/q/50903919
tags question: http://stackoverflow.com/q/50945444
tags question: http://stackoverflow.com/q/50937304
tags question: http://stackoverflow.com/q/50972987
tags question: http://stackoverflow.com/q/50948082
tags question: http://stackoverflow.com/q/50873319
tags question: http://stackoverflow.com/q/50902373
tags question: http://stackoverflow.com/q/50966269
tags question: http://stackoverflow.com/q/50902087
tags question: http://stackoverflow.com/q/50907540
tags question: http://stackoverflow.com/q/50998679
tags question: http://stackoverflow.com/q/50865560
tags question: http://stackoverflow.com/q/50961110
tags question: http://stackoverflow.com/q/50917074
tags question: http://stackoverflow.com/q/51005083
tags question: http://stackoverflow.com/q/50972401
tags question: http://stackoverflow.com/q/50855188
tags question: http://stackoverflow.com/q/50895381
tags question: http://stackoverflow.com/q/50930832
tags question: http://stackoverflow.com/q/50922579
tags question: http://stackoverflow.com/q/50969805
type: Tag
tags question: http://stackoverflow.com/q/50881585
tags question: http://stackoverflow.com/q/50995950
tags question: http://stackoverflow.com/q/50924974
tags question: http://stackoverflow.com/q/50948559
tags question: http://stackoverflow.com/q/50861659
tags question: http://stackoverflow.com/q/50898333
tags question: http://stackoverflow.com/q/50889958
tags question: http://stackoverflow.com/q/51009135
tags question: http://stackoverflow.com/q/50885585
tags question: http://stackoverflow.com/q/51000056
tags question: http://stackoverflow.com/q/50957151
tag name: image-processing
tags question: http://stackoverflow.com/q/50994212
tags question: http://stackoverflow.com/q/50894561
tags question: http://stackoverflow.com/q/50958158
tags question: http://stackoverflow.com/q/50909993
tags question: http://stackoverflow.com/q/50904604
tags question: http://stackoverflow.com/q/50928863

http://stackoverflow.com/q/50868147
score: -1
has comment: http://stackoverflow.com/comment/88738342
has body: I'm trying to create a function that creates a pivot table, and I need to filter one column based on a string. df = DataFrame({'Breed': ['Sheltie', 'Bernard', 'Husky', 'Husky', 'pig', 'Sheltie','Bernard'], 'Metric': ['One month walked', 'two month walked', 'three month walked', 'four month walked', 'one month waiting', 'two month waiting', 'Three month waiting'], 'Age': [1,2,3,4,5,6,7]}) I want a pivot table with the ages of all the dogs summed up, where they have a 'completed' metric, regardless of what month. It would look a little something like this: Age Breed Metric sum ------------------------------------ Husky one month walked 4 Husky four month walked 5 The function would filter out any of the metrics that are not 'walked', while summing up each of the 'completed' metric. I've been trying this so far. import pandas as pd import fnmatch def Dog_Walked_Completed(dfprime): return dfprime[dfprime['Breed'] == 'Husky'].groupby(['Breed','Metric']).fnmatch.filter(lambda df : (df['Metric']=='?completion')).any().agg({'Age': ['sum']}) But whenever i try that, I get a ''DataFrameGroupBy' object has no attribute 'fnmatch' error. Is there a different way to do wildcard searches within a function?
has comment: http://stackoverflow.com/comment/88738334
tagged with: pandas
answer count: 1
downvote count: 1
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/88738831
has comment: http://stackoverflow.com/comment/88740248
has comment: http://stackoverflow.com/comment/88738557
upvote count: 0
has comment: http://stackoverflow.com/comment/88738467
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88738323
has comment: http://stackoverflow.com/comment/88738317
type: Question
has title: Use .filter within a function
has comment: http://stackoverflow.com/comment/88738597
has answer: http://stackoverflow.com/a/50868354

http://stackoverflow.com/q/50934180
score: 0
has title: Having @property only run once
downvote count: 2
answer count: 1
favorite count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/50934292
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50934292
type: Question
has body: I have the following example: class A: value = None @property def value(self): if not value: result = &lt;do some external call&gt; self.value = result return self.value However, this is not working since I'm getting the exception: AttributeError: can't set attribute And that makes sense, but what would be the idiomatic way of doing something like this? I don't just want to use different names.
has comment: http://stackoverflow.com/comment/88866916
linked to: http://stackoverflow.com/q/4037481
has comment: http://stackoverflow.com/comment/88866910
upvote count: 2

http://stackoverflow.com/comment/89001546
has text: If you wrote it in XQuery, there's a good chance your XQuery processor would do the optimization automatically.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51002096
type: QuestionComment

http://stackoverflow.com/comment/88786637
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50893060
type: AnswerComment
has text: shouldn't `albums = json.load(file)` be `albums = json.load(jsonfile)`. Also thanks for the comment on my wrong answer, never knew jsons could be strictly arrays.

http://stackoverflow.com/q/50860285
tagged with: tensorflow
type: Question
downvote count: 0
tagged with: keras
answer count: 1
score: 1
favorite count: 0
has title: ValueError: Tensor is not an element of this graph
tagged with: watchdog
type: UnansweredQuestion
tagged with: python
has body: At the moment I am testing some deep learning with TensorFlow and Keras. Now I would like to evaluate pictures. Therefore I need to know with help of the watchdog class if a new image is created in a folder. In this case I want to do a prediction. Therefore I need to load my trained deep learning model from a .json file first and initialize it with weights from an .h5 file. This step takes some time. Therefore I plan to load the model once and subsequently I would like to do many predictions. Unfortunately I got the following error message and I suggest something with the loaded_model went wrong. If I load it for every prediction there is no problem but this way is not what I want. ##### Prediction-Class ##### #Import from keras.models import model_from_json import numpy as np from keras.preprocessing import image from PIL import Image class PredictionClass(): #loaded_model = self.LoadModel() counter = 0 def Load_Model(self): modelbez = 'modelMyTest30' gewichtsbez = 'weightsMyTest30' # load json and create model print("Loading...") json_file = open(modelbez + '.json', 'r') loading_model_json = json_file.read() json_file.close() loading_model = model_from_json(loading_model_json) # load weights into new model loading_model.load_weights(gewichtsbez + ".h5") print('Loaded model from disk:' + 'Modell: ' + modelbez + 'Gewichte: ' + gewichtsbez) loading_model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy']) return loading_model def Predict(path, loaded_model): test_image = image.load_img(path, target_size = (64, 64)) test_image = image.img_to_array(test_image) test_image = np.expand_dims(test_image, axis = 0) # This step causes the error result = loaded_model.predict(test_image) print('Prediction successful') if result[0][0] == 1: prediction = 'schlecht' img = Image.open(path) img.save(path, "JPEG", quality=80, optimize=True, progressive=True) #counterschlecht = counterschlecht +1 else: prediction = 'gut' img = Image.open(path) img.save(path,…
has answer: http://stackoverflow.com/a/50861489
upvote count: 1

http://stackoverflow.com/comment/89011184
type: Comment
has text: @hyperpallium I updated the gist with a second variant that does explicit backtracking. That is closer to real engines, and can be mapped easily to low-level languages. Although I am copying the op_stack, whereas real engines can avoid copies by using linked lists. NFAs are typically executed by breadth-first search through the states, or by compiling them to a DFA. Parsing with derivatives is an illustrative parsing algorithm, but too inefficient for practical use. I'm using it to construct the `cont` regex. Parser combinators work well but are not used in “real” engines due to high overhead.
comment on: http://stackoverflow.com/a/50985990
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88949878
type: Comment
comment on: http://stackoverflow.com/q/50973830
type: QuestionComment
has text: Don't fall into the trap of [programming by coincidence](https://pragprog.com/the-pragmatic-programmer/extracts/coincidence); really *think* about what the code you're writing means.
score: 0

http://stackoverflow.com/q/50868960
has title: How do I insert data into the middle of a singlelinkedlist in python?
score: 0
answer count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/88989566
downvote count: 1
has body: Node Class and SingleLinkedList Class code: class Node(): '''represents a node as a building block of a single linked list''' def __init__(self, element, next_node=None): '''(Node, obj, Node) -&gt; NoneType construct a node as building block of a single linked list''' self._element = element self._next = next_node def set_next(self, next_node): '''(Node, Node) -&gt; NoneType set node to point to next_node''' self._next = next_node def set_element(self, element): '''(Node, obj) -&gt;NoneType set the _element to a new value''' self._element = element def get_next(self): '''(Node) -&gt; Node returns the reference to next node''' return self._next def get_element(self): '''(Node) -&gt; obj returns the element of this node''' return self._element def __str__(self): '''(Node) -&gt; str returns the element of this node and the reference to next node''' return "(" + str(self._element) + ", " + str(hex(id(self._next))) + ")" class SingleLinkedList(): ''' represents a single linked list''' def __init__(self): '''(SingleLinkedList) -&gt;NoneType initializes the references of an empty SLL''' self._size = 0 self._head = None self._tail = None self._value = None self._next = None def set_head(self, new_head): '''(SingleLinkedList) -&gt; None updates the head''' self._head = new_head def set_tail(self, new_tail): '''(SingleLinkedList) -&gt; None updates the tail''' self._tail = new_tail def get_head(self): '''(SingleLinkedList) -&gt; Node Return the pointer to the head''' return self._head def get_tail(self): '''(SingleLinkedList) -&gt; Node Return the pointer to the tail''' return self._tail def is_empty(self): '''(SingleLinkedList) -&gt; bool returns true if no item is in this SLL''' return self._size == 0 def size(self): '''(SingleLinkedList) -&gt; int returns the number of items in this SLL''' return self._size def add_first(self, element): '''(SingleLinkedList, obj) -&gt; NoneType adds a node to the first of the SLL''' # create a node that point to the head node = Node(elemen…
has comment: http://stackoverflow.com/comment/88740361
has answer: http://stackoverflow.com/a/50869054
type: AnsweredQuestion
favorite count: 0
has comment: http://stackoverflow.com/comment/88989595
type: Question
has comment: http://stackoverflow.com/comment/88989541
has comment: http://stackoverflow.com/comment/88989542
possible better answer: http://stackoverflow.com/a/50869247
tagged with: python
accepted answer: http://stackoverflow.com/a/50869054
has answer: http://stackoverflow.com/a/50869247
tagged with: singly-linked-list
tagged with: list

http://stackoverflow.com/comment/88730499
comment on: http://stackoverflow.com/q/50863652
type: Comment
score: 0
has text: Consider whether you really should define a single function that needs to differentiate its arguments by type in the first place. `None` is usually checked for explicitly, as it signals an implementation-defined default (e.g. `if x is None: x = MY_DEFAULT`). The rest of your function sounds like it just needs a *number*, or a string that can be parsed as a number, in which case it's cleaner to make the *caller* convert the string to a number first and pass the result to your function....
type: QuestionComment

api
tags question: http://stackoverflow.com/q/50937618
tags question: http://stackoverflow.com/q/50912420
tags question: http://stackoverflow.com/q/50977420
tags question: http://stackoverflow.com/q/50861779
tags question: http://stackoverflow.com/q/50887035
tags question: http://stackoverflow.com/q/50897423
tags question: http://stackoverflow.com/q/50888651
tags question: http://stackoverflow.com/q/50993973
tags question: http://stackoverflow.com/q/50872681
tags question: http://stackoverflow.com/q/50881224
tags question: http://stackoverflow.com/q/50933127
type: Tag
tags question: http://stackoverflow.com/q/50968008
tags question: http://stackoverflow.com/q/50962410
tags question: http://stackoverflow.com/q/50964625
tags question: http://stackoverflow.com/q/50924750
tags question: http://stackoverflow.com/q/50898607
tag name: api
tags question: http://stackoverflow.com/q/50910736
tags question: http://stackoverflow.com/q/50959926
tags question: http://stackoverflow.com/q/50871702
tags question: http://stackoverflow.com/q/50976289
tags question: http://stackoverflow.com/q/50880536
tags question: http://stackoverflow.com/q/50938976
tags question: http://stackoverflow.com/q/50933079
tags question: http://stackoverflow.com/q/50926614

http://stackoverflow.com/a/50878955
has body: You have the definition of this effect in the python doc: https://docs.python.org/2/tutorial/floatingpoint.html you can format your result at the print to have the 3 digits you want: print("%.3f" % np.float64(100) - np.float64(123.123))
accepted answer of: http://stackoverflow.com/q/50878858
answers question: http://stackoverflow.com/q/50878858
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/88762726
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/comment/88765225
has text: Thank you! I did not know that. Lambda seems to be a good tool.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50872429
type: Comment

http://stackoverflow.com/q/50863853
tagged with: pip
type: Question
has answer: http://stackoverflow.com/a/50863878
accepted answer: http://stackoverflow.com/a/50863878
has comment: http://stackoverflow.com/comment/88730210
has comment: http://stackoverflow.com/comment/88733234
score: 0
has comment: http://stackoverflow.com/comment/88731542
has comment: http://stackoverflow.com/comment/88730206
answer count: 1
has comment: http://stackoverflow.com/comment/88731593
has title: Terminal doesn't recognize pip as a directory on macOS
has comment: http://stackoverflow.com/comment/88730256
has body: While trying to troubleshoot why the $ pip install command always returns code 1 errors, I tried to enter my pip directory from within a shell. I started by running $ which pip and got /Library/Frameworks/Python.framework/Versions/3.6/bin/pip When I subsequently run cd /Library/Frameworks/Python.framework/Versions/3.6/bin/ and run ls, I get the following: which clearly includes 'pip' as a directory. However, when I run $ cd pip I get the following error. bash: cd: pip: Not a directory How is this possible?
tagged with: python
tagged with: macos
type: AnsweredQuestion

http://stackoverflow.com/q/50997898
has answer: http://stackoverflow.com/a/50998052
has answer: http://stackoverflow.com/a/50998059
possible better answer: http://stackoverflow.com/a/50998059
upvote count: 1
answer count: 4
favorite count: 0
has title: Python 3 is adding elements to a list regardless of key used in dict
has answer: http://stackoverflow.com/a/50998345
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
tagged with: list
accepted answer: http://stackoverflow.com/a/50998052
downvote count: 0
score: 1
has body: I have a dict that I defined with: keys = ['Valid', 'Reverse'] NOC = dict.fromkeys(keys, []) I then iterate through a file and based on elements in the rows I add them to different lists in that dict based on a value in the row This is code inside the list comprehension looping through the reader content: if item[0] == '4': if float(item[10]) &lt; 0: state = 'Reverse' print(state) NOC[state].append(item[6]+"FOOOO") if float(item[10]) &gt;= 0: state = 'Valid' print(state) NOC[state].append(item[6]) print (NOC['Reverse']) As you can see, I am adding the string "FOOOO" in the case of 'Reverse". I did this to see what was happening inside of the lists in the dict. I have validated that the if-then statements are all working correctly. However, the appends seem to be writing to the same place in memory. It's strange. Here is some output of the list comprehension looping through the file content: Valid ['68382011714'] Valid ['68382011714', '69315013701'] Valid ['68382011714', '69315013701', '16729018201'] Valid ['68382011714', '69315013701', '16729018201', '54458098010'] Valid ['68382011714', '69315013701', '16729018201', '54458098010', '61570007301'] Valid ['68382011714', '69315013701', '16729018201', '54458098010', '61570007301', '61570007301'] Reverse ['68382011714', '69315013701', '16729018201', '54458098010', '61570007301', '61570007301', '61570007301FOOOO'] It makes no sense to me that print(NOC['Reverse']) is showing values that have anything other than those with the appended "FOOOO". Why is this happening?
has answer: http://stackoverflow.com/a/50998130
type: Question

http://stackoverflow.com/comment/88743552
comment on: http://stackoverflow.com/a/50870496
score: 0
type: Comment
has text: My code after update looks like, `images = cv2.resize(roi_2,(12,12)); myImage = Image.fromarray(images); pix = np.array(myImage.getdata()).flatten()` This gives me a flattened array of length, `12x12x3`. The code when updated as below, `myImage = Image.fromarray(images); pix = np.array(myImage.getdata()).reshape(myImage.size[0], myImage.size[1], 3)` also gives `12x12x3` matrix. What is the significance of `reshape`?
type: AnswerComment

http://stackoverflow.com/q/50970824
accepted answer: http://stackoverflow.com/a/51009763
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/88938965
score: -1
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/88939759
linked to: http://stackoverflow.com/q/3294889
has comment: http://stackoverflow.com/comment/88940611
downvote count: 2
has body: I have the following dict structure d = {'Attributes': {'Fifth': 'blind (19.33%)', 'First': 'Art (40.0%)', 'Fourth': 'Ser (20.0%)', 'Second': 'Nat (21.33%)', 'Third': 'per (20.67%)'}} Need to convert into the following structure list of dictionary items [ 0: {'First': 'Art (40.0%)'}, 1: {'Second': 'Nat (21.33%)'}, 2: {'Third': 'per (20.67%)'}, 3: {'Fourth': 'Ser (20.0%)'}, 4: {'Fifth': 'blind (19.33%)'} ]
has comment: http://stackoverflow.com/comment/88938132
upvote count: 1
has comment: http://stackoverflow.com/comment/88940552
has title: Conversion of Dict object into a list of dict object
type: Question
has comment: http://stackoverflow.com/comment/88938678
has comment: http://stackoverflow.com/comment/88938223
has comment: http://stackoverflow.com/comment/88938466
has comment: http://stackoverflow.com/comment/88938374
has answer: http://stackoverflow.com/a/51009763
has comment: http://stackoverflow.com/comment/88938278
has comment: http://stackoverflow.com/comment/88938320
has comment: http://stackoverflow.com/comment/88938247
answer count: 2
has comment: http://stackoverflow.com/comment/88940451
possible better answer: http://stackoverflow.com/a/51009353
has comment: http://stackoverflow.com/comment/88940555
has answer: http://stackoverflow.com/a/51009353
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/comment/88748549
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50872445
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/173205/discussion-between-saud-and-sudhanshu-vishnoi).

http://stackoverflow.com/a/51003152
answers question: http://stackoverflow.com/q/51003126
type: AcceptedAnswer
downvote count: 0
has body: Yes, "__main__" is a string literal, since module names are strings. The module is called __main__ to distinguish it from modules named main, and since it is a system-assigned name.
type: Answer
score: 3
accepted answer of: http://stackoverflow.com/q/51003126
upvote count: 3

http://stackoverflow.com/q/50886609
tagged with: h2o
favorite count: 0
answer count: 0
type: UnansweredQuestion
has body: I am trying to calculate variance of multiple columns across each row. Hence the result would have dimension no_of_rows*1. I tried following way: import pandas as pd test = pd.DataFrame({'p1':[0.8,0.7,0.3],'p10':[0.4,0.6,0.3],'p11':[0.9,0.6,0.4],'p12':[0.44,9.8,0.4],'p13':[0.8,0.4,0.5],'p14':[0.7,0.7,0.7],'p15':[0.8,0.8,0.5]}) test_h2o = h2o.H2OFrame(test) test_h2o'p1','p10','p11','p12','p13','p14','p15'.head().apply(lambda x: x.var(),1) and I get the error "Expected a Frame but found a class water.rapids.vals.ValRow". However with mean as function it works test_h2o'p1','p10','p11','p12','p13','p14','p15'.head().apply(lambda x: x.mean(),1)
tagged with: python
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/88840430
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/88854986
has title: Variance across row in h2o

http://stackoverflow.com/q/50944827
score: 0
tagged with: pandas
answer count: 1
favorite count: 0
has body: I cant find problem with variables registration. Jinja2 show me: builtins.UnboundLocalError UnboundLocalError: local variable 'df' referenced before assignment When I try add: global df after function definition Flask told me that variable is not definied. @app.route("/<stop_id>") def show_table(stop_id): stops = pd.read_csv('stops.csv', header=0, usecols=[1, 2]) chosen_stop = stops['stop_name'] == stop_id output_stops = (stops[chosen_stop]) stop_codes = tuple(output_stops['stop_code']) for i, j in enumerate(stop_codes): specific_url = URL + str(j) response = requests.get(specific_url, auth=HTTPDigestAuth(USERNAME, PASSWORD), verify=False) if len(response.content) > 0: data = response.json() df = pd.DataFrame.from_dict(data, orient='columns') return render_template('view.html', tables=[pd.DataFrame.to_html(df, index=False)]) if __name__ == "__main__": app.run(debug=True) HTML: Project {% for table in tables %} {% endfor %}
has answer: http://stackoverflow.com/a/50947530
tagged with: python
has title: Flask view creates DataFrame but still raises "UnboundLocalError: local variable 'df' referenced before assignment"
type: AnsweredQuestion
upvote count: 1
downvote count: 1
accepted answer: http://stackoverflow.com/a/50947530
type: Question

http://stackoverflow.com/comment/127081280
has text: Thank you so much! This is the only comment I have seen to work LDFLAGS=-L/usr/local/opt/openssl/lib pip install mysql-python
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50864487
type: Comment

http://stackoverflow.com/comment/88933754
type: Comment
comment on: http://stackoverflow.com/a/50966925
score: 0
has text: Hrm just to confirm, it should look like this (for MacOS): https://certsimple.com/images/blog/localhost-ssl-fix/trust-new-certificate.png
type: AnswerComment

http://stackoverflow.com/q/50996749
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/88988249
upvote count: 1
has comment: http://stackoverflow.com/comment/88987973
type: Question
downvote count: 0
has title: Use VBA to run a Python Script
tagged with: vba
favorite count: 0
has comment: http://stackoverflow.com/comment/89006433
type: UnansweredQuestion
has body: I'm trying to run a python script through VBA and shell function. Below is my VBA code Private Sub Script() Dim wsh As Object Set wsh = VBA.CreateObject("WScript.Shell") Dim waitOnReturn As Boolean: waitOnReturn = True Dim windowStyle As Integer: windowStyle = 1 MyFile = "C:\Desktop\cmdcode.bat" fnum = FreeFile() Open MyFile For Output As #fnum Print #fnum, "cd C:\Desktop\" Print #fnum, "python CreatePPT.py" Close #fnum ' Run bat-file: wsh.Run MyFile, windowStyle, waitOnReturn ' optional, remove bat-file: Kill "C:\Desktop\cmdcode.bat" End Sub I think I was able to call cmd, it couldn't run my python script. Below is the cmd window called using the shell function (I'm new to Stackoverflow and it doesn't allow me to embed images before I hit certain reputation. My apologizes) cmd window 1 Below is the cmd window called from my start menu cmd window 2 Looks like there are difference between these 2 cmd windows, and the first one wasn't able to execute my python script, while the second one was working fine. Any insights what could be the reasons? thanks!
tagged with: python

http://stackoverflow.com/a/50863841
accepted answer of: http://stackoverflow.com/q/50863789
has comment: http://stackoverflow.com/comment/88796940
has comment: http://stackoverflow.com/comment/88800997
answers question: http://stackoverflow.com/q/50863789
type: Answer
score: 2
has body: You need to pass the data to the template like so. return render_template("index.html", data=data) Then in the HTML file you can loop through the data like this. &lt;div id='info_section'&gt; {% for data in data %} &lt;p&gt;{{ data }}&lt;/p&gt; {% endfor %} &lt;/div&gt; If you want to access a column of the entry you can do &lt;p&gt;{{ data.whatever_attribute }}&lt;/p&gt;
downvote count: 0
has comment: http://stackoverflow.com/comment/88801273
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/a/51002667
answers question: http://stackoverflow.com/q/51001205
downvote count: 1
score: 0
type: Answer
has body: The problem in your code is simple. Here in for loop you assign item to json_dict variable: for item in json_mean['response']: json_dict = item And then you want to access this json_dict in another while loop: while True: try: age = json_dict['bdate'] The problem here is scoping. So every variable in almost every language (f.e var in JS is different) has a scope. It means that if you create it in a block of code (which in languages like C/C++/Java and so on is between {} and in Python it is done by indenting the code) your variable "is alive" until you leave this block of code. In the code you presented, not only you lose the scope of json_dict variable (so it is not known to the compiler, or in this current example the interpreter) after leaving your for loop and you cannot access it from your while loop, but additionally you overwrite it with every iteration of your for loop (I don't know if thats what you really wanted to do). The solution would be creating json_dict above for loop (and f.e assigning it to None, whatever) and then accessing it both from for and while loops
upvote count: 1

http://stackoverflow.com/comment/88921492
comment on: http://stackoverflow.com/q/50962318
score: 0
type: Comment
type: QuestionComment
has text: ...`for line in [ipfile]:`...

http://stackoverflow.com/comment/132290445
type: Comment
has text: I agree with @NathanielVerhaaren. This solution may work for what most people are coming here for, but it is incomplete. Anything that is not covered by the conditions (i.e. something un-serializable that is not `np.generic`) will be mapped to `null`. Just try with an empty function and you'll notice that it doesn't raise any errors. The json.dumps [doc page](https://docs.python.org/3/library/json.html#json.dump) is clear about this.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/65151218

http://stackoverflow.com/comment/88875615
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50938630
has text: Actually, scratch what I said above; [even in Python 0.9 you got this information](https://gist.github.com/abarnert/6ffc8b6cf51adcbe647339eacd7b6d9f). Pretty impressive REPL for 1991.
score: 0

http://stackoverflow.com/comment/88803769
score: 0
comment on: http://stackoverflow.com/q/50901923
type: Comment
type: QuestionComment
has text: This is weird. Works in ipython but not in python shell

http://stackoverflow.com/a/51009893
has body: Consider the following sentence as tokens: sentence = ["the","book","is","on","the","table"] and consider a window_size of 3. The code that builds window_sequences can be reformulated like this: for ix in range(len(sentence)): x = sentence[ix] #so this is the ix-th word of the sentence from_index = max((ix-window_size) # this is the initial index of the window to_index = (ix+window_size+1) # this is the final index of the windows (excluding itself) window = sentence[from_index, to_index] # we pick the words of the sentence Now let's run this code for some ix: ix=0, x="the", from_index=0, to_index=4, window = ["the", "book", "is", "on"] ix=3, x="on", from_index=0, to_index=7, window = ["the", "book", "is", "on", "the", "table"] As you see it is constructing windows of words and they are exactly portions of original sentences. A problem you could have encountered in analyzing this code is that sentence words are substituted with a numeric id in such a way as that the more frequent a word is the lower its id. So the sentence before would appear like: sentence = [2,45,7,13,2,67] They are not sorted in frequency-order but they exactly keep the order in the sentence. Only their surface form is changed from string to int but you can easily understand the code on the string version.
has comment: http://stackoverflow.com/comment/89016205
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51007989
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51007989

http://stackoverflow.com/comment/89000035
has text: Almost: how do you map dtypes to colunm *numbers*?
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51003214
type: Comment

http://stackoverflow.com/comment/88864257
type: QuestionComment
comment on: http://stackoverflow.com/q/50930330
has text: Because I intended to use multithreading, but I was not sure if was the proper solution.
score: 0
type: Comment

http://stackoverflow.com/q/50939736
has comment: http://stackoverflow.com/comment/88879905
favorite count: 0
tagged with: python
tagged with: selenium-webdriver
tagged with: selenium-chromedriver
type: AnsweredQuestion
has title: How I use python selenium for click Navigation Bar With Dropdown
has answer: http://stackoverflow.com/a/50940868
score: 1
has comment: http://stackoverflow.com/comment/88877577
tagged with: selenium
upvote count: 1
has body: I want to click on "Page 1" for show list of sub menu python code I used driver.find_element_by_xpath("nav/div/ul/li[2]/a").click() website code: Home Page 1 Page 1-1 Page 1-2 Page 1-3 Page 2 Page 3 Image of nav
type: Question
accepted answer: http://stackoverflow.com/a/50940868
answer count: 2
has comment: http://stackoverflow.com/comment/88878565
possible better answer: http://stackoverflow.com/a/50941111
tagged with: automated-tests
has comment: http://stackoverflow.com/comment/88877614
has answer: http://stackoverflow.com/a/50941111
downvote count: 0

ldap3
tags question: http://stackoverflow.com/q/50988232
type: Tag
tag name: ldap3

http://stackoverflow.com/comment/88722000
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50859653
has text: A popular Python library for plotting is [Matplotlib](https://matplotlib.org/).

http://stackoverflow.com/a/50979909
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/50978923
type: Answer
has body: Update: I tried @Sunitha solution but accumulate is not in itertools - maybe because running 2.7. I've tested this code with Python 2.7.15 and Python 3.6.5. This code starts at the second sublist in the list (index 1, if applicable) and looks backwards at the previous sublist to accumulate the values as in your example. Python 2.7.15rc1 (default, Apr 15 2018, 21:51:34) [GCC 7.3.0] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; hmm = [['x', 1, 2, 3], ['y', 2, 5, 4], ['z', 6, 2, 1]] &gt;&gt;&gt; for i in range(1, len(hmm)): ... prev = hmm[i - 1][1:] ... current = iter(hmm[i]) ... hmm[i] = [next(current)] + [a + b for a, b in zip(prev, current)] ... &gt;&gt;&gt; hmm [['x', 1, 2, 3], ['y', 3, 7, 7], ['z', 9, 9, 8]] It could be written slightly different in Python 3 as well: Python 3.6.5 (default, Jun 14 2018, 13:19:33) [GCC 7.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; hmm = [['x', 1, 2, 3], ['y', 2, 5, 4], ['z', 6, 2, 1]] &gt;&gt;&gt; for i in range(1, len(hmm)): ... _, *prev = hmm[i - 1] ... letter, *current = hmm[i] ... hmm[i] = [letter] + [a + b for a, b in zip(prev, current)] ... &gt;&gt;&gt; hmm [['x', 1, 2, 3], ['y', 3, 7, 7], ['z', 9, 9, 8]]
upvote count: 1

http://stackoverflow.com/a/50908851
type: Answer
has body: You can use this: wait = WebDriverWait(webdriver, 10) load_button = wait.until(EC.presence_of_element_located((By.XPATH, "//div[@class = 'feed-load-more-button']"))) load_button.click()
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/50908744
downvote count: 0

http://stackoverflow.com/q/50938277
downvote count: 8
tagged with: python
has comment: http://stackoverflow.com/comment/88874923
type: AnsweredQuestion
tagged with: tkinter
has comment: http://stackoverflow.com/comment/88874824
tagged with: tk-toolkit
upvote count: 1
tagged with: import
type: Question
score: -7
accepted answer: http://stackoverflow.com/a/50938344
has comment: http://stackoverflow.com/comment/88874950
has comment: http://stackoverflow.com/comment/88875011
has comment: http://stackoverflow.com/comment/88874834
has comment: http://stackoverflow.com/comment/88874908
has title: How can I use tkinter library with Python 2.7
has comment: http://stackoverflow.com/comment/88874940
answer count: 1
has comment: http://stackoverflow.com/comment/88874999
favorite count: 0
has body: When it comes to import the library. I got an error that the module is not found I'm using Python 2.7 Windows with 32 bit Is there a solution?
has answer: http://stackoverflow.com/a/50938344

http://stackoverflow.com/comment/88741652
type: QuestionComment
has text: What is this shape `(2829, 3)`? It doesn't look like proportions of a regular single character.
comment on: http://stackoverflow.com/q/50869559
score: 0
type: Comment

http://stackoverflow.com/comment/88857944
comment on: http://stackoverflow.com/a/50929337
type: AnswerComment
score: 0
type: Comment
has text: So if I don't specify any sender, every action that saves a models instance will call the post_save signal?

http://stackoverflow.com/q/51005263
favorite count: 0
downvote count: 1
has body: I'm trying to change specific datetime values in a dict into strings by recursively iterating through it's keys. from copy import deepcopy def datetoStr2(datadict): if 'dict' in str(type(datadict)): newdict = dict() newdict.update(datadict) for key in datadict: if isinstance(datadict[key], dict): newdict[key] = datetoStr(datadict[key]) if isinstance(datadict[key], list): mylist = datadict[key] for element in mylist: element = datetoStr(element) if isinstance(datadict[key], datetime): #newdict[key] = datadict[key].strftime('%Y-%m-%d %H:%M:%S.%f%z') newdict[key] = str(datadict[key]) return newdict else: return datadict However, when I run some_dict = datetoStr(mydict) I still have datetime objects in the places as they are. What am I doing wrong? EDIT: Updated function code. This function was written because this dict is passed through Flask's jsonify which currently strips the Timezone info and replaces it with GMT. (This is scheduled to be fixed in the next update). I've updated my function keeping in mind some of the feedback, but I am still unable to produce the result. I'm adding some sample data and my output as well. Result: A quick print inserted in the code tells me the datetime remains a datetime, and TZinfo is stripped out by jsonify. Sample Data: {'data': {'all': {'count': 2, 'data': [{'arrivalby': 'Wed, 20 Jun 2018 09:39:00 GMT', 'closesat': 'Wed, 20 Jun 2018 06:05:40 GMT', 'doctype': 'general', 'geofence': {'coordinates': [[[78.43786473803105, 17.447430456650043], [78.45670406196896, 17.447430456650043], [78.45670406196896, 17.46540214334996], [78.43786473803105, 17.46540214334996], [78.43786473803105, 17.447430456650043]]], 'type': 'Polygon'}, 'housecallid': '591ce42e9b53f96ea393934f61fab25d', 'lastupdated': 'Fri, 22 Jun 2018 04:32:14 GMT', 'requester': {'addr1': 'xxx xxx xx', 'addr2': 'xx xx xx', 'addr3': 'xx xx', 'addrstate': 'xx', 'city': 'xx', 'dob': 'xx/xx/xxxx', 'email': 'xx@xx', 'fname': 'xxx', 'lname': 'xx', 'location': {'coordinates': [78.44728…
has answer: http://stackoverflow.com/a/51005368
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89004117
has title: Iterate through a dictionary and modify values
tagged with: python
has comment: http://stackoverflow.com/comment/89004683
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89004091
score: 1
tagged with: python-datetime
type: Question
upvote count: 2
answer count: 1
accepted answer: http://stackoverflow.com/a/51005368

http://stackoverflow.com/comment/88770208
has text: This question is too broad in its current state. What exactly do you need help with? This may be helpful: https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response
score: 1
comment on: http://stackoverflow.com/q/50884136
type: Comment
type: QuestionComment

http://stackoverflow.com/a/53185358
score: 0
has body: I'm very intersted in this question as well, unfortunately it seems impossible. While setting up a log record, the python logger accepts the dict extra to add information to that record (see Lib/logging/__init__.py). Unfortunately the logger methods like .info(msg) do not accept a similar option AND changing the line number will raise an exception, as the key will already be present (see Lib/logging/__init__.py 1252 ff): rv = LogRecord(name, level, fn, lno, msg, args, exc_info, func) if extra is not None: for key in extra: if (key in ["message", "asctime"]) or (key in rv.__dict__): raise KeyError("Attempt to overwrite %r in LogRecord" % key) rv.__dict__[key] = extra[key] I'm very curious if anybody has an idea, why the developers did not allow the manipulation of the logger (if it was an purpose or just not important enough).
answers question: http://stackoverflow.com/q/50976330
type: Answer

http://stackoverflow.com/q/51011188
tagged with: python-3.x
tagged with: python
has answer: http://stackoverflow.com/a/51011202
accepted answer: http://stackoverflow.com/a/51011202
has title: how to set value in 2 cell if other cell contains 'something'
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
tagged with: numpy
has body: I have some pandas dataframe: a,b,c AAA,, DDD,, KKK,, AAA,, I want to search in column "A" and if string in column "A" contains word "AAA" I need set value "BBB" in column "B" and "CCC" in column "C". So, I want to get result as following: a,b,c AAA,BBB,CCC DDD,, KKK,, AAA,BBB,CCC I wrote the code with numpy: df['b'] = pd.np.where(df.a.str.contains("AAA"), "BBB", '') How to extend it to work with 'b' and 'c' columns?
tagged with: dataframe
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/88840847
type: AnswerComment
score: 0
type: Comment
has text: Correct. Take the `NextContinuationToken` from one call and pass it in as `ContinuationToken` on the next call.
comment on: http://stackoverflow.com/a/50920463

http://stackoverflow.com/q/50860182
has title: Error when checking input: expected conv2d_1_input to have shape (28, 28, 1) but got array with shape (3, 224, 224)
tagged with: python
type: AnsweredQuestion
tagged with: conv-neural-network
possible better answer: http://stackoverflow.com/a/50872497
has answer: http://stackoverflow.com/a/50872497
type: Question
answer count: 2
has body: How do I solve it? codes used by me are displayed below this is for converting image to vector import cv2 import numpy as np file = cv2.imread('17316.png') file = cv2.resize(file, (224, 224)) file = cv2.cvtColor(file, cv2.COLOR_BGR2RGB) file = np.array(file).reshape((1, 3, 224, 224)) print(file.shape[0]) this is part of convolution neural network applied by me whoich lead to that error what do I do,how do I solve it please suggest me changes to code so that I can get proper predictions for my dataset? model = Sequential() model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=input_shape)) model.add(Conv2D(64, (3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(128, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(num_classes, activation='softmax'))
accepted answer: http://stackoverflow.com/a/50860463
tagged with: keras
score: 0
tagged with: deep-learning
has answer: http://stackoverflow.com/a/50860463

http://stackoverflow.com/comment/88857041
has text: Please post the code you have tried so far.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50929015
score: 2

http://stackoverflow.com/a/50874079
has comment: http://stackoverflow.com/comment/88750812
score: 0
has comment: http://stackoverflow.com/comment/88750282
answers question: http://stackoverflow.com/q/50873976
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/88750404
has comment: http://stackoverflow.com/comment/88750809
has comment: http://stackoverflow.com/comment/88750643
has comment: http://stackoverflow.com/comment/88750285
has comment: http://stackoverflow.com/comment/88750767
has comment: http://stackoverflow.com/comment/88750672
has body: Since your problem is with the unknown key's you can use get method of the dictionary to safely ignore unknown keys. For get method, first argument is the key you are looking for and the second argument is the Default value which will be returned when the key is not found. so, do the following return [NewsItem.from_payload(hit['_source']) for hit in result.get('hits',{}).get('hits',"NOT FOUND"): The above is just a example. do modify what you want to get when the hit does not have the key you want.
has comment: http://stackoverflow.com/comment/88750834
has comment: http://stackoverflow.com/comment/88749647
type: Answer
has comment: http://stackoverflow.com/comment/88750757

http://stackoverflow.com/comment/89005630
type: AnswerComment
has text: Perfect. Thanks!
comment on: http://stackoverflow.com/a/50997062
type: Comment
score: 0

http://stackoverflow.com/comment/88774226
comment on: http://stackoverflow.com/q/50886294
has text: Whats the resolution ?
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/50912591
score: 4
favorite count: 0
tagged with: pandas
accepted answer: http://stackoverflow.com/a/57214233
tagged with: python
type: AnsweredQuestion
has title: pandas_ml change confusion matrix image size
type: Question
tagged with: matplotlib
has body: How can the size of a pandas_ml confusion matrix image with lots of classes be increased so the labels are clearly visible? Such an image can be generated in Jupyter like this: import pandas as pd from pandas_ml import ConfusionMatrix import matplotlib.pyplot as plt import string %matplotlib inline classes = string.printable # 100 target classes df = pd.DataFrame({'true':list(classes*10), 'pred':sorted(classes*2)+list(classes*8) }) cm = ConfusionMatrix(df['true'],df['pred']) cm.plot() I've tried various suggestions involving changing figure sizes and subfigure sizes, as well as looking for size or width in the pandas_ml docs but nothing has worked so far.
linked to: http://stackoverflow.com/q/41530975
tagged with: pandas-ml
upvote count: 4
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/10388462
has answer: http://stackoverflow.com/a/57214233

http://stackoverflow.com/a/50949609
answers question: http://stackoverflow.com/q/50935153
has comment: http://stackoverflow.com/comment/88896807
type: Answer
score: 2
downvote count: 0
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50935153
has body: So thanks to @user4815162342 here is the solution : def __init__(self, interval=1): self.interval = interval logging.basicConfig(level=logging.INFO) loop = asyncio.new_event_loop(); asyncio.set_event_loop(loop) loop.run_until_complete(self.runCoap()) loop.close() Mqtt = multiprocessing.Process(target = self.runMqtt) async def runCoap(self): print('COUCOU C cOAP') protocol = await Context.create_client_context() requestTemp = Message(code=GET, uri='coap://129.6.60.38/other/sensors/temperature') requestHumidity = Message(code=GET, uri='coap://129.6.60.38/other/sensors/humidity') while True: await asyncio.sleep(1) try: responseTemp = await protocol.request(requestTemp).response responseHumidity = await protocol.request(requestHumidity).response except Exception as e: print('Failed to fetch resource:') print(e) else: print('Result: %s\n%r'%(responseTemp.code, responseTemp.payload)) print('Result: %s\n%r'%(responseHumidity.code, responseHumidity.payload))

http://stackoverflow.com/q/50957341
tagged with: python
type: AnsweredQuestion
score: 3
downvote count: 0
tagged with: async-await
type: Question
has title: How to setup a background process using asyncio as part of a module
answer count: 2
has body: I'm writing a python module (experimental use case) which gives users the ability to send messages to another computer. The computer we want to send the message to has an unknown address which changes at arbitrary times. There is another computer (intermediary) which provides the address and time until the address expires. For simplicity sake, let's call the one sending the message computer-A, the one receiving computer-B and computer-C is the intermediary we need to contact for computer-B's address. What I'm trying to accomplish: I want to be able to defer the process of waiting for the expiration time to be over to asyncio.sleep(). When the time expires, I would expect the process to get back control of the event loop and run a function to update the address. The problem i'm struggling with is how do i implement this within a class where I cannot invoke run_until_complete/run_forever (or am i blatantly incorrect). How do you implement such a thing using the asyncio framework? Example hypothetical code?: from some_random_messaging_service import deliver_msg INTERMEDIARY_COMPUTER_C_ADDRESS = "some.random.address" class CustomMessagingSystem: def __init__(self, computer=None): """Constructor :param computer: computer name """ self.addresses = {} if computer: self.get_address(computer) def get_address(self, computer): """Gets address from computer-C (intermediary) :param computer: computer name """ self.addresses[computer] = self.find_address(INTERMEDIARY_COMPUTER_C_ADDRESS, computer) await self.update_address(computer, self.expiration_time(computer)) def expiration_time(self, computer): """ :param computer: computer name :return: address expiration time in seconds """ return self.addresses[computer][1] def address(self, computer): """ :param computer: computer name :return: computer address """ return self.addresses[computer][0] async def update_address(self, computer, expiration_time): """updates address of computer after given expiration_time :param computer: compu…
upvote count: 3
has answer: http://stackoverflow.com/a/50957973
accepted answer: http://stackoverflow.com/a/50957973
tagged with: python-asyncio
possible better answer: http://stackoverflow.com/a/50957496
tagged with: asynchronous
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50957496

http://stackoverflow.com/a/50978831
downvote count: 0
score: 8
upvote count: 8
has comment: http://stackoverflow.com/comment/88963778
type: Answer
has comment: http://stackoverflow.com/comment/88962232
has comment: http://stackoverflow.com/comment/88963890
has comment: http://stackoverflow.com/comment/88966655
has comment: http://stackoverflow.com/comment/88963935
answers question: http://stackoverflow.com/q/50978323
has comment: http://stackoverflow.com/comment/88962020
has body: How to get probabilities (percentages)? Use the predict_proba method. What is decision_function ? Since the SGDClassifier is a linear model, the decision_function outputs a signed distance to the separating hyperplane. This number is simply &lt;w,x> + b or translated to scikit-learn attribute names &lt;coef_,x> + intercept_.
has comment: http://stackoverflow.com/comment/88963602

http://stackoverflow.com/a/50870608
score: 0
answers question: http://stackoverflow.com/q/50868270
type: Answer
has body: In DriverForm change yn field like this yn = forms.BooleanField(initial=False)

http://stackoverflow.com/q/50907764
has comment: http://stackoverflow.com/comment/88815510
tagged with: parsing
downvote count: 0
accepted answer: http://stackoverflow.com/a/50914877
has body: I am trying the following (python 3.6) import dateutil.parser as dp t1 = '0001-04-23T02:25:43.511Z' t2 = '0001-04-23T01:25:43.511Z' print(dp.parse(t1)) print(dp.parse(t2)) which gives me 0001-04-23 02:25:43.511000+00:00 0023-01-04 01:25:43.511000+00:00 In various similar cases, when the year string has form 00XY and the hour string XY, the parser seems to produce the wrong output. Am I missing something, or is this a bug?
has comment: http://stackoverflow.com/comment/88815780
type: AnsweredQuestion
tagged with: python-dateutil
has answer: http://stackoverflow.com/a/50914877
score: 4
type: Question
answer count: 1
has title: python dateutil.parser wrong (??) parsing
favorite count: 0
has comment: http://stackoverflow.com/comment/88816218
tagged with: datetime
tagged with: python
has comment: http://stackoverflow.com/comment/88815867
upvote count: 4

http://stackoverflow.com/a/50925144
has body: def dates_from_file(f): with open(f) as file: for l in file: yield l[0:16] dates = [d for d in dates_from_file("internet.test")] print(dates)
type: Answer
answers question: http://stackoverflow.com/q/50924879
score: 0

http://stackoverflow.com/comment/113158135
comment on: http://stackoverflow.com/q/50932821
score: 0
has text: Facing same issue, I am getting coloured in HTML file but not seeing any colour in doc file My input is a Pandas Stylo object which i converted into a HTML string
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50996038
has title: Automatically populate relations in Django admin
has comment: http://stackoverflow.com/comment/89209775
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88991766
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/88988930
has comment: http://stackoverflow.com/comment/88987769
linked to: http://stackoverflow.com/q/9352662
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/88987502
has comment: http://stackoverflow.com/comment/89200925
has comment: http://stackoverflow.com/comment/89166753
has comment: http://stackoverflow.com/comment/89050561
score: 0
has body: I'm working on my first Django app. My goal is to have two models, one for offices and one for employees, and when a person record is created (in the admin site), creating and specifying the room also populates that room with that person. I was able to create the models, but now I'm stuck in a catch-22 where when I add a person, I have to create a room, but to create a room I have to add a person, etc... How can I create and automatically populate a room like this? Here is the relevant code from models.py: class Room(models.Model): number = models.CharField('Room number', primary_key=True, max_length=50) occupant = models.ManyToManyField('Person', blank=True) # Can have multiple occupants class Person(models.Model): name = models.CharField('Full name', max_length=200) office = models.ForeignKey(Room, on_delete=models.SET_NULL, null=True) # Some offices may not have an occupant Update: I added blank=True to office so I can create an office with no occupant. But, even when I add a person and assign their office to that number, and it shows that in the admin page, the detail-view page doesn't seem to grab that, unless I manually go into the Room admin page and select the person. Can that part be automated?

http://stackoverflow.com/comment/88924528
has text: Why don't you extract it right away?
score: 0
comment on: http://stackoverflow.com/q/50963346
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88879812
has text: It said i can accept the answer in 7 minutes. im just waiting for those 7 minutes
type: Comment
score: 1
comment on: http://stackoverflow.com/a/50940987
type: AnswerComment

http://stackoverflow.com/a/50887728
answers question: http://stackoverflow.com/q/50886451
type: AcceptedAnswer
downvote count: 0
has body: Here is a minimum working piece of code just to focus on saving graphs. I intentionally omitted graph-styling parts of your code to be simple. import matplotlib.pyplot as plt dictionary_town = {'Berlin': [[1, 333]], 'London': [[1, 111], [2, 555]], 'Paris': [[1, 444], [2, 222], [3, 999]]} path = '/your_path_to_image_saving/' #pls change here i = 0 for town, values in dictionary_town.items(): x = [] y = [] i += 1 save_plot = path + str(i) + '.png' for value in values: x.append(value[0]) y.append(value[1]) plt.figure() plt.scatter(x=x, y=y, label=town) plt.ylabel("Population") plt.title(str(i)) plt.legend(loc=4) plt.savefig(save_plot) plt.close() I recommend you to start from here and add some stylings one by one to figure out what's wrong. Hope this helps. EDIT: Plot 5 cities at a time. If you want to change # of cities, change chunk. Also, if # of cities needs to be larger than 5, colors needs to be added accordingly. import matplotlib.pyplot as plt import numpy as np dictionary_town = {'Berlin': [[1, 333]], 'London': [[1, 111], [2, 555]], 'Paris': [[1, 444], [2, 222], [3, 999]]} colors = {1: 'r', 2: 'b', 3: 'g', 4: 'k', 5: 'grey'} path = '/your_path_to_image_saving/' #pls change here i = 0 chunk = 5 for town, values in dictionary_town.items(): i += 1 values = np.array(values) x = values[:,0] y = values[:,1] plt.scatter(x=x, y=y, label=town, color=colors[(i+1)%chunk+1]) if i % chunk == 0: save_plot = path + str(i) + '.png' plt.ylabel("Population") plt.title(str(i)) plt.legend(loc=4) plt.savefig(save_plot) plt.close() elif (i == len(dictionary_town)) &amp; (i % chunk != 0): save_plot = path + str(i) + '.png' plt.ylabel("Population") plt.title(str(i)) plt.legend(loc=4) plt.savefig(save_plot) plt.close()
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/88802228
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50886451
has comment: http://stackoverflow.com/comment/88791095

http://stackoverflow.com/comment/88962399
type: AnswerComment
comment on: http://stackoverflow.com/a/50983726
type: Comment
has text: Thank you,sir!This is useful.
score: 0

http://stackoverflow.com/q/50877819
has title: Telegram bot on webhook with flask
downvote count: 0
score: 1
tagged with: flask
favorite count: 0
tagged with: telegram
type: Question
tagged with: webhooks
has answer: http://stackoverflow.com/a/52825402
has body: I try to create Telegram bot, i'am using: Ubuntu 18 python 3.6 pyTelegramBotAPI flask Here is my code: API_TOKEN = 'My_Token' WEBHOOK_HOST = 'My_ip' WEBHOOK_PORT = 8443 # 443, 80, 88 or 8443 (port need to be 'open') WEBHOOK_LISTEN = '0.0.0.0' # In some VPS you may need to put here the IP addr WEBHOOK_SSL_CERT = './webhook_cert.pem' # Path to the ssl certificate WEBHOOK_SSL_PRIV = './webhook_pkey.pem' # Path to the ssl private key WEBHOOK_URL_BASE = "https://%s:%s" % (WEBHOOK_HOST, WEBHOOK_PORT) WEBHOOK_URL_PATH = "/%s/" % (API_TOKEN) logger = telebot.logger telebot.logger.setLevel(logging.INFO) bot = telebot.TeleBot(API_TOKEN) apihelper.proxy = {'https': 'socks5://login:password@ip:port'} app = flask.Flask(__name__) # Empty webserver index, return nothing, just http 200 @app.route('/', methods=['GET', 'HEAD']) def index(): return '' # Process webhook calls @app.route(WEBHOOK_URL_PATH, methods=['GET', 'POST']) def webhook(): print(flask.request.headers) if flask.request.headers.get('content-type') == 'application/json': json_string = flask.request.get_data().decode('utf-8') update = telebot.types.Update.de_json(json_string) bot.process_new_updates([update]) return '' else: print('You NOT made it!') flask.abort(403) # Handle '/start' and '/help' @bot.message_handler(commands=['help', 'start']) def send_welcome(message): bot.reply_to(message, ("Hi there, I am EchoBot.\n" "I am here to echo your kind words back to you.")) # Handle all other messages @bot.message_handler(func=lambda message: True, content_types=['text']) def echo_message(message): bot.reply_to(message, message.text) # Remove webhook, it fails sometimes the set if there is a previous webhook bot.remove_webhook() time.sleep(0.1) # Set webhook bot.set_webhook(url=WEBHOOK_URL_BASE+WEBHOOK_URL_PATH, certificate=open(WEBHOOK_SSL_CERT, 'r')) # Start flask server app.run(host=WEBHOOK_LISTEN, port=WEBHOOK_PORT, ssl_context=(WEBHOOK_SSL_CERT, WEBHOOK_SSL_PRIV), debug=True) My program starts well, but nothing happe…
tagged with: python
tagged with: py-telegram-bot-api
upvote count: 1
answer count: 1
type: UnansweredQuestion

http://stackoverflow.com/comment/88728263
has text: This would give fraction values. Not percentage values.
comment on: http://stackoverflow.com/a/50862816
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/88825538
type: Comment
type: QuestionComment
has text: https://realpython.com/modern-web-automation-with-python-and-selenium/ this might be what you are looking for.
comment on: http://stackoverflow.com/q/50912666
score: 0

http://stackoverflow.com/comment/88825775
type: Comment
comment on: http://stackoverflow.com/a/50881081
score: 1
type: AnswerComment
has text: Neither is better. It is as you say, one is lazy and one is immediate. Otherwise they are both mostly the same.

http://stackoverflow.com/comment/88795276
score: 0
comment on: http://stackoverflow.com/q/50897444
type: Comment
type: QuestionComment
has text: One important point: don't use convolutions with a kernel size of `1*1`. The minimum recommended size is `3*3` (`1*1` convolutions have another applications and are rarely used alone).

http://stackoverflow.com/comment/88988100
type: Comment
comment on: http://stackoverflow.com/a/50972468
score: 1
has text: Also, regarding adjusting the existing O(R/G)M or doing something different, I'd suggest the best route is to abstract your data from your implementation into your database. If you can store the data in NetworkX, then you're in a stronger position to put it into any data store (although sounds like Neo4J is probably your best bet). Write code to create your data, then write code to store it! That way it's easier to test, and if you decide to change to something else in future you only have to change one smaller module that does one thing rather than one big module that does too many things.
type: AnswerComment

http://stackoverflow.com/comment/88850719
type: QuestionComment
has text: I think that you are right. Here is another answer: http://www.pgpool.net/mediawiki/index.php/Main_Page . I f you want post an answer to help others.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50924843

loops
tags question: http://stackoverflow.com/q/50880595
tags question: http://stackoverflow.com/q/51010481
tags question: http://stackoverflow.com/q/50869654
tags question: http://stackoverflow.com/q/51002971
tags question: http://stackoverflow.com/q/50958972
tags question: http://stackoverflow.com/q/50967065
tags question: http://stackoverflow.com/q/50949765
tags question: http://stackoverflow.com/q/50928657
tags question: http://stackoverflow.com/q/50950906
tags question: http://stackoverflow.com/q/50981503
type: Tag
tags question: http://stackoverflow.com/q/50905462
tags question: http://stackoverflow.com/q/50972901
tags question: http://stackoverflow.com/q/51009887
tags question: http://stackoverflow.com/q/50897254
tags question: http://stackoverflow.com/q/50888544
tags question: http://stackoverflow.com/q/50940661
tags question: http://stackoverflow.com/q/50883894
tags question: http://stackoverflow.com/q/50998203
tags question: http://stackoverflow.com/q/50974075
tags question: http://stackoverflow.com/q/50972054
tags question: http://stackoverflow.com/q/50868109
tags question: http://stackoverflow.com/q/50961598
tags question: http://stackoverflow.com/q/50871840
tags question: http://stackoverflow.com/q/50914083
tags question: http://stackoverflow.com/q/51001660
tags question: http://stackoverflow.com/q/50991345
tags question: http://stackoverflow.com/q/50959624
tags question: http://stackoverflow.com/q/51006126
tags question: http://stackoverflow.com/q/51010502
tags question: http://stackoverflow.com/q/51009483
tag name: loops
tags question: http://stackoverflow.com/q/50935272
tags question: http://stackoverflow.com/q/50892601
tags question: http://stackoverflow.com/q/50956456
tags question: http://stackoverflow.com/q/51004990
tags question: http://stackoverflow.com/q/50955701
tags question: http://stackoverflow.com/q/50923756
tags question: http://stackoverflow.com/q/50859965
tags question: http://stackoverflow.com/q/50898184
tags question: http://stackoverflow.com/q/50974899
tags question: http://stackoverflow.com/q/50856563
tags question: http://stackoverflow.com/q/50955427
tags question: http://stackoverflow.com/q/50873376
tags question: http://stackoverflow.com/q/50886076
tags question: http://stackoverflow.com/q/50980245
tags question: http://stackoverflow.com/q/50997639
tags question: http://stackoverflow.com/q/50958938
tags question: http://stackoverflow.com/q/50909802
tags question: http://stackoverflow.com/q/50860578
tags question: http://stackoverflow.com/q/50918419
tags question: http://stackoverflow.com/q/50901296
tags question: http://stackoverflow.com/q/50884136
tags question: http://stackoverflow.com/q/50894168

http://stackoverflow.com/a/50895553
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50895454
has body: This answer assumes that there is different maximum values per user in Values column: In [10]: def get_max(group): ...: return group[group.Date == group.Date.max()] ...: In [12]: df.groupby('User').apply(get_max).reset_index(drop=True) Out[12]: Date User Values 0 14 A x 1 14 B z 2 14 C s
upvote count: 5
type: Answer
downvote count: 0
score: 5
accepted answer of: http://stackoverflow.com/q/50895454

http://stackoverflow.com/comment/88885421
has text: Possible duplicate of [Python 3: EOF when reading a line (Sublime Text 2 is angry)](https://stackoverflow.com/questions/12547683/python-3-eof-when-reading-a-line-sublime-text-2-is-angry)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50943995
score: 2

http://stackoverflow.com/a/51077359
downvote count: 0
type: Answer
upvote count: 1
has body: NFA backtracking The various engines seem to first construct (or "compile") an NFA from the regular expression, then execute the NFA, following transitions from state to state, and backtracking to a previous state when a route fails. Please note: the backtracking is done on the NFA, not on the regular expression. An NFA is a kind of automata, with a graph of nodes (states) connected by directed arcs (transitions). An arc is labeled with a character; when that character is seen in the text, that arc is followed. An NFA is a Non-deterministic Finite Automata - the "non-deterministic" part means that two arcs leaving a node can have the same label, so that both are followed simultaneously. There can also be epsilon transitions (ε, representing the empty string - no character), which are always followed without needing a input character. Backtracking means when we come to a choice, we checkpoint the state (where we are in the automata and in the text). Then, make a choice. If it doesn't work out, we revert or "backtrack" to that checkpoint, and tnry the next choice. Like navigating a cave, when might go deeper and deeper through a series of forks before we hit a dead-end, "nesting" the checkpoints. Java source code analysis Constructing NFA The process for contructing an NFA from a regular expression is called "Thompson's construction". For details, please see MJD article or Regular Expression Matching Can Be Simple And Fast (about 1/5 the way through, section "Converting Regular Expressions to NFAs"). There's also a wikipedia article Thompson's construction. Java's implementation (java/util/regex/Pattern.java) recursively-descent parses the regular expression, with methods expr() (alternation |), sequence(), atom(), closure() (optional ? and star *), generating the NFA as Node objects with a next field for the transition to another Node. There are many, many different Node subclasses. notes: (1) expr() calls sequence() which returns with a so-called "double return" - i…
score: 1
answers question: http://stackoverflow.com/q/50983308

http://stackoverflow.com/q/50912960
has title: referencing python libraries in a separate folder
has answer: http://stackoverflow.com/a/50913020
has body: Im pip-ing all my libraries to a folder called lib. My source code is in the directory scr. My directory structure Folder -lib -different libraries -scr -main.py I just want to reference my libraries so my code will run.
score: 0
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/50912999
has comment: http://stackoverflow.com/comment/88826308
has comment: http://stackoverflow.com/comment/88827020
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/4383571
has comment: http://stackoverflow.com/comment/88826118
favorite count: 0
type: Question
answer count: 2
tagged with: python

http://stackoverflow.com/comment/89002188
has text: Should repeated patterns *with no spaces in between* be supported?
score: 0
comment on: http://stackoverflow.com/q/51004201
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/88906749
type: Comment
comment on: http://stackoverflow.com/a/50954481
score: 1
has text: @BenjaminToueg I'm operating under the impression that this is what they actually wanted, even if it wasn't what they wrote.
type: AnswerComment

http://stackoverflow.com/comment/88801721
comment on: http://stackoverflow.com/a/50900143
type: AnswerComment
score: 0
type: Comment
has text: @PrimuS Simply do : `list(bincount_numexpr_app(a))`.

django-forms
tags question: http://stackoverflow.com/q/50928395
tags question: http://stackoverflow.com/q/50922794
tags question: http://stackoverflow.com/q/50942003
tags question: http://stackoverflow.com/q/50858571
tags question: http://stackoverflow.com/q/50908729
tag name: django-forms
type: Tag
tags question: http://stackoverflow.com/q/50859307
tags question: http://stackoverflow.com/q/50921532
tags question: http://stackoverflow.com/q/50891877
tags question: http://stackoverflow.com/q/50953809
tags question: http://stackoverflow.com/q/50970667
tags question: http://stackoverflow.com/q/50948274
tags question: http://stackoverflow.com/q/50950864
tags question: http://stackoverflow.com/q/51007517
tags question: http://stackoverflow.com/q/50906044
tags question: http://stackoverflow.com/q/50857793
tags question: http://stackoverflow.com/q/50934156
tags question: http://stackoverflow.com/q/50976740
tags question: http://stackoverflow.com/q/50869399
tags question: http://stackoverflow.com/q/50879042
tags question: http://stackoverflow.com/q/51002076

http://stackoverflow.com/q/50971091
answer count: 3
tagged with: pandas
downvote count: 0
has body: The below code helps in obtaining subplots with unique colored boxes. But all subplots share a common set of x and y axis. I was looking forward to having independent axis for each sub-plot: import pandas as pd import numpy as np import matplotlib.pyplot as plt from matplotlib.patches import PathPatch df = pd.DataFrame(np.random.rand(140, 4), columns=['A', 'B', 'C', 'D']) df['models'] = pd.Series(np.repeat(['model1','model2', 'model3', 'model4', 'model5', 'model6', 'model7'], 20)) bp_dict = df.boxplot( by="models",layout=(2,2),figsize=(6,4), return_type='both', patch_artist = True, ) colors = ['b', 'y', 'm', 'c', 'g', 'b', 'r', 'k', ] for row_key, (ax,row) in bp_dict.iteritems(): ax.set_xlabel('') for i,box in enumerate(row['boxes']): box.set_facecolor(colors[i]) plt.show() Here is an output of the above code: I am trying to have separate x and y axis for each subplot...
favorite count: 0
possible better answer: http://stackoverflow.com/a/50971284
linked to: http://stackoverflow.com/q/14503423
tagged with: boxplot
has answer: http://stackoverflow.com/a/50971284
tagged with: python
score: 4
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/2176424
tagged with: matplotlib
has answer: http://stackoverflow.com/a/50971301
type: Question
upvote count: 4
has title: Independent axis for each subplot in pandas boxplot
accepted answer: http://stackoverflow.com/a/50971301
tagged with: dataframe
has answer: http://stackoverflow.com/a/51020046

http://stackoverflow.com/comment/88900304
score: 0
comment on: http://stackoverflow.com/q/50951177
type: QuestionComment
type: Comment
has text: damn, there's always a duplicate :)

http://stackoverflow.com/q/50889797
has comment: http://stackoverflow.com/comment/88781001
upvote count: 0
type: Question
score: -1
has answer: http://stackoverflow.com/a/50889905
has body: I am picking names of the same starting letter. When the result comes out for any rows over 2, it is automatically repeated the part other than the first row and the last row though the bottom statement still reads non-repeated rows. Drop_duplicates() does not work at all, the repeated rows can not be deleted. Bonus question: Why is the value selection Numbers&gt;13908 not working when there's only one matching row?
tagged with: pandas
downvote count: 1
answer count: 1
has title: How to drop duplicates in condition drop_duplicates() does not work at all?
favorite count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/51007214
answer count: 3
tagged with: python
linked to: http://stackoverflow.com/q/41986507
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89008110
type: UnansweredQuestion
score: -3
upvote count: 1
type: Question
has title: Python 2.7.5 and Python 3.6.5
has body: I have installed Python 3.6.5 however when i type Python it shows Python 2.7.5. Id like to use Python 3. [aravind@aravind05 Python-3.6.5]$ python3 --version Python 3.6.5 [aravind@aravind05 Python-3.6.5]$ python Python 2.7.5 (default, Apr 11 2018, 07:36:10) [GCC 4.8.5 20150623 (Red Hat 4.8.5-28)] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; I want to use Python 3
has answer: http://stackoverflow.com/a/51007255
has answer: http://stackoverflow.com/a/51208067
downvote count: 4
favorite count: 0
has answer: http://stackoverflow.com/a/51749850
has comment: http://stackoverflow.com/comment/89007945

http://stackoverflow.com/comment/88729838
score: 0
has text: I'm trying to grab the worksheet's title from the cell. I thought I could just do cell.worksheet.title? Tells me the "cell" object does not have an object "worksheet"
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50863152

http://stackoverflow.com/q/50897702
tagged with: feedparser
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/50898972
accepted answer: http://stackoverflow.com/a/50898972
has comment: http://stackoverflow.com/comment/88795307
has comment: http://stackoverflow.com/comment/88795277
tagged with: python
has body: I have designed a full-screen clock for my Raspberry Pi 3 Model B which runs on Raspbian but can also run on Windows. The whole point of the clock is to show the date, time, and a RSS feed on r/news (Reddit). The news feed should stay on the screen for 5 seconds then change to the next one, and this process should go on forever until I exit. If I use sleep(), the clock stops. I have tried using threading, but it only works on the first loop, and then tries to show the next one, but returns to the previous one. The clock and date work fine, it's just that I can't get the feed to stay on screen for 5 seconds and move on to the next one. Code: import sys if sys.version_info[0] == 2: from Tkinter import * else: from tkinter import * from time import * import datetime import feedparser root = Tk() d = feedparser.parse('https://www.reddit.com/r/news/.rss') def exitt(): sleep(3) root.destroy() time1 = '' extra_time1 = '' clock = Label(root, font=('calibri light', 150), bg='black', fg='white') clock.pack(fill=BOTH, expand=1) extra_clock = Label(root, font=('calibri light', 45), bg='black', fg='white') extra_clock.pack(fill=BOTH, expand=1) label_rss = Label(root, font=('calibri', 14), bg='black', fg='white') label_rss.pack(fill=BOTH) end = Button(root, text="Exit", font=('bold', 20), fg="white", bg='black', bd=0, borderwidth=0, highlightthickness=0, highlightcolor='black', command=lambda:exitt(), height=0, width=0) end.pack(fill=BOTH) def rssfeeds(): for post in d.entries: RSSFEED = post.title label_rss.config(text=RSSFEED) #sleep(5) &lt;-- To prevent glitches but to keep my point #rssfeeds() def tick(): global time1 time2 = strftime("%H:%M:%S") if time2 != time1: time1 = time2 clock.config(text=time2) clock.after(1, tick) def ticki(): global extra_time1 extra_time2 = strftime("%A, %d %B %Y") if extra_time2 != extra_time1: extra_time1 = extra_time2 extra_clock.config(text=extra_time2) extra_clock.after(1, ticki) tick() ticki() w, h = root.winfo_screenwidth(), root.winfo_scre…
type: AnsweredQuestion
tagged with: tkinter
has comment: http://stackoverflow.com/comment/88795679
tagged with: rss
has comment: http://stackoverflow.com/comment/88796179
has title: Issues in time delay for RSS feed on full screen clock python
type: Question

http://stackoverflow.com/a/59111870
score: 0
type: Answer
has body: My timing tests differ from Scott for small lists. Using Python 3.7.3, set() is much faster than np.unique for a small numpy array from randint (length 8), but faster for a larger array (length 1000). Length 8 Timing test iterations: 10000 Function Min Avg Sec Conclusion p-value ---------- --------- ----------- ------------ --------- set_len 0 7.73486e-06 Baseline unique_len 9.644e-06 2.55573e-05 Slower 0 Length 1000 Timing test iterations: 10000 Function Min Avg Sec Conclusion p-value ---------- ---------- ----------- ------------ --------- set_len 0.00011066 0.000270466 Baseline unique_len 4.3684e-05 8.95608e-05 Faster 0 Then I tried my own implementation, but I think it would require optimized C code to beat set: def check_items(key_rand, **kwargs): for i, vali in enumerate(key_rand): for j in range(i+1, len(key_rand)): valj = key_rand[j] if vali == valj: break Length 8 Timing test iterations: 10000 Function Min Avg Sec Conclusion p-value ----------- ---------- ----------- ------------ --------- set_len 0 6.74221e-06 Baseline unique_len 0 2.14604e-05 Slower 0 check_items 1.1138e-05 2.16369e-05 Slower 0 (using my randomized compare_time() function from easyinfo)
answers question: http://stackoverflow.com/q/50883576

http://stackoverflow.com/a/50992055
downvote count: 0
type: Answer
upvote count: 7
has comment: http://stackoverflow.com/comment/88979866
has body: The problem is that you are iterating through the word and using its letters as indexes, this would fix it: def farrange(word): finaloutput = '' for i, l in enumerate(word): if i%2 == 0: finaloutput += l.upper() else: finaloutput += l.lower() return finaloutput a more pythonic way for example: def arrange(word): op = ( str.upper, str.lower ) return "".join(op[x%2](l) for x, l in enumerate(word))
score: 7
has comment: http://stackoverflow.com/comment/88978954
has comment: http://stackoverflow.com/comment/88978906
answers question: http://stackoverflow.com/q/50992005

http://stackoverflow.com/q/50892309
favorite count: 0
tagged with: python
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50892325
has body: I have a pandas dataframe like the following: import pandas as pd pd.DataFrame({"AAA":["x1","x1","x1","x2","x2","x2"], "BBB":["y1","y1","y2","y2","y2","y1"], "CCC":["t1","t2","t3","t1","t1","t1"], "DDD":[10,11,18,17,21,30]}) Out[1]: AAA BBB CCC DDD 0 x1 y1 t1 10 1 x1 y1 t2 11 2 x1 y2 t3 18 3 x2 y2 t1 17 4 x2 y2 t1 21 5 x2 y1 t1 30 The problem What I want is to group on column AAA so I have 2 groups - x1, x2. I want then calculate the ratio of y1 to y2 in column BBB for each group. And assign this output to a new column Ratio of BBB The desired output So I want this as my output. pd.DataFrame({"AAA":["x1","x1","x1","x2","x2","x2"], "BBB":["y1","y1","y2","y2","y2","y1"], "CCC":["t1","t2","t3","t1","t1","t1"], "DDD":[10,11,18,17,21,30], "Ratio of BBB":[0.33,0.33,0.33,0.66,0.66,0.66]}) Out[2]: AAA BBB CCC DDD Ratio of BBB 0 x1 y1 t1 10 0.33 1 x1 y1 t2 11 0.33 2 x1 y2 t3 18 0.33 3 x2 y2 t1 17 0.66 4 x2 y2 t1 21 0.66 5 x2 y1 t1 30 0.66 Current status I have currently achieved it like so: def f(df): df["y1"] = sum(df["BBB"] == "y1") df["y2"] = sum(df["BBB"] == "y2") df["Ratio of BBB"] = df["y2"] / df["y1"] return df df.groupby(df.AAA).apply(f) What I want to achieve Is there anyway to achieve this with the .pipe() function? I was thinking something like this: df = (df .groupby(df.AAA) # groupby a column not included in the current series (df.colname) .BBB .value_counts() .pipe(lambda series: series["BBB"] == "y2" / series["BBB"] == "y1") ) Edit: One solution using pipe() N.B: User jpp made clear comment below: unstack / merge / reset_index operations are unnecessary and expensive However, I initially intended to use this method i thought I would share it here! df = (df .groupby(df.AAA) # groupby the column .BBB # select the column with values to calculate ('BBB' with y1 &amp; y2) .value_counts() # calculate the values (# of y1 per group, # of y2 per group) .unstack() # turn the rows into columns (y1, y2) .pipe(lambda df: df["y1"]/df["y2"]) # calculate the ratio of y1:y2 (o…
upvote count: 2
has title: pandas for each group calculate ratio of two categories, and append as a new column to dataframe using .pipe()
type: Question
tagged with: pipe
accepted answer: http://stackoverflow.com/a/50892325
possible better answer: http://stackoverflow.com/a/50892408
answer count: 2
tagged with: pandas-groupby
tagged with: pandas
has answer: http://stackoverflow.com/a/50892408
downvote count: 0

http://stackoverflow.com/comment/88867835
has text: do you need something like `import json` `kwargs= json.loads(JSON_str)` `instance=Message(**kwargs)`?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50934222
score: 2

http://stackoverflow.com/q/50955219
has title: convert unknown file type readable by notepad to .csv files
type: AnsweredQuestion
upvote count: 0
has body: I have 300 files with extension .EMA (never seen before) that I would like to convert to .csv files. The files are perfectly readable in Notepad. However, I need to convert them to .csv files as I want to read them with Python. Does anyone know how to convert the files in a quick way? Thanks.
has answer: http://stackoverflow.com/a/50955265
accepted answer: http://stackoverflow.com/a/50955265
has comment: http://stackoverflow.com/comment/88908424
type: Question
downvote count: 3
answer count: 1
has comment: http://stackoverflow.com/comment/88908167
favorite count: 0
tagged with: http://stackoverflow.com/tag/csv
score: -3
tagged with: python

http://stackoverflow.com/comment/88917530
score: 0
type: Comment
type: QuestionComment
has text: Mad Physicist: I'm not sure. But when I also tested with the stopwatch at http://online-stopwatch.chronme.com/, the difference between the times on two pictures was from 0.041s to 0.045s.
comment on: http://stackoverflow.com/q/50960177

http://stackoverflow.com/a/51006481
score: 5
has body: In Python 3+ you just use zip instead. It's builtin, so you don't have to import it. Try using the 2to3 tool to update the code automatically.
type: AcceptedAnswer
upvote count: 5
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51006477
answers question: http://stackoverflow.com/q/51006477

http://stackoverflow.com/comment/88784907
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50890013
type: Comment
has text: @patronizing_bofh, I forgot to change the `fig, ax` setup lines. I've edited the answer; try it now.

http://stackoverflow.com/q/51001480
type: Question
has title: Load File on Pyspark Worker Once
has body: I have a problem with a large object (400mb pickled) I need to use in a UDF. The object is pickled and on every worker but I don't know how to have it load on a worker outside the UDF which causes it to be reloaded for every row. Broadcast hasn't really helped the overhead of loading this up for every task crashes everything in my dev environment.
tagged with: pyspark
downvote count: 0
tagged with: apache-spark
linked to: http://stackoverflow.com/q/37343437
favorite count: 0
answer count: 0
linked to: http://stackoverflow.com/q/35500196
type: UnansweredQuestion
upvote count: 1
tagged with: python
score: 1
has comment: http://stackoverflow.com/comment/88999277

http://stackoverflow.com/q/50930805
type: UnansweredQuestion
tagged with: multithreading
has answer: http://stackoverflow.com/a/50930862
has comment: http://stackoverflow.com/comment/88860651
has comment: http://stackoverflow.com/comment/88860741
has comment: http://stackoverflow.com/comment/88861160
score: 2
has title: Nested for loops looping through a python list
tagged with: nested-loops
has body: I have to loop through a list of over 4000 item and check their similarity with a recommendation algorithm in python. The script takes a long time to run (10-11 Hours) and I wanted to incorporate multi-threading to improve speed but dont know how to do it exactly. import numpy as np import pandas as pd import matplotlib.pyplot as plt data=pd.read_csv('data.csv',index_col=0, encoding="ISO-8859-1") # Get list of unique items itemList=list(set(data["product_ref"].tolist())) # Get count of customers userCount=len(set(data["customer_id"].tolist())) # Create an empty data frame to store item affinity scores for items. itemAffinity= pd.DataFrame(columns=('item1', 'item2', 'score')) def itemUsers(ind): return data[data.product_ref==itemList[ind]]["customer_id"].tolist() rowCount=0 for ind1 in range(len(itemList)): item1Users = itemUsers(ind1) pool = Pool() pool.map(loop2, data_inputs) for ind2 in range(ind1+1, len(itemList)): print(ind1, ":", ind2) item2Users = itemUsers(ind2) commonUsers= len(set(item1Users).intersection(set(item2Users))) score=commonUsers / userCount itemAffinity.loc[rowCount] = [itemList[ind1],itemList[ind2],score] rowCount +=1
has comment: http://stackoverflow.com/comment/88860895
type: Question
answer count: 1
downvote count: 0
tagged with: iteration
tagged with: pandas
has comment: http://stackoverflow.com/comment/88860854
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/88860768
upvote count: 2

http://stackoverflow.com/comment/88979260
type: QuestionComment
comment on: http://stackoverflow.com/q/50992241
has text: The parent dictionary key will change because it's associated with a dictionary that compares an IP prefix to different buildings. So, ideally I would like to keep that key a variable.
score: 0
type: Comment

http://stackoverflow.com/a/50990307
upvote count: 1
score: 1
has body: Take a look at Scapy. You can forge all the packets you want with it and it's a fairly simple API.
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50989064

http://stackoverflow.com/q/50874602
has body: Hi I have a vector where the min is 5.748113263784852 and the max is 175.5 I want to scale those values to a 0 to 10 ( 1 2 3 ... 10 ). how can I do?
answer count: 2
downvote count: 2
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88750560
tagged with: python
possible better answer: http://stackoverflow.com/a/50876339
has answer: http://stackoverflow.com/a/50874978
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50876339
accepted answer: http://stackoverflow.com/a/50874978
has title: How to normalize vector to [0 10] range
has comment: http://stackoverflow.com/comment/88750980
type: Question
has comment: http://stackoverflow.com/comment/88751012
tagged with: math
score: -1

http://stackoverflow.com/q/50907224
type: Question
tagged with: multiprocessing
has title: not able to terminate the process in multiprocessing python (linux)
score: 3
tagged with: kill
tagged with: terminate
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/50908038
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/50907961
has body: I am new to python and using multiprocessing, I am starting one process and calling one shell script through this process. After terminating this process shell script keeps running in the background, how do I kill it, please help. python script(test.py) #!/usr/bin/python import time import os import sys import multiprocessing # test process def test_py_process(): os.system("./test.sh") return p=multiprocessing.Process(target=test_py_process) p.start() print 'STARTED:', p, p.is_alive() time.sleep(10) p.terminate() print 'TERMINATED:', p, p.is_alive() shell script (test.sh) #!/bin/bash for i in {1..100} do sleep 1 echo "Welcome $i times" done
upvote count: 3
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/284325

http://stackoverflow.com/comment/88854847
score: 0
has text: The last index, `[65:]`, should probably be added as well.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50927993

http://stackoverflow.com/q/51008968
tagged with: http://stackoverflow.com/tag/json
type: Question
accepted answer: http://stackoverflow.com/a/51009035
has body: I'm trying to save a directed graph to a JSON file, it's giving me an error: TypeError: Object of type 'Graph' is not JSON serializable The graph is represented as an object, my code looks like this: g = {"a": ["d"], "b": ["c"], "c": ["b", "c", "d", "e"], "d": ["a", "c"], "e": ["c"], "f": [] } graph = Graph(g) with open('graph.json', 'w') as output_file: json.dump(graph, output_file) How can i fix it?
has title: Writing JSON representation of a graph
has answer: http://stackoverflow.com/a/51009035
upvote count: 1
answer count: 1
favorite count: 0
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1

http://stackoverflow.com/q/50896188
type: AnsweredQuestion
tagged with: pubmed
type: Question
has title: neo4j CYPHER - Dynamically run a FOREACH during JSON import depending on whether JSON element has a certain property
score: 0
has body: To import XML data into a neo4j DB I first parse the XML to a python dictionary and then use CYPHER queries like this: (The pmid has a UNIQUE CONSTRAINT) WITH $pubmed_dict as pubmed_article UNWIND pubmed_article as particle MERGE (p:Publication {pmid: particle.MedlineCitation.PMID.text}) ON CREATE SET p.title = COALESCE (particle.MedlineCitation.Article.Journal.Title, particle.MedlineCitation.Article.ArticleTitle) ON MATCH SET p.title = COALESCE (particle.MedlineCitation.Article.Journal.Title, particle.MedlineCitation.Article.ArticleTitle) FOREACH (author IN particle.MedlineCitation.Article.AuthorList.Author | MERGE (a:Author {last_name: COALESCE(author.LastName, 'LAST NAME MISSING!'), first_name: COALESCE(author.ForeName, 'FIRST NAME MISSING!')}) MERGE (p)&lt;-[:WROTE]-(a) ) FOREACH (ref IN particle.MedlineCitation.CommentsCorrectionsList.CommentsCorrections | MERGE (cited_p:Publication {pmid: COALESCE (ref.PMID.text, 'NO-PMID')}) MERGE (cited_p)&lt;-[:REFERENCES]-(p) ) My particle has the following dictionary structure: What I want to achieve in the second FOREACH loop is: IF there is a particle.MedlineCitation.CommentsCorrectionsList.CommentsCorrections list AND IF it has a map with PMID.text, I want that nothing happens if a publication with the given PMID already exists and I want otherwise that new nodes are created with the given PMID. In both cases I want that the node gets a relationship REFERENCES from the initially created p:Publication at the start of the query. I have not found the syntax for such a case yet and the only workaround so far using the function COALESCE (ref.PMID.text, 'NO-PMID')}) always creates new :REFERENCES relationships to nodes which have a CommentsCorrectionsList without a PMID. Who has a better solution?
answer count: 1
tagged with: neo4j
tagged with: py2neo
tagged with: cypher
tagged with: python
has answer: http://stackoverflow.com/a/50941924
accepted answer: http://stackoverflow.com/a/50941924

http://stackoverflow.com/q/50922875
tagged with: text
has comment: http://stackoverflow.com/comment/88847140
has comment: http://stackoverflow.com/comment/88845316
has comment: http://stackoverflow.com/comment/88846713
score: 1
has comment: http://stackoverflow.com/comment/88847875
has comment: http://stackoverflow.com/comment/88847536
type: Question
downvote count: 0
has title: Using text from clipboard. Python 3
upvote count: 1
has comment: http://stackoverflow.com/comment/88847811
has comment: http://stackoverflow.com/comment/88846634
favorite count: 0
answer count: 0
tagged with: clipboard
type: UnansweredQuestion
tagged with: python
has body: I'm writing a small program in python that copies text from a CAD-program and then creates a XML-file based on the text. I've encountered a problem. Neither tkinter's root.clipboard_get() nor pyperclips.paste() give the same (correct) result as pasting manually with Ctrl+V into notepad. Some lines of text is missing for whatever strange reason. I can't seem to find a way around this and to me it looks like my best option (although very stupid) is to write something that: Copy text from CAD-program Create new .txt file and paste from clipboard Copy text from .txt file Delete .txt file Use the copied text from step 3 in the program So far I've got: import pyautogui pyautogui.hotkey('alt', 'tab') pyautogui.hotkey('ctrl', 'c') clip = root.clipboard_get() f = open('cliptext.txt', 'w') pyautogui.hotkey('ctrl', 'v') pyautogui.hotkey('ctrl', 'a') pyautogui.hotkey('ctrl', 'c') f.close() clip2 = root.clipboard_get() I'm still new to python and very lost so all help is highly appreciated!

http://stackoverflow.com/comment/88969523
type: QuestionComment
score: 1
has text: check https://en.wikipedia.org/wiki/Sed
comment on: http://stackoverflow.com/q/50987378
type: Comment

http://stackoverflow.com/comment/88910948
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50956724
has text: For debugging this yourself, it would really help to either run in a debugger, or print things out (like `print(colordict[key][0], colordict[key][1])` so you can see what you're asking Python to do for you instead of just guessing at it. If you do this, you'll see that `colordict[key]` is a string, like `"Red"`, so `colordict[key][0]` is a single character, like `"R"`, and `colordict[key][1]` is the next character, like `"e"`. You can't compare either of those to an array of floats.

http://stackoverflow.com/q/50882377
has body: How do you convert a numpy.float64 to Python native string type for writing to a file with write()?
tagged with: string
favorite count: 0
has title: How do you convert a numpy.float64 to Python native string type for writing to a file with write()?
upvote count: 2
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/24914735
downvote count: 3
type: Question
tagged with: numpy
score: -1
has comment: http://stackoverflow.com/comment/88771013
has comment: http://stackoverflow.com/comment/88767056
answer count: 2
has answer: http://stackoverflow.com/a/50882408
has answer: http://stackoverflow.com/a/50882844

http://stackoverflow.com/a/51010497
has body: Use the JSON module. Ex: import json data = """[{"leagueId":"37085320-2d31-11e8-802e-c81f66dacb22","leagueName":"Akali's Highwaymen","tier":"BRONZE","queueType":"RANKED_FLEX_SR","rank":"III","playerOrTeamId":"87747329","playerOrTeamName":"REYKKU","leaguePoints":0,"wins":53,"losses":59,"veteran":true,"inactive":false,"freshBlood":false,"hotStreak":false},{"leagueId":"c64de250-0065-11e8-b792-c81f66dd2a8f","leagueName":"Fiora's Horde","tier":"BRONZE","queueType":"RANKED_SOLO_5x5","rank":"IV","playerOrTeamId":"87747329","playerOrTeamName":"REYKKU","leaguePoints":28,"wins":29,"losses":25,"veteran":false,"inactive":false,"freshBlood":false,"hotStreak":false}]""" print(json.loads(data)) Output: [{u'queueType': u'RANKED_FLEX_SR', u'hotStreak': False, u'wins': 53, u'veteran': True, u'losses': 59, u'playerOrTeamId': u'87747329', u'leagueName': u"Akali's Highwaymen", u'playerOrTeamName': u'REYKKU', u'inactive': False, u'rank': u'III', u'freshBlood': False, u'leagueId': u'37085320-2d31-11e8-802e-c81f66dacb22', u'tier': u'BRONZE', u'leaguePoints': 0}, {u'queueType': u'RANKED_SOLO_5x5', u'hotStreak': False, u'wins': 29, u'veteran': False, u'losses': 25, u'playerOrTeamId': u'87747329', u'leagueName': u"Fiora's Horde", u'playerOrTeamName': u'REYKKU', u'inactive': False, u'rank': u'IV', u'freshBlood': False, u'leagueId': u'c64de250-0065-11e8-b792-c81f66dd2a8f', u'tier': u'BRONZE', u'leaguePoints': 28}]
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51010480
has comment: http://stackoverflow.com/comment/89034467
type: Answer
has comment: http://stackoverflow.com/comment/89025177
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/89020056
answers question: http://stackoverflow.com/q/51010480
type: AcceptedAnswer

http://stackoverflow.com/q/51000655
tagged with: server
tagged with: anaconda
score: -2
downvote count: 2
answer count: 1
tagged with: sublimetext3
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51142251
has title: sublime connection to localhost:57734 timed out
tagged with: python
has body: I get this popup error whenever I open my sublimetext3.
upvote count: 0
tagged with: sublime-anaconda
type: Question

http://stackoverflow.com/q/50962255
has comment: http://stackoverflow.com/comment/90029746
answer count: 1
linked to: http://stackoverflow.com/q/467738
favorite count: 0
has answer: http://stackoverflow.com/a/55554244
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88921620
tagged with: rule-engine
tagged with: python
tagged with: business-rules
downvote count: 3
has comment: http://stackoverflow.com/comment/88921239
upvote count: 7
has title: How can i use Drools business rule engine with python application?
type: Question
has body: I Need a scalable business rule engine, i think Drools is good one. How can i use this Drools business rule engine with python application? If Drools is not suitable with python, please suggest a good one for python? Thanks in advance, Jerin John
tagged with: drools
score: 4
has comment: http://stackoverflow.com/comment/124034875
linked to: http://stackoverflow.com/q/53421492
linked to: http://stackoverflow.com/q/1925360

http://stackoverflow.com/comment/88940678
type: QuestionComment
type: Comment
has text: possible duplicate: https://stackoverflow.com/questions/42920363/how-to-expand-one-column-in-pandas-to-many-columns
score: 0
comment on: http://stackoverflow.com/q/50971123

http://stackoverflow.com/comment/88927660
type: AnswerComment
score: 0
has text: Hi Rakesh, I already used this module. This function can't handle formats like %m%d%Y Ex: parser.parse('03232018') and very slow compared to datetime.strptime
type: Comment
comment on: http://stackoverflow.com/a/50964803

http://stackoverflow.com/a/78975517
has body: In addition to @poke's answer, if you use a virtual environment in a particular project, and activate it via &gt; venv\Scripts\activate.bat (or the activate script that best suits your platform), the activation places the local venv\Scripts\ directory at the head of the PATH list, so you can execute &gt; python .... and it will run the correct version of python without having to have one version of python always in the PATH list. (Though virtual environments will work nicely both ways.)
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50896496

http://stackoverflow.com/q/50970859
downvote count: 0
linked to: http://stackoverflow.com/q/27238066
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88938235
score: 19
type: Question
has comment: http://stackoverflow.com/comment/88948791
has comment: http://stackoverflow.com/comment/88948107
tagged with: pandas
linked to: http://stackoverflow.com/q/16626058
has body: Why is merging dataframes in Pandas on an index more efficient (faster) than on a column? import pandas as pd # Dataframes share the ID column df = pd.DataFrame({'ID': [0, 1, 2, 3, 4], 'Job': ['teacher', 'scientist', 'manager', 'teacher', 'nurse']}) df2 = pd.DataFrame({'ID': [2, 3, 4, 5, 6, 7, 8], 'Level': [12, 15, 14, 20, 21, 11, 15], 'Age': [33, 41, 42, 50, 45, 28, 32]}) df = df.set_index('ID') df2 = df2.set_index('ID') This represents about a 3.5 times speed up! (Using Pandas 0.23.0) Reading through the Pandas internals page it says an Index "Populates a dict of label to location in Cython to do O(1) lookups." Does this mean that doing operations with an index is more efficient than with columns? Is it a best practice to always use the index for operations such as merges? I read through the documentation for joining and merging and it doesn't explicitly mention any benefits to using the index.
has comment: http://stackoverflow.com/comment/88948307
tagged with: merge
favorite count: 0
tagged with: python
answer count: 1
upvote count: 19
has comment: http://stackoverflow.com/comment/88938484
tagged with: dataframe
has title: Merging dataframes on an index is more efficient in Pandas
has comment: http://stackoverflow.com/comment/88950978
has answer: http://stackoverflow.com/a/51855634

http://stackoverflow.com/comment/88990311
has text: ur solution worked , thank you so much , hh but Ill still waiting for somebody else maybe to give me this embedded version .
comment on: http://stackoverflow.com/a/50997881
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/50996452
tagged with: python
tagged with: selenium
accepted answer: http://stackoverflow.com/a/51005821
linked to: http://stackoverflow.com/q/1472876
has comment: http://stackoverflow.com/comment/88988912
possible better answer: http://stackoverflow.com/a/51128170
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51128170
tagged with: network-programming
has body: I started messing around with Python networking using selenium on Firefox. Unfortunately, I keep getting "ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine". However, this only happens when running some commands, and it only happens the first time I run them. If execute the command a second time right after that, it works. (See below for a minimal example.) I found this question, but being a networking newbie I'm having a hard time applying the solution to my situation. How do I prevent the connection from shutting down? Any help is greatly appreciated! from selenium import webdriver browser = webdriver.Firefox() browser.get('http://www.google.com/') searchfield = browser.find_element_by_id("lst-ib") # Runs without issues searchfield.get_attribute("value") # Produces WinError 10053 searchfield.get_attribute("value") # Returns '' as it should EDIT: It seems the error only occurs, when I execute the command in the shell, rather than saving and running the whole script. Nonetheless, it's pretty annoying.
has comment: http://stackoverflow.com/comment/88989683
type: Question
has title: Python selenium: WinError 10053 - host is shutting connection down
upvote count: 4
answer count: 2
tagged with: firefox
downvote count: 0
score: 4
has answer: http://stackoverflow.com/a/51005821
linked to: http://stackoverflow.com/q/20437701
favorite count: 0
has comment: http://stackoverflow.com/comment/88988158
tagged with: windows

http://stackoverflow.com/q/50983763
has body: This question is related to the previous question linked here Number of consecutive values above certain cut off and slightly with the answer provided by @kvantour So in my case I have file like this (Sample Input) 0.34 0.3432 0.32 0.35 0.323 0.3623 0.345 0.32 0.31 0.378 0.34 0.35 0.342 First: In my case if 2 or more consecutive values satisfy a given cutoff c =0.33 I called it B. This is given by condition m see here: Number of consecutive values above certain cut off Second: if the c is 0.33 and I want values lower than c it will print out 0.32 and 0.323 but I also want to print out 0.35 because that is just one occurrence of above the c which doesn't follow my rule as mentioned in m hence it will also be printed out. This was answered by @kvantour . I called this F So in my $2 the states look like this BCBCB So I can count number of broken (B) events like following (Sample Output) 2 #this corresponds to no. of frames in first B 2 #this corresponds to no. of frames in second B 4 #this corresponds to no. of frames in third B Is there a way to count and print out no. of broken events as a list?
answer count: 2
tagged with: awk
downvote count: 0
has answer: http://stackoverflow.com/a/50990361
has title: Count number of concurring events
has comment: http://stackoverflow.com/comment/88962670
tagged with: bash
upvote count: 1
possible better answer: http://stackoverflow.com/a/50991786
linked to: http://stackoverflow.com/q/50950646
has comment: http://stackoverflow.com/comment/88968791
favorite count: 0
linked to: http://stackoverflow.com/q/50801616
has comment: http://stackoverflow.com/comment/88962612
tagged with: python
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/50991786
accepted answer: http://stackoverflow.com/a/50990361
type: Question
has comment: http://stackoverflow.com/comment/88962514

http://stackoverflow.com/q/50892064
score: 1
type: Question
has title: How to erase image created on PIL/Pillow?
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/50892506
favorite count: 0
has body: I have created an array of monochrome images with: buffer_pages=[Image.new('1',(width,page_height)) for i in range(pages)] and I'm drawing on those images with: whiteboard_pages=[ImageDraw.Draw(page_buffer) for page_buffer in buffer_pages ] I like to reset one of the images from the array, but I can't find a command that will bring all pixels back to 0 or 1. Is there a PIL method that resets all pixels to a certain value? Ideally, I'd like something like: buffer_pages[i].reset_all_pixels(color) whitout using a function that iterates on every pixel an changes it. Speed is quite inportant in my case...
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50892506
type: AnsweredQuestion
tagged with: python-imaging-library

http://stackoverflow.com/comment/88922674
type: Comment
type: QuestionComment
has text: Read more about `safe` templatetag
comment on: http://stackoverflow.com/q/50962903
score: 0

http://stackoverflow.com/a/50947902
type: Answer
score: 13
downvote count: 1
has body: You just have to use the ax parameter fig, (ax1, ax2) = plt.subplots(1,2) sns.heatmap(uniform_data, ax=ax1) sns.heatmap(uniform_data2, ax=ax2) plt.show()
upvote count: 14
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50947776
answers question: http://stackoverflow.com/q/50947776

http://stackoverflow.com/q/50941059
upvote count: 1
tagged with: python
tagged with: excel
type: Question
downvote count: 0
has body: I have a data which consist of wrapped cell content Wrapped data cell My aim is to split the wrapped cell into multiple rows but yet retaining the UID through filling which identify the customer that buy the fruits and vegetables. To achieve something like this. Multi-Row Previously, I have tried using lambda to split the cell contents but it didn't work. Been stuck for quite awhile already would be glad if someone could just give me some guidance on this.
favorite count: 0
tagged with: http://stackoverflow.com/tag/xlsx
tagged with: pandas
has title: Split Multiline/Wrapped Cell Contents Into Separated Rows In Python
tagged with: http://stackoverflow.com/tag/csv
score: 1
has comment: http://stackoverflow.com/comment/88881006
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/88946103
type: AnswerComment
comment on: http://stackoverflow.com/a/50972974
type: Comment
has text: Right but in my post "Note: I cannot reset the server's MsgSeqNum because you can only send that flag after logging in, which I never get the chance to do." the main problem is that you have to log in to be able to send that flag and the server is not letting me even log in before it boots me out of it.
score: 0

http://stackoverflow.com/q/50916377
type: UnansweredQuestion
tagged with: python
has title: How to search text file and return all items that containing the user input string
answer count: 0
has comment: http://stackoverflow.com/comment/88833269
has comment: http://stackoverflow.com/comment/88832918
has body: The text file has on each line the book title, author, publisher, date, and genre, in that order, of all bestselling books in alphabetical order. I want to be able to search this text file by author or title to be able to print all the books with the author ("Name of book by author") that are containing that string the has been entered. def author_search(): author_string = input('Enter a title') lower_author = author_string.lower() with open('file.txt', 'r') as book_file: for line in book_file: if 'lower_title' in line: print(line) def title_search(): title_string = input('Enter a title') lower_title = title_string.lower() with open('file.txt', 'r') as book_file: for line in book_file: if 'lower_title' in line: print(line) I'm not getting any errors but I'm also not getting any output when I run it with my main function def main(): run = True while run: book_file = open('file.txt', 'r') print('What would you like to do? ') print('1: Look up year range') print('2:Look up month/year') print('3:Search for author') print('4:Search for title') print('Q: Quit') userOp = input('Select an operation by entering its number: ') book_file = open('file.txt', 'r') if userOp == 1: print(year_range(book_file)) if userOp == 2: print(month_year(book_file)) elif userOp == 3: print(author_search(book_file)) elif userOp == 4: print(title_search(book_file)) runCheck = input('Do you want to run another operation? ') if runCheck.lower == 'Q': run = False print('Goodbye') It asks me to select and operation and then immediately asks me if I want to run another operation. A Dance With Dragons George R. R. Martin Bantam 7/31/2011 Fiction A Day Late and a Dollar Short Terry McMillan Viking 2/4/2001 Fiction A Feast For Crows George R. R. Martin Bantam 11/27/2005 Fiction A Lion Is In the Streets Adria Locke Langley McGraw 7/1/1945 Fiction A Man In Full Tom Wolfe Farrar, Straus &amp; Giroux 11/22/1998 Fiction
type: Question
has comment: http://stackoverflow.com/comment/88832894
has comment: http://stackoverflow.com/comment/88832759
score: 0
tagged with: string
has comment: http://stackoverflow.com/comment/88833321
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88833226

http://stackoverflow.com/q/50914364
favorite count: 0
has body: I started working with python a couple of weeks ago and thus my knowledge of python is low. I wish to plot a bar plot with some continuous data, but do not want to fill it with any color. I want to see only the final edges like a line histogram. I can not use white color because I will be overlapping different bar plots with errorbar plots in the same canvas. Any clue on how should I change it to a line histogram and set its line color? For x-axis, I have used numpy.array. For y-axis, the height I need is in numpy.histogram form. I am using following method: import matplotlib.pyplot as plt plt.bar(np_array_bins, np_histogram,width=binwidth, label='data', alpha=0.5, edgecolor = 'red', color = 'green', linewidth=0.1) I can't put the real data online but what I have is something like And I want : Neglect the data shown. I am concerned only about the style of the plot. Thanks!
tagged with: python
has answer: http://stackoverflow.com/a/50914770
answer count: 4
score: 2
type: AnsweredQuestion
upvote count: 2
possible better answer: http://stackoverflow.com/a/79509959
has answer: http://stackoverflow.com/a/79509959
type: Question
tagged with: matplotlib
accepted answer: http://stackoverflow.com/a/50914770
has title: Making a bar plot using matplotlib.pyplot
has answer: http://stackoverflow.com/a/79492459
has answer: http://stackoverflow.com/a/79425980
has comment: http://stackoverflow.com/comment/88829571
has comment: http://stackoverflow.com/comment/88829218
downvote count: 0
has comment: http://stackoverflow.com/comment/88829281
has comment: http://stackoverflow.com/comment/88829116

http://stackoverflow.com/q/50884248
has body: If I have the following list of items for a shopping store: shop_list = [{'item': 'apple', 'amount': 10, 'cost': 5}, {'item': 'banana', 'amount': 12, 'cost': 6}, {'item': 'strawberry', 'amount': 8, 'cost': 9}] So I have several dicts within a list. I want to find out how to get the item dict knowing the item. For example: def x(item) #do something to get the dict print dict x('apple') #print {'item': 'apple', 'amount': 10, 'cost': 5} x('banana') #print {'item': 'banana', 'amount': 12, 'cost': 6} What's the shortest, most efficient way to do this?
downvote count: 2
favorite count: 0
type: UnansweredQuestion
has title: Searching dict within a list
tagged with: python
answer count: 4
tagged with: list
has comment: http://stackoverflow.com/comment/88770469
score: 1
tagged with: set
has answer: http://stackoverflow.com/a/50884520
has answer: http://stackoverflow.com/a/50884546
type: Question
has comment: http://stackoverflow.com/comment/88770635
has answer: http://stackoverflow.com/a/50884326
has answer: http://stackoverflow.com/a/51009224
upvote count: 3

binary-tree
tag name: binary-tree
type: Tag
tags question: http://stackoverflow.com/q/50906232

http://stackoverflow.com/comment/88861809
has text: Usually yes, since a class-based view performs some "routing" to these functions. But you can of course patch that routing, and thus let it work differently.
type: QuestionComment
type: Comment
score: 2
comment on: http://stackoverflow.com/q/50931448

http://stackoverflow.com/q/50859936
has title: Python(Flask RESTful API) Modifying Objects
answer count: 1
type: UnansweredQuestion
tagged with: flask-restful
downvote count: 0
score: 1
favorite count: 0
type: Question
tagged with: python
has body: I am having an issue with an object (configuration object) that I want both the python program and external API users to modify. If I use the API and PUT new data, the data is saved. If I have the Python program try modifying the object, I cannot observe that change when doing a GET.As you can see, I change config.encoding to "test", but when doing a GET, I do not observe the change. I still see encoding set to "ASCII". I am relatively new to Python and may be overlooking something simple. Thanks. config = util.Config() class api_Config(Resource): def get(self, id): return [{"id": config.id, "capture": config.capture, "controller": config.controller, "gateway_ip_address": config.gateway_ip_address, "port": config.port, "interval_rate": config.interval_rate, "encoding": config.encoding}], 200 def put(self, id): parser = reqparse.RequestParser() parser.add_argument("capture") parser.add_argument("controller") parser.add_argument("gateway_ip_address") parser.add_argument("port") parser.add_argument("interval_rate") parser.add_argument("encoding") args = parser.parse_args() config.capture = args["capture"] config.controller = args["controller"] config.gateway_ip_address = args["gateway_ip_address"] config.port = args["port"] config.interval_rate = args["interval_rate"] config.encoding = args["encoding"] return [{"id": config.id, "capture": config.capture, "controller": config.controller, "gateway_ip_address": config.gateway_ip_address, "port": config.port, "interval_rate": config.interval_rate, "encoding": config.encoding}], 200 if __name__== "__main__": app = Flask(__name__) api = Api(app) config = util.Config() api.add_resource(api_Config, '/&lt;string:id&gt;') app.run(debug=True) print config.encoding config.encoding = "test"
upvote count: 1
has answer: http://stackoverflow.com/a/50901754

http://stackoverflow.com/comment/88867178
type: Comment
has text: Another option would be to use a descriptor without `__set__` or `__delete__` methods, so you can simply set `self.__dict__['name'] = value` and never invoke the descriptor again on subsequent accesses.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50934292

http://stackoverflow.com/comment/88952453
type: Comment
has text: Link to similar question: https://stackoverflow.com/questions/701802/how-do-i-execute-a-string-containing-python-code-in-python
type: AnswerComment
comment on: http://stackoverflow.com/a/50978272
score: 0

http://stackoverflow.com/comment/125107194
has text: OP is asking which error type is appropriate here.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/56072795
score: 11

http://stackoverflow.com/a/50998465
upvote count: 4
accepted answer of: http://stackoverflow.com/q/50998417
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88991423
type: Answer
answers question: http://stackoverflow.com/q/50998417
has body: Try this: def capitalize_names(input): return list(map(lambda s: s.capitalize(), input)) this is the efficient way of doing this.
downvote count: 1
score: 3

http://stackoverflow.com/comment/89007235
has text: Can you suggest another package that can chunk?
type: Comment
comment on: http://stackoverflow.com/a/51006266
type: AnswerComment
score: 0

http://stackoverflow.com/comment/89010937
has text: i implemented your suggestion and it is working but it is also making a warning : DeprecationWarning: n_iter parameter is deprecated in 0.19 and will be removed in 0.21. Use max_iter and tol instead. ( DeprecationWarning) can you help me how to avoid this warning
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51008914
type: Comment

http://stackoverflow.com/q/50999870
answer count: 0
type: UnansweredQuestion
has body: I'm using a this simple websocket module in my code and I want my server to send the client some data (E.g. current time) every n seconds. my code is as below. import threading import datetime from SimpleWebSocketServer import SimpleWebSocketServer, WebSocket # ============================================================================ class SimpleWS(WebSocket): def __init__(self): super(SimpleWS, self).__init__() threading.Timer(10.0, self.print_date).start() def handleMessage(self): print(self.address, 'sent massage') def handleConnected(self): # threading.Timer(10.0, self.print_date).start() print(self.address, 'connected') def handleClose(self): print(self.address, 'closed') def print_date(self): threading.Timer(10.0, self.print_date).start() print str(datetime.datetime.now()) # ============================================================================ server = SimpleWebSocketServer('', 8080, SimpleWS) server.serveforever() The websocket server doesn't work using the above code. However if I remove the constructor, It works perfectly. So my question is what is wrong with my code?
has comment: http://stackoverflow.com/comment/88993746
tagged with: python
has comment: http://stackoverflow.com/comment/88993763
type: Question
has comment: http://stackoverflow.com/comment/88993759
tagged with: websocket
has comment: http://stackoverflow.com/comment/89008499
score: 0
has title: Python Simple Websocket Server doesn't work when I define the websocket class constructor
tagged with: constructor

http://stackoverflow.com/q/50955189
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88908816
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/9000305
answer count: 4
downvote count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/88908229
type: Question
has title: Returning largest factor of a number is very slow
has comment: http://stackoverflow.com/comment/88908341
score: -1
has answer: http://stackoverflow.com/a/51490269
has comment: http://stackoverflow.com/comment/88908596
has comment: http://stackoverflow.com/comment/88908987
has answer: http://stackoverflow.com/a/50955631
has body: When substituting x in the get_large function with a large integer such as 600851475143 the program stalls and doesn't return a value. But, when substituting x with a smaller integer such as 20 it returns the result. How can I fix this? factors = [] # create new empty list def calc(x): for n in range(1, x): if x % n == 0: factors.append(n) # if x is divisible by n append to factor list return factors def get_large(x): calc(x) # call the returned values in factors list return calc(x)[-1] # return the last factor in the list print("The largest factor is: " + str(get_large(600851475143)))
has answer: http://stackoverflow.com/a/50955657
has answer: http://stackoverflow.com/a/50955480
favorite count: 0

http://stackoverflow.com/comment/88893648
type: Comment
has text: It looks like write_column method only supports string. inside the loop use worksheet.write_column('A2',str(col))
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50947999

http://stackoverflow.com/comment/122476900
type: Comment
has text: @jpp, `decimals` provide 'fast correctly-rounded decimal floating point arithmetic' see https://docs.python.org/3.6/library/decimal.html for a list of its advantages over `float`.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51257246

http://stackoverflow.com/q/50962318
has answer: http://stackoverflow.com/a/50962415
score: -4
has comment: http://stackoverflow.com/comment/88921492
upvote count: 1
type: Question
tagged with: split
downvote count: 5
has comment: http://stackoverflow.com/comment/88921400
has comment: http://stackoverflow.com/comment/88921315
answer count: 1
has body: What's wrong with this piece of code? --ipfile is an ip text file ipfile= open(filename,'rU') for line in ipfile: list_words = line.split() fwrd= list_words[0] I like to check first word and if it is an integer I like to do something else. Why does the fwrd assignment give me index of of range error? EDIT:Added the file opening line. Also note that if I print list_words I can see all the lines from the file printed for e.g: ['45', 'PAN', 'RECTANGULAR', 'STAINLESS,', '350X270X63MM', '172123', '2.00', 'PCS'] ['Details', ':', 'Stainless', 'steel', 'made', 'pan', 'for', 'storing', 'meat,', 'fish,', 'vegetables,', 'etc.', 'prior', 'to', 'cooking.']
favorite count: 0
has comment: http://stackoverflow.com/comment/88922004
has comment: http://stackoverflow.com/comment/88921401
type: UnansweredQuestion
tagged with: python
has title: Index out of Range issue in with python split function

http://stackoverflow.com/comment/88761248
comment on: http://stackoverflow.com/q/50878903
score: 0
type: QuestionComment
type: Comment
has text: Alasdair, i have added all the code affects that problem

http://stackoverflow.com/a/50959499
has comment: http://stackoverflow.com/comment/88916233
answers question: http://stackoverflow.com/q/50959385
type: Answer
has body: Your file structure should look like: directory structure: __init__.py file_a.py file_b.py Oh, sorry for past answer, go ahead and name it __main__.py. You need from . import foo or from . import * when the __init__.py file is present. Then you can import anything from the same folder.
score: 0

http://stackoverflow.com/q/50969928
score: 0
tagged with: optionmenu
accepted answer: http://stackoverflow.com/a/50973040
has comment: http://stackoverflow.com/comment/88937018
has title: Python/Tkinter OptionMenu Update creates a "Shadow" of the Menu
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88936424
type: Question
has comment: http://stackoverflow.com/comment/88936547
has answer: http://stackoverflow.com/a/50973040
tagged with: python
has comment: http://stackoverflow.com/comment/88936836
answer count: 1
has body: So I'm still quite new to this (my code should make this obvious) and I am working on a GUI with tkinter. I am trying to have an OptionMenu which shows Keys from a dict and and upon clicking on a key I would like to see the value. I want to modify that dict and would like to be able to update said OptionMenu. So far, so good. Now I've been able to get this to "work" - but when I update the menu (after changing it or not) I get a shadow of the menu itself. I've conconcted a small test program: import tkinter as tk from tkinter import ttk class MyApp(): def __init__(self,master): self.master = master self.myDict = {'Key1':1, 'Key2': 2, 'Key3':3} self.valueVar = tk.StringVar() self.valueVar.set("0.00") self.RCS = tk.Label(master, textvariable=self.valueVar).grid(row=5, column=3) updateButton = tk.Button(text= "Update List", command = self.update) updateButton.grid(row=4,column=4) changeButton = tk.Button(text= "Change list", command = self.changeDict) changeButton.grid(row=5,column=4) self.keyVar = tk.StringVar(master) self.om = ttk.OptionMenu(self.master, self.keyVar, "Select Key ", *self.myDict, command = self.setKey ) self.om.configure(width=20) self.om.grid(row=4, column=3) def setKey(self,Surface): self.valueVar.set(self.myDict[Surface]) def update(self): menu = self.om["menu"] menu.delete(0,"end") menu.destroy menu = ttk.OptionMenu(self.master, self.keyVar, "Select Key", *self.myDict, command = self.setKey ) menu.grid(row=4, column=3) def changeDict(self): self.myDict = {'Key4':4, 'Key5': 5, 'Key6':6} root = tk.Tk() app = MyApp(root) root.mainloop() What do I have to change? Why? Usually I work with Matlab. I guess it shows. Much appreciated!
tagged with: tkinter

search
tags question: http://stackoverflow.com/q/50976390
tags question: http://stackoverflow.com/q/50933912
tags question: http://stackoverflow.com/q/51007775
tags question: http://stackoverflow.com/q/50870442
tags question: http://stackoverflow.com/q/51002638
type: Tag
tags question: http://stackoverflow.com/q/50948391
tags question: http://stackoverflow.com/q/50958152
tags question: http://stackoverflow.com/q/50947184
tags question: http://stackoverflow.com/q/50975977
tag name: search

http://stackoverflow.com/comment/88875371
type: QuestionComment
has text: You do not have to initiate a session only when the route is called, I recommend moving `Session = sessionmaker(bind=engine)` and `s=Session()` to the very top of the code right below `app = Flask(__name__)`
comment on: http://stackoverflow.com/q/50937058
score: 0
type: Comment

http://stackoverflow.com/comment/88948139
comment on: http://stackoverflow.com/a/50972974
type: Comment
type: AnswerComment
has text: I'm starting to think I'm making a mistake and confusing the method onLogon with the FIX message of "Logon". Do you think this is correct?
score: 0

http://stackoverflow.com/comment/88785295
score: 0
type: Comment
type: QuestionComment
has text: Hi Michael. I've tried that but it opens in steve\my documents.
comment on: http://stackoverflow.com/q/50892257

polynomials
tags question: http://stackoverflow.com/q/50914959
tags question: http://stackoverflow.com/q/50968800
tag name: polynomials
type: Tag

http://stackoverflow.com/comment/88963237
type: QuestionComment
comment on: http://stackoverflow.com/q/50984068
has text: The order is for the list of values in dictionary, no for the key. I need for every key all points order by proximity.
score: 0
type: Comment

http://stackoverflow.com/comment/88766051
score: 0
type: Comment
type: QuestionComment
has text: It is different from the duplicate, once you've clarified rows and columns. If the case is just to add rows then I'm curious about any efforts you've made to solve this problem.
comment on: http://stackoverflow.com/q/50881505

http://stackoverflow.com/a/50881356
has body: A possible workaround: set the range element for both graphs to be proportional to each other then the axes will line up. Basically, your problem is one axis has to show negative numbers and the other doesn't. By telling y2 to show negative numbers we obtain our goal. from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot import plotly.graph_objs as go init_notebook_mode(connected=True) traces = [ go.Bar( x=[1, 2, 3, 4], y=[-1, 2, -3, 4], name='y actual' ), go.Bar( x=[1], y=[0], name='y dummy', hoverinfo='none', showlegend=False ), go.Bar( x=[1], y=[0], yaxis='y2', name='y2 dummy', hoverinfo='none', showlegend=False ), go.Bar( x=[1, 2, 3, 4], y=[22, 2, 13, 25], yaxis='y2', name='y2 actual' ) ] # layout layout = go.Layout( barmode='group', yaxis=dict( title='y actual', rangemode="tozero", #anchor='x', overlaying='y2', side="left", range = [-4, 10] ), yaxis2=dict( title='y2 actual', side='right', rangemode = "tozero", #anchor='x', range = [-12, 30] ) ) # make fig fig = go.Figure(data=traces, layout=layout) iplot(fig) This may be annoying to have to keep them in proportion but it will ensure their alignment. to help automate the process you can use the following function to produce two ranges that are proportional to each other. def make_proportional_intervals(a, b): """ Given two list like objects, compute two proprotionally sized ranges. This function assumes the max value in both lists is positive and non-zero """ min_a, min_b = min(a), min(b) max_a, max_b = max(a), max(b) if (min_a &gt;=0) &amp; (min_b &gt;= 0): # provide a 20% cushion to the scale return [0, round(1.2*max_a)], [0, round(1.2*max_b)] else: if (min_a &lt; min_b) &amp; (max_a &lt; max_b): n = -(-max_b // max_a) # n = math.ceil(max_b / max_a), if you cannot assume ints. return [min_a, max_a], [n*min_a, n*max_a] elif (min_b &lt; min_a) &amp; (max_b &lt; max_a): n = -(-max_a // max_b) # n = math.ceil(max_b / max_a), if you cannot assume ints. return [n*min_b, n*max_b], [min_b, max_…
upvote count: 5
has comment: http://stackoverflow.com/comment/124470739
has comment: http://stackoverflow.com/comment/88858265
type: Answer
has comment: http://stackoverflow.com/comment/88765563
has comment: http://stackoverflow.com/comment/88894073
downvote count: 0
answers question: http://stackoverflow.com/q/50880980
score: 5
has comment: http://stackoverflow.com/comment/88856469

http://stackoverflow.com/a/50971284
has comment: http://stackoverflow.com/comment/88939269
has comment: http://stackoverflow.com/comment/88939391
answers question: http://stackoverflow.com/q/50971091
downvote count: 0
type: Answer
score: 1
upvote count: 1
has body: You may set the ticklabels visible again, e.g. via plt.setp(ax.get_xticklabels(), visible=True) This does not make the axes independent though, they are still bound to each other, but it seems like you are asking about the visibilty, rather than the shared behaviour here.

http://stackoverflow.com/comment/88814572
type: Comment
comment on: http://stackoverflow.com/q/50906708
has text: Is this fine @Christoph-Terasa ? Please help me. I am a novice.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/88855680
has text: Where did you get this compose file? You should not use localhost or 127.0.0.1 to connect one container to the others... Basically, Kafka nor the Registry can reach Zookeeper
comment on: http://stackoverflow.com/q/50923582
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/88943754
type: Comment
comment on: http://stackoverflow.com/q/50973691
type: QuestionComment
has text: show your code .
score: 0

http://stackoverflow.com/comment/88821740
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50906844
has text: Do you need to use non-default ports? If so, why? Even if you can get the python client to work with a non-standard port, this may cause you some other headaches down the road.
score: 0

http://stackoverflow.com/q/50913471
has comment: http://stackoverflow.com/comment/88842009
has comment: http://stackoverflow.com/comment/88841671
has answer: http://stackoverflow.com/a/50921874
has comment: http://stackoverflow.com/comment/88841402
type: Question
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/88841651
has body: I am trying to get Hourly and Daily water level data from website using selenium. my code so far import time from selenium import webdriver from selenium.webdriver.support.ui import Select driver = webdriver.Chrome(r"C:\Python27\chromedriver.exe") driver.get('http://hydrology.gov.np/#/basin/77?_k=1r1onx') time.sleep(5) driver.find_elements_by_xpath("//*[contains(text(), 'Hourly')]").click() But its not working. I am new to selenium. I have also tried other methods to find elements but not succedded. I will appreciate any help in this regard. code from the html div style="padding: 16px 0px; display: table-cell; user-select: none; width: 96px;"> <span tabindex="0" style="border: 10px; box-sizing: border-box; display: block; font-family: Roboto, sans-serif; -webkit-tap-highlight-color: rgba(0, 0, 0, 0); cursor: pointer; text-decoration: none; margin: 0px; padding: 0px; outline: none; font-size: 15px; font-weight: inherit; position: relative; color: rgba(0, 0, 0, 0.87); line-height: 32px; transition: all 450ms cubic-bezier(0.23, 1, 0.32, 1) 0ms; min-height: 32px; white-space: nowrap; background: none;"> Point <span tabindex="0" style="border: 10px; box-sizing: border-box; display: block; font-family: Roboto, sans-serif; -webkit-tap-highlight-color: rgba(0, 0, 0, 0); cursor: pointer; text-decoration: none; margin: 0px; padding: 0px; outline: none; font-size: 15px; font-weight: inherit; position: relative; color: rgb(255, 64, 129); line-height: 32px; transition: all 450ms cubic-bezier(0.23, 1, 0.32, 1) 0ms; min-height: 32px; white-space: nowrap; background: none;"> Hourly <span tabindex="0" style="border: 10px; box-sizing: border-box; display: block; font-family: Roboto, sans-serif; -webkit-tap-highlight-color: rgba(0, 0, 0, 0); cursor: pointer; text-decoration: none; margin: 0px; padding: 0px; outline: none; font-size: 15px; font-weight: inherit; position: relative; color: rgba(0, 0, 0, 0.87); line-height: 32px; transition: all 450ms cubic-bezier(0.23, 1, 0.32, 1) 0ms; m…
has comment: http://stackoverflow.com/comment/88842058
has title: Extracting div tags without any class and id using selenium and python
accepted answer: http://stackoverflow.com/a/50921874
tagged with: python
tagged with: selenium-webdriver
possible better answer: http://stackoverflow.com/a/50913975
has comment: http://stackoverflow.com/comment/88842321
has answer: http://stackoverflow.com/a/50913975
type: AnsweredQuestion

http://stackoverflow.com/comment/88847564
score: 2
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50923923
has text: Are you sure your training set contained all 165 classes? If you did something like train_test_split without stratifying that could have resulted in your training set simply not containing the missing 6 classes (165 - 159).

http://stackoverflow.com/q/50870915
has body: I tried to make below code useable in dask. daily_register_users = df.groupby(['gid','timestamp')['uid'].apply(set).apply(list) daily_register_users = daily_register_users.unstack().T I had tried unstack(), but it haven't implement in dask, and dask.pivot_table() only supports mean ,sum and count. thanks for any help my input is input dataframe expected output is expected
has comment: http://stackoverflow.com/comment/91573749
favorite count: 0
tagged with: dask
type: UnansweredQuestion
tagged with: python
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/88743872
upvote count: 1
type: Question
has title: how to make one index in multindex be columns in dask?
has comment: http://stackoverflow.com/comment/88743666
has comment: http://stackoverflow.com/comment/88743559
tagged with: pandas
downvote count: 0

http://stackoverflow.com/comment/88874026
type: Comment
comment on: http://stackoverflow.com/q/50937822
has text: How is your data stored? Are you using pandas?
score: 0
type: QuestionComment

http://stackoverflow.com/comment/88925865
has text: type hints are really just hints, they are not enforced, you *could* pass anything as parameter, in this case preferrably a list.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50964622

http://stackoverflow.com/a/51008914
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/89010968
answers question: http://stackoverflow.com/q/51008555
has body: So the error is caused by the value corresponding to key 'sgd__n_iter' : np.ceil(10**6/len(train_label)). So you have two options to fix this: Turn it into a list: [np.ceil(10**6/len(train_label))] Add it right away to the constructor of SGDRegressor and do not put it into the param_distributions dictionary. I also noticed some inconsistencies in your code so see below a minimal and slightly cleaner version of your code import numpy as np from sklearn.pipeline import Pipeline from sklearn.linear_model import SGDRegressor from sklearn.model_selection import RandomizedSearchCV, train_test_split from sklearn.preprocessing import StandardScaler from sklearn.datasets import make_regression n_samples = 1000 n_features = 50 X, y = make_regression(n_samples=n_samples, n_features=n_features) X_train, X_test, y_train, y_test = train_test_split(X, y) pipe = Pipeline([('scaler', StandardScaler()), ('sgd', SGDRegressor())]) parameters = {'sgd__loss': ['squared_loss','huber'], 'sgd__n_iter': [np.ceil(10**6 / n_samples)], 'sgd__alpha': 10.0**np.arange(1,7)} g_search = RandomizedSearchCV(pipe, param_distributions=parameters, random_state=2) g_search.fit(X_train, y_train)
accepted answer of: http://stackoverflow.com/q/51008555
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89010937
type: Answer

http://stackoverflow.com/a/58415361
score: 5
type: Answer
has body: The short answer is NO. WxPython uses the native graphic elements of the operating system as well as buttons, windows and others. On the other hand, you can always create your own widgets. In the following example I create my custom wxFrame and I remove the title bar that brings by default using the window styles. Then, by means of sizers, I simulate my own title bar, with its icon, text and buttons. The hard part is to make the window move by dragging it with the mouse but you have thousands of examples on the Internet. I leave you an example: #!/usr/bin/env python # -*- coding: UTF-8 -*- import wx class MyFrame(wx.Frame): def __init__(self, *args, **kwds): kwds["style"] = kwds.get("style", 0) wx.Frame.__init__(self, *args, **kwds) self.SetSize((400, 299)) # Creting the custom title bar self.panelTitleBar = wx.Panel(self, wx.ID_ANY) self.btnMinimize = wx.Button(self.panelTitleBar, wx.ID_ANY, "", style=wx.BORDER_NONE | wx.BU_NOTEXT) self.btnMaximize = wx.Button(self.panelTitleBar, wx.ID_ANY, "", style=wx.BORDER_NONE | wx.BU_NOTEXT) self.btnExit = wx.Button(self.panelTitleBar, wx.ID_ANY, "", style=wx.BORDER_NONE | wx.BU_NOTEXT) self.panelBody = wx.Panel(self, wx.ID_ANY) self.Bind(wx.EVT_BUTTON, self.OnBtnExitClick, self.btnExit) self.Bind(wx.EVT_BUTTON, self.OnBtnMinimizeClick, self.btnMinimize) self.Bind(wx.EVT_BUTTON, self.OnBtnMaximizeClick, self.btnMaximize) self.panelTitleBar.Bind(wx.EVT_LEFT_DOWN, self.OnTitleBarLeftDown) self.panelTitleBar.Bind(wx.EVT_MOTION, self.OnMouseMove) self._isClickedDown = False; self._LastPosition = self.GetPosition(); self.__set_properties() self.__do_layout() def __set_properties(self): self.SetTitle("frame") self.btnMinimize.SetMinSize((22, 22)) self.btnMinimize.SetBitmap(wx.Bitmap("images\\btn_minimize.png", wx.BITMAP_TYPE_ANY)) self.btnMaximize.SetMinSize((22, 22)) self.btnMaximize.SetBitmap(wx.Bitmap("images\\btn_maximize.png", wx.BITMAP_TYPE_ANY)) self.btnExit.SetMinSize((22, 22)) self.btnExit.SetBitmap(wx.Bitmap("images\\btn_…
upvote count: 5
answers question: http://stackoverflow.com/q/51000320
accepted answer of: http://stackoverflow.com/q/51000320
type: AcceptedAnswer
downvote count: 0

reindex
tag name: reindex
tags question: http://stackoverflow.com/q/50969381
type: Tag

http://stackoverflow.com/q/50871088
has comment: http://stackoverflow.com/comment/88743850
tagged with: mysql
has answer: http://stackoverflow.com/a/50871717
answer count: 1
has comment: http://stackoverflow.com/comment/88743916
score: 0
has title: Connect to MySQL running on raspberry pi in my own laptop
tagged with: python
type: UnansweredQuestion
has body: I have been having problems connecting to the database. I have tested the username and password. It works fine and can login to the database. The database has been running. This is the code for python in my own laptop not the virtual machine. import mysql.connector try: connection = mysql.connector.connect( user='myname', password='mypw', host='169.254.X.X', database='GarageParking') print('success') except mysql.connector.Error as e: print("Database not successful") The host is the ip addr of the raspberrypi. I had edited the mysql config file to 0.0.0.0. I just have problems connecting to the database only not the login. The error is 2003: Can't connect to MySQL server on '169.254.X.X:3306' (10061 No connection could be made because the target machine actively refused it) phpMyadmin I appreciate your help.
has comment: http://stackoverflow.com/comment/88743810
has comment: http://stackoverflow.com/comment/88743957
type: Question
tagged with: raspbian
has comment: http://stackoverflow.com/comment/88744651

http://stackoverflow.com/comment/90052540
score: 0
comment on: http://stackoverflow.com/q/50880303
type: QuestionComment
type: Comment
has text: I mean it's not really an answer to my question. It's a workaround, but sure.

http://stackoverflow.com/q/50863045
downvote count: 1
type: Question
has title: How do tell setuptools to get my package from src/mypackage
upvote count: 12
answer count: 1
has answer: http://stackoverflow.com/a/50874613
favorite count: 0
tagged with: setup.py
accepted answer: http://stackoverflow.com/a/50874613
tagged with: python
score: 11
has body: I have a package directory setup like this package_dir |-src | |-mypackage | |-__init__.py | |-setup.py How do I set up setup.py to enable me to import mypackage I've tried: I run python setup.py bdist_wheel where setup.py has options... packages=find_packages(include=["src"]), package_dir={"": "src"}, When I run pip install path/to/mypackage.whl it installs fine But when I do python -c "import mypackage" it fails with ModuleNotFoundError while python -c "import src.mypackage" is fine
type: AnsweredQuestion
tagged with: setuptools

http://stackoverflow.com/a/50931060
type: Answer
answers question: http://stackoverflow.com/q/50930773
has body: You have to simply stub A within the same context as B, and validate against the way it would have been called. Example: &gt;&gt;&gt; class B(): ... def method_b(self): ... A().method_a() ... &gt;&gt;&gt; A = mock.MagicMock() &gt;&gt;&gt; A().method_a.called False &gt;&gt;&gt; b = B() &gt;&gt;&gt; b.method_b() &gt;&gt;&gt; A().method_a.called True &gt;&gt;&gt;
accepted answer of: http://stackoverflow.com/q/50930773
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/88861106
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/50987436
has comment: http://stackoverflow.com/comment/88969451
score: 0
has answer: http://stackoverflow.com/a/50987481
has body: I'm trying to make something that displays some messages depending on the time but I get the following error when I try to call the function. Traceback (most recent call last): File "autodrive.py", line 31, in &lt;module&gt; goodbye() File "autodrive.py", line 19, in goodbye now = datetime.now() AttributeError: 'module' object has no attribute 'now' import datetime import random import re import sys def goodbye(): now = datetime.now() now_time = now.time() bye = ['byee', 'see u', 'see you', 'au revoir'] night = ['goodnight', 'gn', 'bye', 'sleep well', 'bonne nuit'] if now_time &gt;= time(21,30) or now_time &lt;= time(4,00): print random.choice(night) if now_time &gt;= time(4,00) or now_time &lt;= time(21,30): print random.choice(bye) goodbye()
has answer: http://stackoverflow.com/a/50987540
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88969424
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/50987542
upvote count: 1
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/50987506
has title: AttributeError when calling a function

http://stackoverflow.com/comment/88867286
comment on: http://stackoverflow.com/q/50919267
type: Comment
type: QuestionComment
has text: @jakevdp Yes, I completely missed it -- thanks!
score: 0

http://stackoverflow.com/a/50922480
has body: try this, df=pd.read_csv('input.csv',header=None) print df.T.rename(columns={0:'Index',1:'Value'}) print df['Value'] Out: 0 1000 1 2000 2 3000 3 4000 Name: Value, dtype: int64
has comment: http://stackoverflow.com/comment/88844743
type: Answer
has comment: http://stackoverflow.com/comment/88845046
has comment: http://stackoverflow.com/comment/88847292
score: 2
has comment: http://stackoverflow.com/comment/88850194
upvote count: 2
has comment: http://stackoverflow.com/comment/88850352
has comment: http://stackoverflow.com/comment/88850155
accepted answer of: http://stackoverflow.com/q/50922436
has comment: http://stackoverflow.com/comment/88844937
has comment: http://stackoverflow.com/comment/88845363
answers question: http://stackoverflow.com/q/50922436
has comment: http://stackoverflow.com/comment/88850238
has comment: http://stackoverflow.com/comment/88844459
has comment: http://stackoverflow.com/comment/88844834
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/51138090
type: AcceptedAnswer
has body: The warning comes from a call to the pandas library. plotnine still uses a functionality of pandas that has been deprecated and will be removed in a future version. Plotnine is actively developed, and this bug has been fixed already. There was no new release after plotnine 0.3.0 yet, so you will have to install the development version from GitHub or wait for a new release to make the warning go away.
type: Answer
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50974860
answers question: http://stackoverflow.com/q/50974860
upvote count: 2

http://stackoverflow.com/q/50988026
linked to: http://stackoverflow.com/q/45082832
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/88971022
tagged with: pandas
has comment: http://stackoverflow.com/comment/88976027
has comment: http://stackoverflow.com/comment/88972044
upvote count: 6
has title: Python - read parquet file without pandas
has comment: http://stackoverflow.com/comment/88972231
has answer: http://stackoverflow.com/a/62785762
favorite count: 0
has comment: http://stackoverflow.com/comment/88971012
tagged with: parquet
type: UnansweredQuestion
score: 6
tagged with: python
has comment: http://stackoverflow.com/comment/88972102
has body: Currently I'm using the code below on Python 3.5, Windows to read in a parquet file. import pandas as pd parquetfilename = 'File1.parquet' parquetFile = pd.read_parquet(parquetfilename, columns=['column1', 'column2']) However, I'd like to do so without using pandas. How to best do this? I'm using both Python 2.7 and 3.6 on Windows.
has comment: http://stackoverflow.com/comment/97717664
type: Question

database-security
type: Tag
tag name: database-security
tags question: http://stackoverflow.com/q/50896631

http://stackoverflow.com/comment/88868258
score: 1
has text: Yeah, I had the same issue with Fedora, you are gonna have to find an RPM that contains the sasl development libraries. Take a look here https://rpmfind.net/linux/rpm2html/search.php?query=libsasl&submit=Search+...&system=&arch=
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50932009

http://stackoverflow.com/comment/88847153
type: Comment
comment on: http://stackoverflow.com/q/50923929
score: 0
type: QuestionComment
has text: you need to parse the current dates first - there's a parse_dates argument when you read a csv files. Then you can convert to whichever output you want. Alternatively just use a lambda function df.date.apply(lambda x: x[0:4] + "/" + x[4:5])

http://stackoverflow.com/a/50863485
score: 0
has body: I cannot tell here why printing out type(table) returns a Tag object Because tables type is a BS4 tag. As for finding the children, the function you want to use is actually .findChildren(). You just missed capitalizing the 'C'. So what you really need on that last line is: children = table.findChildren() EDIT: As @abarnert pointed out, .findChildren() is technically depricated in beautifulsoup4, however the function still exists. The new way to get the same result would be to use .find_all() without specifying any parameter. Both functions work and return the same results. So it would be best to use children = table.find_all()
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88733535
answers question: http://stackoverflow.com/q/50863315
has comment: http://stackoverflow.com/comment/88733120
type: Answer
accepted answer of: http://stackoverflow.com/q/50863315
has comment: http://stackoverflow.com/comment/88729631
has comment: http://stackoverflow.com/comment/88733361

http://stackoverflow.com/q/50875322
has comment: http://stackoverflow.com/comment/88754871
score: 0
has comment: http://stackoverflow.com/comment/88755478
has comment: http://stackoverflow.com/comment/88823284
has comment: http://stackoverflow.com/comment/88756210
has title: Tensorboard not running, Tensorflow missing attribute train
type: UnansweredQuestion
tagged with: tensorboard
tagged with: python
answer count: 0
tagged with: tensorflow
type: Question
has body: I use Visual Studio, Python 3.6(64-bit) and i have installed tensorflow (3.5, 64-bit), tensorboard (1.9.0) and tflearn (0.3.2) on Windows 10. I have seen a lot of issues resolved on the same subject, but none have been efficient to solve mine. I am training a neuronal network to make edge detection, which is more or less working, but I would like to monitor the training. I make it using tflearn. The line for the training is the following : model = tflearn.DNN(network, tensorboard_verbose=3, checkpoint_path='edge-classifier.tfl.ckpt',tensorboard_dir="logs",) So now I should just get the 'logs' file which is in the same folder than my programm by using the command line (by the way, the file is correctly created in my folder by my programm): tensorboard --logdir=training:F:\Dev\Embryo\Version2\TrainingCellsV2\TrainingCellsV2\logs as I have seen it in many issues resolution on GitHub or else. But it always get me the same answer : [enter image description here][1] File "c:\program files (x86)\microsoft visual studio\shared\python36_64\lib\site-packages\tensorboard\plugins\beholder\beholder.py", line 192, in &lt;module&gt; class BeholderHook(tf.train.SessionRunHook): AttributeError: module 'tensorflow' has no attribute 'train' And in fact even if I just write the line : tensorboard in my windows Shell (opened in administrator mode) I always got the same mistake : AttributeError: module 'tensorflow' has no attribute 'train' But when I check with python I can clearly see that there ain't any problem with the attribute 'train' in tensorflow : &gt;&gt;&gt; import tensorflow as tf &gt;&gt;&gt; tf.train &lt;module 'tensorflow.tools.api.generator.api.train' from 'C:\\Users\\bcerisier\\AppData\\Local\\Continuum\\miniconda3\\lib\\site-packages\\tensorflow\\tools\\api\\generator\\api\\train\\__init__.py'&gt; So I really don't see what to do, please help me, I can't get away with this since two days haha !

http://stackoverflow.com/comment/88943743
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50972596
has text: Fair enough, thanks anyway.

http://stackoverflow.com/comment/88795434
score: 4
has text: you need to add `)` after closing the string `"""`
type: QuestionComment
comment on: http://stackoverflow.com/q/50897891
type: Comment

http://stackoverflow.com/comment/88788894
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50894096
has text: when I print result it shows different order
score: 0

http://stackoverflow.com/comment/88878059
comment on: http://stackoverflow.com/q/50939973
has text: I guess this is a question for Github support since it's their server that returns an error when it shouldn't AFAICS.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88862106
comment on: http://stackoverflow.com/q/50931523
score: 0
type: Comment
type: QuestionComment
has text: I think the linked answer shows you at least the strategy to pursue here. Don't use seaborn but matplotlib and supply the precalculated confidence intervals as levels to the `contour` function. I guess you should comment on why or in how far this would not work for you.

http://stackoverflow.com/q/50889231
tagged with: scipy
type: Question
tagged with: weibull
has title: Python counter part of wblinv in matlab
has body: I am trying to convert a matlab code into python code. What I am stuck into is inverse weibull function part. So, matlab code goes as follows: p = 0.9978 scale_param = 3.5666 shape_param = 0.4936 wblinv(p, scale_param, shape_param) wblinv gives a value corresponding a quantile, p of cdf and the result from above gives 139.9775. I searched and found scipy provides weibull distribution functions. I guess scipy.stats.invweibull.cdf function would do the same operation. but the result is quite different. from scipy import stats p = 0.9978 scale_param = 3.5666 shape_param = 0.4936 stats.invweibull.cdf(p, shape_param, scale=scale_param) it gives abt. 0.153312 Any advice will be helpful.
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50889332
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/50889332

http://stackoverflow.com/q/50879760
tagged with: seaborn
score: 1
type: Question
type: AnsweredQuestion
tagged with: matplotlib
has title: Python Seaborn Boxplot: Overlay 95 percentile values on whisker
linked to: http://stackoverflow.com/q/50554235
upvote count: 1
answer count: 1
favorite count: 0
tagged with: visualization
tagged with: pandas
linked to: http://stackoverflow.com/q/38649501
tagged with: python
has answer: http://stackoverflow.com/a/50882763
accepted answer: http://stackoverflow.com/a/50882763
has body: I want to overlay 95 percentile values on seaborn boxplot. I could not figure out the ways to overlay text or if there is seaborn capability for that. How would I modify following code to overlay the 95 percentile values on plot. import pandas as pd import numpy as np import seaborn as sns df = pd.DataFrame(np.random.randn(200, 4), columns=list('ABCD'))*100 alphabet = list('AB') df['Gr'] = np.random.choice(np.array(alphabet, dtype="|S1"), df.shape[0]) df_long = pd.melt(df, id_vars=['Gr'], value_vars = ['A','B','C','D']) sns.boxplot(x = "variable", y="value", hue = 'Gr', data=df_long, whis = [5,95])
downvote count: 0
has comment: http://stackoverflow.com/comment/88767534

http://stackoverflow.com/q/50923997
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50924025
score: 1
upvote count: 1
has title: Name Error when running a Python Script
has body: My code is class GuessPassword(object): def generate_Parent(self,length): genes= [] while len(genes) &lt; length: sampleSize = min(length - len(genes),len(self.__class__.geneSet)) genes.extend(random.sample(self.__class__.geneSet, sampleSize)) return ''.join(genes) In My main method if __name__ == '__main__': random.seed() bestparent = self.generate_Parent( len(target)) and it's giving the error "NameError: name 'self' is not defined". And when I ran it without "self" it gave the error "NameError: name 'generate_Parent' is not defined". I know it's a small issue. But I searched and couldn't find a solution. Any help would be great.
type: Question
has comment: http://stackoverflow.com/comment/88847263
tagged with: program-entry-point
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/50924025
tagged with: python

http://stackoverflow.com/q/50999833
has title: Set background image in html body using python flask framework
tagged with: http://stackoverflow.com/tag/html
tagged with: python
tagged with: css
score: 2
type: AnsweredQuestion
has body: How to set html body background image my images is inside FlasApp-->static-->in static there are two folders(css and images)--> In .css file used the below code: body { background: url("images/background.jpg"); } In .html file used the below code: &lt;link rel="stylesheet" href="{{ url_for('static', filename='css/main.css') }}"&gt; But neither background color is shown nor background image.
type: Question
has answer: http://stackoverflow.com/a/50999868
accepted answer: http://stackoverflow.com/a/50999868
tagged with: flask
upvote count: 3
answer count: 1
downvote count: 1
favorite count: 0

http://stackoverflow.com/a/50939765
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50939657
has comment: http://stackoverflow.com/comment/88879135
has comment: http://stackoverflow.com/comment/88879434
has comment: http://stackoverflow.com/comment/88879317
has body: A more step-by-step approach First, let's create our new column and be rid of the pesky NaN values In [156]: df['new_column'] = df.X.fillna(0) In [157]: df Out[157]: X Y Z new_column 0 21000 0 0.0 21000 1 NaN 2 2.0 0 2 40000 yy NaN 40000 3 NaN 3 3.0 0 4 49000 yy 4.0 49000 5 80000 yy NaN 80000 Then we can deal with creating the deltas by using a lambda function based on the code you had written. Note that we have to cast the values of the new column to ints for the seconds parameter of timedelta. In [158]: df['new_column'] = df.apply(lambda x: datetime.timedelta(seconds=int(x['new_column'])), axis=1) In [159]: df Out[159]: X Y Z new_column 0 21000 0 0.0 05:50:00 1 NaN 2 2.0 00:00:00 2 40000 yy NaN 11:06:40 3 NaN 3 3.0 00:00:00 4 49000 yy 4.0 13:36:40 5 80000 yy NaN 22:13:20 Using a one-liner Building on what we wrote before, we need to eliminate the NaNs and then convert the entire series firstly to ints and then to timedeltas. In [173]: df['td'] = pd.to_timedelta(pd.to_numeric(df.X.fillna(0)), unit='s') In [174]: df Out[174]: X Y Z new_column td 0 21000 0 0.0 05:50:00 05:50:00 1 NaN 2 2.0 00:00:00 00:00:00 2 40000 yy NaN 11:06:40 11:06:40 3 NaN 3 3.0 00:00:00 00:00:00 4 49000 yy 4.0 13:36:40 13:36:40 5 80000 yy NaN 22:13:20 22:13:20 This approach should be faster as apply is quite slow As per your comment, to be consistent with the NaNs, you can use this df['td'] = df.apply(lambda x: x['td'] if x['X'] is not np.NaN else None, axis=1)
has comment: http://stackoverflow.com/comment/88880349
has comment: http://stackoverflow.com/comment/88880321

http://stackoverflow.com/comment/88744864
type: Comment
has text: How likely is it, that your 400 words change? Building a regular expression with 400 alternatives and a frame of word boundary criteria is surely worth a try, but I would build the pattern dynamically.
score: 0
comment on: http://stackoverflow.com/q/50871201
type: QuestionComment

http://stackoverflow.com/comment/88779736
comment on: http://stackoverflow.com/a/50887126
score: 0
type: AnswerComment
type: Comment
has text: Ohh right! I got blindsided by the fact that it might be an integer and as I was using ceil it was always giving me an integer. Thanks for the help :), it seems like my blunder.

http://stackoverflow.com/comment/88783019
score: 0
type: Comment
has text: What Python version are you using, for 3.6 I'm getting the whole path.
comment on: http://stackoverflow.com/a/50890994
type: AnswerComment

http://stackoverflow.com/comment/88805135
score: 2
has text: If your cost is oscillating then it is probably that your learning rate is still too high. You should switch to a decaying learning rate, but watch out for overfitting.
type: Comment
comment on: http://stackoverflow.com/q/50900148
type: QuestionComment

http://stackoverflow.com/comment/136266569
type: Comment
has text: This workaround works. (seems like [a bug of the extension](https://github.com/formulahendry/vscode-code-runner/issues/1038) actually...
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/53924384

http://stackoverflow.com/comment/88811874
type: Comment
type: QuestionComment
score: 0
has text: @Stev: thanks for clarification. going through the link you suggested, I understand that a split can happen with unequal number of leaf nodes in each resulting node the size of which is basically controlled through min_sample_leaf size. Can you please throw some light on the reasoning behind this? If I understand it correctly it is probably because of decisioning approach of underlying algorithm.
comment on: http://stackoverflow.com/q/50902523

http://stackoverflow.com/comment/88921797
comment on: http://stackoverflow.com/a/50962175
type: AnswerComment
type: Comment
has text: I agree, made a mistake by using write in the answer! Removing that part.
score: 0

http://stackoverflow.com/q/51001660
accepted answer: http://stackoverflow.com/a/51001787
answer count: 4
has answer: http://stackoverflow.com/a/51001853
has body: I have a list containing thousands of sets similar to this: set_list = [a, b, c, d] each set in the list look something like this: a = set([1, 2, 3, 4, 5]) b = set([4, 5, 6, 7, 7, 9]) c = set([1, 2, 6, 8, 10, 12, 45]) d = set([11, 3, 23, 3, 4, 44]) I would like to do the set operation: X-(YUZUAUB......etc) for every set in the list, for example, this would look something like this: after applying this operation on all elements in set_list the new elements look like this: a = a.difference(b.union(c, d)) b = b.difference(c.union(a, d)) c = c.difference(d.union(b, a)) d = d.difference(a.union(c, b)) how do i accomplish this?
tagged with: set
tagged with: loops
possible better answer: http://stackoverflow.com/a/51001853
type: Question
type: AnsweredQuestion
upvote count: 6
has title: set operation on a list of elements
score: 5
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51001954
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51001912
has comment: http://stackoverflow.com/comment/88997101
has comment: http://stackoverflow.com/comment/88997114
tagged with: python
has answer: http://stackoverflow.com/a/51001787

http://stackoverflow.com/comment/88865668
type: QuestionComment
has text: @Barmar Yes, this is another fault. Using `.split()` to answer this question may mean this question is an X - Y question :-)
score: 0
comment on: http://stackoverflow.com/q/50933454
type: Comment

http://stackoverflow.com/q/50907015
has answer: http://stackoverflow.com/a/50907100
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88813910
downvote count: 0
score: 1
tagged with: http://stackoverflow.com/tag/json
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/50907167
tagged with: arrays
has title: How to create a nested array of JSON objects using Python?
has answer: http://stackoverflow.com/a/50907167
upvote count: 1
has comment: http://stackoverflow.com/comment/88813975
favorite count: 0
tagged with: python-3.x
tagged with: python
possible better answer: http://stackoverflow.com/a/50907100
has body: Desired output: {"MainKey": [{"key01":"value01","key02":"value02"}, {"key11":"value11","key22":"value02"} ] } The code I tried: data = {} data2=[{}] data2[0]['key01'] = 'value01' data2[0]['key02']= 'value02' data2[1]['key11'] = 'value11' #index out of bounds error data2[1]['key12']= 'value12' data['MainKey']=data2 import json with open('try.json", 'w') as outfile: json.dump(data,outfile) But this gives index out of bounds error for the second set of values in data2. How do i solve this?

http://stackoverflow.com/q/50929841
tagged with: pandas
possible better answer: http://stackoverflow.com/a/50930060
has body: I have a dataframe with user and session columns, I want to randomly sample the number of sessions so that the dataframe contains N unique sessions per user. The ordering of sessions is important i.e. the 'in' column per session must be preserved. For example if N=2 and I have: x in session_id user_id 0 0.0 1.0 trn-04a23351-283d paul 1 -1.0 2.0 trn-04a23351-283d paul 2 -1.0 3.0 trn-04a23351-283d paul 3 -1.0 4.0 trn-04a23351-283d paul 4 -1.0 1.0 blz-412313we-333 paul 5 -1.0 2.0 blz-412313we-333 paul 6 0.0 3.0 blz-412313we-333 paul 7 -1.0 1.0 wha-111111-fff paul 8 0.0 2.0 wha-111111-fff paul 9 1.0 1.0 bz-0000-01101 chris 10 0.0 2.0 bz-0000-01101 chris 11 -1.0 1.0 1111-sawas-1221 chris 12 -1.0 2.0 1111-sawas-1221 chris 13 1.0 1.0 pppppppppppppppp chris 14 1.0 2.0 pppppppppppppppp chris 15 1.0 3.0 pppppppppppppppp chris 16 -1.0 1.0 55555555555555555 philip 17 -1.0 2.0 55555555555555555 philip 18 -1.0 3.0 55555555555555555 philip 19 -1.0 1.0 333333333333333 philip 20 -1.0 2.0 333333333333333 philip 21 -1.0 3.0 333333333333333 philip 22 0.0 1.0 zz-222222222 philip 23 -1.0 2.0 zz-222222222 philip 24 0.0 1.0 f-32355261-ss3d sarah 25 -1.0 2.0 f-32355261-ss3d sarah 26 0.0 3.0 f-32355261-ss3d sarah 27 0.0 1.0 adasdfs sarah 28 -1.0 2.0 adasdfs sarah 29 0.0 3.0 adasdfs sarah I want: x in session_id user_id 0 0.0 1.0 trn-04a23351-283d paul 1 -1.0 2.0 trn-04a23351-283d paul 2 -1.0 3.0 trn-04a23351-283d paul 3 -1.0 4.0 trn-04a23351-283d paul 4 -1.0 1.0 blz-412313we-333 paul 5 -1.0 2.0 blz-412313we-333 paul 6 0.0 3.0 blz-412313we-333 paul 7 1.0 1.0 bz-0000-01101 chris 8 0.0 2.0 bz-0000-01101 chris 9 1.0 1.0 pppppppppppppppp chris 10 1.0 2.0 pppppppppppppppp chris 11 1.0 3.0 pppppppppppppppp chris 12 -1.0 1.0 333333333333333 philip 13 -1.0 2.0 333333333333333 philip 14 -1.0 3.0 333333333333333 philip 15 0.0 1.0 zz-222222222 philip 16 -1.0 2.0 zz-222222222 philip 17 0.0 1.0 f-32355261-ss3d sarah 18 -1.0 2.0 f-32355261-ss3d sarah 19 0.0 3.0 f-32355261-ss3d sarah 20 0.0 1.0 adasdfs sara…
favorite count: 0
tagged with: python-3.x
has title: Sampling with groups in pandas
has answer: http://stackoverflow.com/a/50930060
has answer: http://stackoverflow.com/a/50930207
accepted answer: http://stackoverflow.com/a/50930207
tagged with: python
score: 2
type: AnsweredQuestion
downvote count: 0
type: Question
upvote count: 2
answer count: 2

http://stackoverflow.com/a/50893647
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50893586
score: 1
answers question: http://stackoverflow.com/q/50893586
upvote count: 1
type: AcceptedAnswer
has body: numpy.gradient takes axis as parameter, so you might just stack the arrays, and then calcualte the gradient along a certain axis; For instance, use np.dstack with axis=2; If you need a different shape as result, just use reshape method: np.gradient(np.dstack((array_1, array_2, array_3)), axis=2) #array([[[ 1. , 0. , -1. ], # [ 1. , 3. , 5. ], # [ 1. , 3. , 5. ]], # [[ 1. , 2.5, 4. ], # [ 1. , 0.5, 0. ], # [ 1. , 0.5, 0. ]]]) Or if flatten the arrays first: np.gradient(np.column_stack((array_1.ravel(), array_2.ravel(), array_3.ravel())), axis=1) #array([[ 1. , 0. , -1. ], # [ 1. , 3. , 5. ], # [ 1. , 3. , 5. ], # [ 1. , 2.5, 4. ], # [ 1. , 0.5, 0. ], # [ 1. , 0.5, 0. ]])
type: Answer

http://stackoverflow.com/q/50966042
has answer: http://stackoverflow.com/a/50966259
type: AnsweredQuestion
score: 1
possible better answer: http://stackoverflow.com/a/50966396
upvote count: 1
type: Question
duplicate of: http://stackoverflow.com/q/27298178
answer count: 2
tagged with: group-by
downvote count: 0
has title: Can't find column names when using group by function in pandas dataframe
tagged with: dataframe
linked to: http://stackoverflow.com/q/27298178
tagged with: pandas-groupby
tagged with: pandas
has answer: http://stackoverflow.com/a/50966396
accepted answer: http://stackoverflow.com/a/50966259
favorite count: 0
has body: I have a pandas dataframe, which looks like this: Country City POI Type 0 NL Amsterdam KFC restaurant 1 NL Amsterdam KFC cafe 2 NL Arnhem McDonalds fast food 3 NL Arnhem McDonalds ice cream I need to group by type column so I do not have duplicates in all other columns. In other words, I need an output like this: Country City POI Type 0 NL Amsterdam KFC restaurant, cafe 1 NL Arnhem McDonalds fast food, ice cream I tried to use group by function, but all column names disappear, and shape function shows 0 columns. Maybe there is a better way to group those values? Here is a sample code: import pandas as pd import numpy as np data = np.array([['','Country','City', 'POI', 'Type'], [0,"NL","Amsterdam", 'KFC', 'cafe'], [1,"NL","Amsterdam", 'KFC', 'restaurant'], [2,"NL","Arnhem", 'McDonalds', 'fast-food'], [3,"NL","Arnhem", 'McDonalds', 'ice cream']] ) initial_df = pd.DataFrame(data=data[1:,1:], index=data[1:,0], columns=data[0,1:]) final_df = initial_df .groupby( [ "Country", "City", "POI", "Type"] ).count() print(list(final_df.columns.values)) print(final_df.shape)
tagged with: python

http://stackoverflow.com/comment/88808202
score: 0
comment on: http://stackoverflow.com/q/50878134
type: Comment
type: QuestionComment
has text: You are all right, check the return value/code est the best practice and it's done in our code but I remove the checks here to reduce the code.

http://stackoverflow.com/q/50997764
has body: If i have a number like: 1234567899 or 1999234567 or 1294597890 or 9234967890 I want to print "Test" whenever a digit appears more than once in the number.
type: Question
has title: Search for same digits in a number variable
has comment: http://stackoverflow.com/comment/88989601
upvote count: 0
linked to: http://stackoverflow.com/q/19694533
score: -1
has answer: http://stackoverflow.com/a/50997776
duplicate of: http://stackoverflow.com/q/19694533
has comment: http://stackoverflow.com/comment/88989589
answer count: 1
favorite count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/50997776
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88989774
downvote count: 1
has comment: http://stackoverflow.com/comment/88989616

feature-extraction
tags question: http://stackoverflow.com/q/50917877
tags question: http://stackoverflow.com/q/50877791
tag name: feature-extraction
tags question: http://stackoverflow.com/q/50942553
tags question: http://stackoverflow.com/q/50856769
type: Tag

http://stackoverflow.com/q/50976432
type: Question
has comment: http://stackoverflow.com/comment/88948942
has body: I am trying to extract a string from a table in word document using win32 and concatenating it using os.join. But I am getting a weird output. Following is my entire code: import win32com.client as win32 import os word = win32.Dispatch("Word.Application") word.Visible = 0 word.Documents.Open("E:\pyauto\sample.doc") doc = word.ActiveDocument table = doc.Tables(11) for i in range(2 , table.Rows.Count): Path=table.Cell(Row = i,Column = 2).Range.Text dir_base="E:"+'\\' base_filename=Path.strip() filename_suffix = '.zip' absPath=os.path.join(dir_base,base_filename+filename_suffix) print absPath Actual Output: .zipolder\file The string mentioned in the document is, folder\file Desired output: E:\folder\file.zip Please help me out with this.
tagged with: win32com
has comment: http://stackoverflow.com/comment/88949007
has comment: http://stackoverflow.com/comment/88949031
score: 0
tagged with: os.path
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/88949609
favorite count: 0
has comment: http://stackoverflow.com/comment/88949407
has comment: http://stackoverflow.com/comment/88949107
has comment: http://stackoverflow.com/comment/88949220
has comment: http://stackoverflow.com/comment/88949612
tagged with: python
has title: extracting string from a table in word document using python win32com
has comment: http://stackoverflow.com/comment/88950715
has comment: http://stackoverflow.com/comment/88948858
has comment: http://stackoverflow.com/comment/88948888
linked to: http://stackoverflow.com/q/50975677
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/50951284
has comment: http://stackoverflow.com/comment/88900339
tagged with: class
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88900373
tagged with: python
score: -2
has title: Python - Unexpected behaviour of class attributes
favorite count: 0
tagged with: python-3.x
type: Question
has comment: http://stackoverflow.com/comment/88901070
answer count: 2
downvote count: 2
has comment: http://stackoverflow.com/comment/88900502
has comment: http://stackoverflow.com/comment/88900420
tagged with: object
tagged with: class-attributes
has comment: http://stackoverflow.com/comment/88900678
has answer: http://stackoverflow.com/a/50951715
has answer: http://stackoverflow.com/a/50955448
has comment: http://stackoverflow.com/comment/88900719
has body: Edited in simple words code: class temp: attr1 = 0 attr2 = [] t1 = temp() t2 = temp() t1.attr1 = 50 t1.attr2.append(50) print(t1.attr1) print(t1.attr2) print(t2.attr1) print(t2.attr2) output: 50 [50] 0 [50] I have called append only on attr2 object t1 but the append changes attr2 of both objects. if attr2 is shared (class attributes) then why does attr1 values are different for t1 and t2. What might have caused this unexpected behaviour ? old question I am writing a python code for blackjack. The code I have written is as follows. from random import randint from IPython.display import clear_output deck = ["S","D","C","H"] class Player: cards = [] total = 0 amount = 0 def __init__(self,money=0): self.amount = money def busted(self): return self.total &gt; 21 def showCards(self): for i in self.cards: print("| {}{} |".format(i%13,deck[i//13]),end = " ") print() def hit(self): no = randint(1,53) self.cards.append(no) if no % 13 == 1: if self.total + 11 &gt; 21: self.total+=1 else: self.total+=11 else: self.total += (no%13 if no%13 &lt;= 10 else 10) dealer = Player(10000) p1 = Player(0) print("Welcome to BlackJack ....") while True: try: p1.amount = int(input("Enter the amount you currrently have for the game")) except: print("invalid Value") continue else: break Game = True while Game: print(dealer.cards) print(p1.cards) dealer.hit() print(dealer.cards) print(p1.cards) print(dealer.total) print(p1.total) Game = False output of this code is as follows Welcome to BlackJack .... Enter the amount you currrently have for the game55 [] [] [45] [45] 6 0 as you can see I had called hit() only once on dealer object but it is appending it to cards attribute of both dealer as well as p1 object. However total attribute is different. Can anyone explain what might have caused this unexpected behaviour ?
upvote count: 0
accepted answer: http://stackoverflow.com/a/50955448
possible better answer: http://stackoverflow.com/a/50951715
has comment: http://stackoverflow.com/comment/88900781

http://stackoverflow.com/comment/88933110
score: 0
has text: You should specify what exactly "didn't work".
type: Comment
comment on: http://stackoverflow.com/q/50968321
type: QuestionComment

http://stackoverflow.com/comment/88918979
score: 0
type: QuestionComment
type: Comment
has text: Ty. I am posted
comment on: http://stackoverflow.com/q/50955736

http://stackoverflow.com/comment/133950710
score: 2
comment on: http://stackoverflow.com/a/63321100
has text: The Anaconda distribution comes with both installed. Relevant link for your answer: [Migrating to Notebook 7](https://jupyter-notebook.readthedocs.io/en/latest/migrate_to_notebook7.html): _it was decided late 2021 to continue developing the Jupyter Notebook application and sunrise it as Notebook 7. Notebook 7 is built on top of JupyterLab components and delivers new features like realtime collaboration, debugger, and theming._.
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/88751747
has text: Try to add `'mail_admins'` into this your handler: `'handlers': ['console'],` in *staging.py* file.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50865739

http://stackoverflow.com/a/50904509
type: Answer
score: 1
has comment: http://stackoverflow.com/comment/88808781
upvote count: 1
answers question: http://stackoverflow.com/q/50904470
has body: pos = 0 result = [] for amount in list_1: result.append(list_2[pos:pos+amount]) pos += amount result # =&gt; [[1], [2, 3], [4, 5]] The key is to track the position using cumulative sum of the amounts.
downvote count: 0
has comment: http://stackoverflow.com/comment/88808801

http://stackoverflow.com/comment/88745085
has text: What have you tried so far?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50871688

http://stackoverflow.com/comment/89089261
type: AnswerComment
has text: Please add how you figured out that `unittest` was the problem. I could fix it now: I called `coverage` directly instead of using `pytest` and let `pytest-cov` call coverage. Thank you!
type: Comment
comment on: http://stackoverflow.com/a/51015167
score: 1

http://stackoverflow.com/comment/126755892
type: AnswerComment
type: Comment
has text: @user2357112supportsMonica Yes, for showing that it's faster it's enough. And we can't *completely* remove the time contribution from the iterable (well, maybe by profiling the C code). And I mostly agree about these overheads mattering less in most practical use cases. Still, I always strive to minimize the benchmark overhead and ideally show just the time for the thing I *want* to measure. If the consumption is half of those 3 µs, then the 17 µs were 91% overhead and just 9% consumption.
comment on: http://stackoverflow.com/a/50938015
score: 0

testing
tags question: http://stackoverflow.com/q/50935019
tags question: http://stackoverflow.com/q/50972170
tags question: http://stackoverflow.com/q/50991551
tag name: testing
tags question: http://stackoverflow.com/q/50972149
tags question: http://stackoverflow.com/q/50862101
tags question: http://stackoverflow.com/q/50934517
tags question: http://stackoverflow.com/q/50944928
tags question: http://stackoverflow.com/q/50870823
tags question: http://stackoverflow.com/q/50904866
tags question: http://stackoverflow.com/q/50877963
type: Tag
tags question: http://stackoverflow.com/q/50858550
tags question: http://stackoverflow.com/q/50881563
tags question: http://stackoverflow.com/q/50857927
tags question: http://stackoverflow.com/q/50965695
tags question: http://stackoverflow.com/q/51009174

http://stackoverflow.com/comment/88722088
type: Comment
type: QuestionComment
has text: its just an example to explain the major problem .
comment on: http://stackoverflow.com/q/50858581
score: 0

http://stackoverflow.com/q/50902318
answer count: 1
has title: Nested if conditions for Tkinter Combobox
score: 0
has comment: http://stackoverflow.com/comment/88804563
has body: I am trying to use this function below for applying a nested condition, which first checks if the file is a text file and then checks the word in that file. If both are yes then the file entry is added into the combobox. But this function is not delivering me anything. Help is needed. def find(): i = 0 keyword = tb4.get("1.0", END).replace('\n', '') if len(tb2.get("1.0", END)) &gt; 2: tid = tb2.get("1.0", END).replace('\n', '').replace("Destination Folder :", '') arr = [x for x in os.listdir(tid) if x.endswith(".txt")] while i &lt; len(arr): x = os.path.join(tid, arr) with open(x) as f: if 'keyword' in f.read(): combo2['values'] = arr f.close() else: pass else: messagebox.showinfo(title="PROCEDURAL ERROR", message="FOLDER is not set. \nSet Destination") Thanks in advance.
has comment: http://stackoverflow.com/comment/88804544
tagged with: python
tagged with: combobox
tagged with: tkinter
type: UnansweredQuestion
type: Question
has answer: http://stackoverflow.com/a/50902400
has comment: http://stackoverflow.com/comment/88804536

http://stackoverflow.com/q/50949545
type: Question
has title: Pandas function to linearise a dataframe
tagged with: dataframe
upvote count: 2
answer count: 2
tagged with: pandas
downvote count: 1
favorite count: 0
possible better answer: http://stackoverflow.com/a/50949703
has body: Often I want to linearise a dataframe. For example, a b 1 l m 2 n o to columns index value a 1 l b 1 m a 2 n b 2 o I use this custom code to linearise a dataframe. import pandas as pd def unstack2df(df,coln='columns',idxn='index',col='value'): if df.columns.name is None: df.columns.name=coln if df.index.name is None: df.index.name=idxn df=df.unstack() df.name=col return pd.DataFrame(df).reset_index() I wonder if there is any in built module in pandas that can do this.
has answer: http://stackoverflow.com/a/50949703
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50949823
accepted answer: http://stackoverflow.com/a/50949823
score: 1

http://stackoverflow.com/q/50954182
type: Question
downvote count: 0
tagged with: six
has title: Python: Cannot uninstall 'six' while pip install tld
answer count: 3
score: 45
upvote count: 45
has answer: http://stackoverflow.com/a/55681774
has answer: http://stackoverflow.com/a/53177770
favorite count: 0
tagged with: tld
type: UnansweredQuestion
has body: $ pip install tld Collecting tld Using cached https://files.pythonhosted.org/packages/fa/78/dbeaeb20db795c42deb81271fd65a35c040ce2e946024eaeef5c6b184176/tld-0.9-py2.py3-none-any.whl Collecting six&gt;=1.9 (from tld) Using cached https://files.pythonhosted.org/packages/67/4b/141a581104b1f6397bfa78ac9d43d8ad29a7ca43ea90a2d863fe3056e86a/six-1.11.0-py2.py3-none-any.whl Installing collected packages: six, tld Found existing installation: six 1.4.1 Cannot uninstall 'six'. It is a distutils installed project and thus we cannot accurately determine which files belong to it which would lead to only a partial uninstall. When installing tld module getting error of cannot uninstall existing 'six' module.
has answer: http://stackoverflow.com/a/50954183
tagged with: python

http://stackoverflow.com/a/51005232
has body: Here's one way using get_dummies + groupby, you get counts for free: res = pd.get_dummies(df'customerID', 'item_tag', columns=['item_tag'])\ .groupby(['customerID'], as_index=False).sum() print(res) customerID item_tag_A item_tag_B item_tag_D item_tag_F 0 23 2 0 0 0 1 55 0 1 1 1 There are a couple of additional steps if you want a binary result and limit to specific tags: L = ['A', 'B', 'D'] df_filtered = df.loc[df['item_tag'].isin(L), ['customerID', 'item_tag']] res = pd.get_dummies(df_filtered, columns=['item_tag'])\ .groupby(['customerID']).any().astype(int).reset_index() res['total_count'] = res.iloc[:, 1:].sum(axis=1) print(res) customerID item_tag_A item_tag_B item_tag_D total_count 0 23 1 0 0 1 1 55 0 1 1 2
upvote count: 2
type: AcceptedAnswer
type: Answer
score: 2
answers question: http://stackoverflow.com/q/51005199
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51005199

http://stackoverflow.com/q/50902252
upvote count: 1
has comment: http://stackoverflow.com/comment/88809667
answer count: 1
tagged with: regex
has answer: http://stackoverflow.com/a/50902375
favorite count: 0
tagged with: python
has title: How to break pandas dataframe break where row contains in python
type: AnsweredQuestion
downvote count: 0
has body: I have a pandas dataframe file.I'm trying to break up a dataframe column contains . column A column B (('', ''), 'abc') 0.043025210084033615 (('', 'abc'), 'abc') 0.65234375 (('abc', 'abc'), 'abc') 0.04259501965923984 (('abc', 'abc'), 'abc') 0.18604651162790697 (('abc', 'abc'), '') 0.41317365269461076 (('abc', ''), '') 0.011148272017837236 (('', ''), 'def') 0.09090909090909091 (('def', 'def'), 'def') 0.008287292817679558 (('def', 'def'), 'def') 0.13506493506493505 (('def', 'def'), '') 0.007653061224489796 (('def', ''), '') 0.08333333333333333 (('', ''), 'ghi') 0.5 (('ghi', 'ghi'), 'ghi') 0.125 (('ghi', 'ghi'), 'ghi') 0.033766233766233764 (('ghi', 'ghi'), '') 0.0694980694980695 (('ghi',''), '') 0.16666666666666666 I need to get output the below way. How can this be implemented in python or Regex? I am new to Python. column A column B (('', ''), 'abc') 0.043025210084033615 (('', 'abc'), 'abc') 0.65234375 (('abc', 'abc'), 'abc') 0.04259501965923984 (('abc', 'abc'), 'abc') 0.18604651162790697 (('abc', 'abc'), '') 0.41317365269461076 (('abc', ''), '') 0.011148272017837236 column A column B (('', ''), 'def') 0.09090909090909091 (('def', 'def'), 'def') 0.008287292817679558 (('def', 'def'), 'def') 0.13506493506493505 (('def', 'def'), '') 0.007653061224489796 (('def', ''), '') 0.08333333333333333 column A column B (('', ''), 'ghi') 0.5 (('ghi', 'ghi'), 'ghi') 0.125 (('ghi', 'ghi'), 'ghi') 0.033766233766233764 (('ghi', 'ghi'), '') 0.0694980694980695 (('ghi',''), '') 0.16666666666666666
score: 1
has comment: http://stackoverflow.com/comment/88809685
type: Question
has comment: http://stackoverflow.com/comment/88804420
accepted answer: http://stackoverflow.com/a/50902375

http://stackoverflow.com/a/50984036
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50983848
type: Answer
has body: From the drfdocs https://www.drfdocs.com/installation/: you can upgrade it by: pip install --upgrade drfdocs

readonly
tag name: readonly
tags question: http://stackoverflow.com/q/50915744
type: Tag

http://stackoverflow.com/a/69719145
downvote count: 0
type: Answer
score: 1
has body: When the file to read is already open, we have a problem, because of the fact that by removing the open line, we will obtain the following error. iterator should return strings, not bytes (did you open the file in text mode?) I had the same error, and, to avoid it, I made(CSVfile is my CSV file which is already open): decoded_file = CSVfile.read().decode('utf-8').splitlines() reader = csv.reader(decoded_file, delimiter=delimitation) Then, with that, I can pass into my CSVfile csv file by the loop: for row in reader:
upvote count: 1
answers question: http://stackoverflow.com/q/50864199
has comment: http://stackoverflow.com/comment/123234682

http://stackoverflow.com/a/65654871
has body: def MultiModeCalc(data): &quot;&quot;&quot; set(data) -&gt; discards duplicated values list(map(lambda x: data.count(x), set(data))))) -&gt; counting how many of each value there are dict(zip(set(data), list(map(lambda x: data.count(x), set(data))))) -&gt; making a dictionary by zipping all unique values(as keys) with their frequency in the data(as values) return [i for i in multimode if multimode[i] == max(multimode.values())] -&gt; returning a list of the values that are most frequent in the data &quot;&quot;&quot; multimode = dict(zip(set(data), list(map(lambda x: data.count(x), set(data))))) return [i for i in multimode if multimode[i] == max(multimode.values())] dataset = [1,2,5,6,3,7,2,3,9,1,10,3,1,2,9,9] print(MultiModeCalc(dataset)) # [1, 2, 3, 9] A DRY answer.
answers question: http://stackoverflow.com/q/50959614
score: 0
has comment: http://stackoverflow.com/comment/116081088
type: Answer

http://stackoverflow.com/comment/88783232
score: 0
type: AnswerComment
has text: @user1245262 don't feel embarrassed, there are still many packages / codebases that haven't updated, requiring use of 2.7. Anyway, you should self-answer and accept it if that ended up working :)
comment on: http://stackoverflow.com/a/50890994
type: Comment

http://stackoverflow.com/comment/88820979
type: Comment
type: QuestionComment
has text: [ERROR] [1529328080.479925]: bad callback: <function callback at 0x7f2bc2d92500> ValueError: Expecting property name: line 1 column 3 (char 2)
comment on: http://stackoverflow.com/q/50909786
score: 0

http://stackoverflow.com/comment/88880038
comment on: http://stackoverflow.com/a/50940987
type: AnswerComment
score: 0
has text: Accepted! Thanks!
type: Comment

http://stackoverflow.com/q/50975017
answer count: 1
tagged with: opencv
has body: At the moment my code takes an image in color and converts it to grayscale. The problem is that it makes the transparent pixels white or black. This is what I have so far: import cv2 img = cv2.imread("watch.png",cv2.IMREAD_GRAYSCALE) cv2.imwrite("gray_watch.png",img) Here is the pic for reference: Watch.png
has answer: http://stackoverflow.com/a/51249331
has title: How can I convert an image to grey scale while keeping transparency using cv2?
type: AnsweredQuestion
tagged with: grayscale
downvote count: 0
has comment: http://stackoverflow.com/comment/88979654
favorite count: 0
tagged with: transparency
type: Question
score: 3
accepted answer: http://stackoverflow.com/a/51249331
tagged with: python
upvote count: 3
tagged with: transparent

http://stackoverflow.com/a/50901147
score: -1
has comment: http://stackoverflow.com/comment/88802364
downvote count: 2
type: Answer
has body: As @figbeam suggested, you can sort and retrieve the first and final value as such: AList = [1,2,3,4] sorted_list = sorted(AList) minValue = sorted_list[0] maxValue = sorted_list[-1] print (minValue) print (maxValue) There are additional ways in case that example doesn't do it for you (such as making a copy of the list, then iterating through and reassigning the min (or max) based on the next entry.
upvote count: 1
has comment: http://stackoverflow.com/comment/88837910
answers question: http://stackoverflow.com/q/50901016

http://stackoverflow.com/comment/88875377
has text: See the updated answer.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50918092

http://stackoverflow.com/comment/99754925
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51008008
has text: @Goyo The intent of my question is to just ask about a shortcut around collecting the data from each artist and then getting the min/max. It's true that the relationship between that data and the plot limits is very nontrivial, so you can't use the plot limits except in special cases, but I guess I figured the plot has to keep track of those numbers somewhere.
score: 0

http://stackoverflow.com/comment/88924356
score: 0
type: Comment
type: QuestionComment
has text: I got that, However, the hour '23:00:00' is not present in your input data. Same goes for '00:00:00'. This means you must have a rule to determine this hour. This rule is not present in your code. Therefore (again) the question: How to know those hours for the other rows?
comment on: http://stackoverflow.com/q/50962722

http://stackoverflow.com/a/50917220
score: 0
type: Answer
has body: As I said in a comment, the problem of overwritting comes from using append on a dataframe the way you did, the data is lost when you reassign result. With the sample you give, you can append chunk_merge into a list at each loop and then use pd.concat. inventory_1 = pd.read_csv("file1.csv") list_to_concat = [] #empty list you will append with chunk_merge for chunk in pd.read_csv("file2.csv",chunksize=2): list_to_concat.append( pd.merge( inventory_1, chunk, on='A', #simple on as both column have the same name how='inner')) # this will help for concat, if you want to keep left, then a dropna is necessary result = pd.concat(list_to_concat) #add .dropna() if left above With your data, I artificially chunked your "large data set" into a df of 2 rows and another one of 1 row to recreate the idea, and at the end, I get: result Out[366]: A B_x C_x B_y C_y 0 1 2 101 2 1000 1 3 4 102 4 2000 0 9 10 103 10 3000 Note that C_x and C_y are exchange (B too but you don't see with your data), as you merge first on inventory_1, but otherwise it's what you want
answers question: http://stackoverflow.com/q/50916860

http://stackoverflow.com/comment/88917367
comment on: http://stackoverflow.com/q/50960220
type: Comment
type: QuestionComment
score: 2
has text: Possible duplicate of [python generator "send" function purpose?](https://stackoverflow.com/q/19302530/2988730)

http://stackoverflow.com/q/50863650
downvote count: 0
tagged with: pandas
score: 3
answer count: 1
favorite count: 0
tagged with: python
has title: Change Bokeh Datasource on input change
has answer: http://stackoverflow.com/a/50864456
type: AnsweredQuestion
upvote count: 3
tagged with: bokeh
accepted answer: http://stackoverflow.com/a/50864456
has body: In my example i have data collected for fruits and vegetables. The data itself has the same key values which are Names and Values. When the user changes the dropdown i would like to swap out the data in the bar graph to show the dropdown list option. How can I do this. I'm a bit lost on how to manage all of this in a custom callback. from bokeh.layouts import column from bokeh.models import CustomJS, ColumnDataSource, Slider, Select from bokeh.plotting import figure, output_file, show from bokeh.models.glyphs import VBar import pandas as pd # create dataframes of data df_fruit = pd.DataFrame({ 'values':[3, 5, 12, 21, 16], 'names':['Apples', 'Pears', 'Nectarines', 'Grapes', 'Strawberries'] }) source_fruit = ColumnDataSource(df_fruit) df_vegetables = pd.DataFrame({ 'values':[3, 4, 4], 'names':['Peppers', 'Potatoes', 'Carrots'] }) source_vegetables = ColumnDataSource(df_vegetables) # plot dataframes names = df_fruit['names'].tolist() plot = figure(plot_width=500, plot_height=400, title="Data Counts", x_range=names) plot.vbar(source=source_fruit, x="names", top="values", bottom=0, width=0.75, color="red", fill_alpha=0.7, name='fruits') # callback for input controls callback = CustomJS(args=dict(source=source_fruit), code=""" var data = source.data; console.log(data); source.change.emit(); """) ui_view = Select(title="View", callback=callback, value="Fruit", options=["Fruit", "Vegetables"]) callback.args['ui_view'] = ui_view # layout layout = column(ui_view, plot) show(layout)
type: Question

http://stackoverflow.com/comment/88972787
comment on: http://stackoverflow.com/q/50988546
type: Comment
has text: you should check the return value you get from `subprocess.call()` and make sure it is 0 if you want to make sure it works as intended.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/88859177
comment on: http://stackoverflow.com/a/50929997
score: 0
type: AnswerComment
has text: Side Note: This seems to work as well `new_dfp['Stock'] = new_dfp.groupby('Product')['Stock'].ffill().astype(int)`
type: Comment

http://stackoverflow.com/comment/88731587
type: QuestionComment
comment on: http://stackoverflow.com/q/50863706
has text: You do not need a regex. `for line in f:` -> `if line.startswith("Chores"):` -> `print(line)` (and perhaps add `break` to stop processing lines). See [**the Python demo**](https://ideone.com/9NkYMm)
score: 0
type: Comment

http://stackoverflow.com/comment/89014645
type: Comment
type: QuestionComment
score: 1
has text: You tagged this question with a lot of tags that are not relevant to your question in its current form.
comment on: http://stackoverflow.com/q/51010644

http://stackoverflow.com/a/50866518
accepted answer of: http://stackoverflow.com/q/50865974
answers question: http://stackoverflow.com/q/50865974
upvote count: 1
type: AcceptedAnswer
type: Answer
has body: The easiest way is to create a separate compose file for your development environment. A good start would be to copy this file and change the appropriate settings (such as DJANGO_SETTINGS_MODULE). By default, docker-compose searches for a file called docker-compose.yml and uses it to bring up the containers; but you can pass in a custom file name with -f. [~]$ docker-compose -f dev.yml up dev.yml is the name of your development settings file. It can be called anything, as long as its proper YAML. It would be good to bookmark the compose file reference from the documentation, as there is a very comprehensive list of directives and options you can add here.
downvote count: 0
score: 1

http://stackoverflow.com/comment/88887336
type: Comment
has text: It doesn't seem to be possible in pure bottle. Maybe you should consider to use nginx as a frontend server which is usually used in production.
comment on: http://stackoverflow.com/q/50944442
score: 0
type: QuestionComment

http://stackoverflow.com/q/50996166
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/59741520
has answer: http://stackoverflow.com/a/50996216
has comment: http://stackoverflow.com/comment/88986931
has title: Create Folders within SubFolders
tagged with: os.walk
type: Question
tagged with: subdirectory
accepted answer: http://stackoverflow.com/a/50996216
score: 0
answer count: 3
tagged with: directory
has body: I am new to python and I am looking for a way to create subfolders within subfolders. My file tree looks like this: &gt;&gt; Main Folder &gt;&gt; Folder a &gt;&gt; Folder 1 &gt;&gt; Folder 2 &gt;&gt; Folder b &gt;&gt; Folder 1 &gt;&gt; Folder 2 I am looking for a way to create a new folder in the bottom most level (folder 1 and folder 2). I've tried using os.walk and os.path, like this for dirpath, subdirs, files in os.walk(current_path): for subdir in subdirs: filePath = os.path.abspath(subdir) newFolder = (filePath + "/new") if not os.path.exists(newFolder): os.mkdir(newFolder) But this only creates the new folder in the second level (Folder a and Folder b), then gives me the error: FileNotFoundError: [Errno 2] No such file or directory: '/Users/diunt-02/Desktop/Brown_Brothers/TEST/new/new' I think that the loop is making new folders, and the os.walk can't find a path to them. Are there any suggestions for getting os.walk to move into the next level down and create a folder there?
has comment: http://stackoverflow.com/comment/88987373
has comment: http://stackoverflow.com/comment/89045752
tagged with: python
possible better answer: http://stackoverflow.com/a/51026829
has answer: http://stackoverflow.com/a/51026829

http://stackoverflow.com/a/50908734
type: Answer
has body: writerow() expects a sequence where each element will fill a column, ie `writer.writerow(["foo", 42, "bar") will result in (quoting and delimiter depending on your writer params): "foo",42,"bar" In your code you create a list c as: c=['Vector1', [[1, 2, 3]]] ie your first element is a string and the second a list of one element which is another list. then iterate over this list to pass each of it's elements to your writer, so basically what you're doing is: writer.writerow("Vector1") writer.writerow([[1, 2, 3]]) For the first line, since strings are sequences, it will fill one column per character resulting in (quoting and delim depending on your writer config) : "V","e","c","t","o","r","1" and for the second, since you pass a list of one element, it will fill one single column with the string representation of the single element in the list: "[1, 2, 3]" If what you want is "Vector1",1,2,3 then the obvious solution is to pass the correct sequence to writerow: writer.writerow(["Vector1", 1, 2, 3]) Now you just have to change your code to correctly produce this sequence...
score: 0
upvote count: 1
downvote count: 1
answers question: http://stackoverflow.com/q/50908443

http://stackoverflow.com/comment/88882059
type: QuestionComment
has text: Can you give me an example? I am quite rookie on this :-(
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50942233

kinect
type: Tag
tags question: http://stackoverflow.com/q/50898940
tag name: kinect

http://stackoverflow.com/a/50929705
has comment: http://stackoverflow.com/comment/88861453
score: 0
has comment: http://stackoverflow.com/comment/88868296
has body: The reason the script was not reporting that videos were outside of the date range was because they were in the download archive. On videos that had not yet been downloaded everything worked as it should.
type: Answer
answers question: http://stackoverflow.com/q/50916170

http://stackoverflow.com/q/50924974
has comment: http://stackoverflow.com/comment/88884795
has title: Converting a greyscale image to a smaller 'pixel by pixel' greyscale image
favorite count: 0
has answer: http://stackoverflow.com/a/51710511
type: UnansweredQuestion
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/88885875
tagged with: opencv
linked to: http://stackoverflow.com/q/23100482
tagged with: python-imaging-library
has body: I've got this image which is massive but 1 square represents a number of pixel values but I want an image that has only 1 pixel with a particular value. The squares are not all the same size. Some of the columns are narrower and some are wider. This is the example which is part of the big image: As you can see the squares on the left hand side is bigger than the one on the right handside. That's the problem! Actual image: For example, using the code below, when I try to convert my image to a smaller pixel by pixel one, I get this, which is completely different to the initial picture. from PIL import Image import numpy as np img = Image.open('greyscale_intense.png').convert('L') # convert image to 8-bit grayscale WIDTH, HEIGHT = img.size a = list(img.getdata()) # convert image data to a list of integers # convert that to 2D list (list of lists of integers) a = np.array ([a[offset:offset+WIDTH] for offset in range(0, WIDTH*HEIGHT, WIDTH)]) print " " print "Intial array from image:" #print as array print " " print a rows_mask = np.insert(np.diff(a[:, 0]).astype(np.bool), 0, True) columns_mask = np.insert(np.diff(a[0]).astype(np.bool), 0, True) b = a[np.ix_(rows_mask, columns_mask)] print " " print "Subarray from Image:" #print as array print " " print b print " " print "Subarray from Image (clearer format):" #print as array print " " for row in b: #print as a table like format print(' '.join('{:3}'.format(value) for value in row)) img = Image.fromarray(b, mode='L') img.show() What I've done in the code is create an array from the initial image and then by ignoring an repeated values, create a subarray that has no repeated values. The new image was constructed using that. For example for this image: The result I get is: As you can see from the array 38 is repeated 9 times while 27 is repeated 8 times... My final aim is to do the same process for a coloured RGB image as shown here. Please help!
has comment: http://stackoverflow.com/comment/88885069
tagged with: image-processing
has comment: http://stackoverflow.com/comment/88887622
has comment: http://stackoverflow.com/comment/88886317
downvote count: 1
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/50947323
has answer: http://stackoverflow.com/a/50932599
has comment: http://stackoverflow.com/comment/88865591
score: 0
answer count: 3

http://stackoverflow.com/q/50930717
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/50932607
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/88863704
tagged with: kivy
has comment: http://stackoverflow.com/comment/88865823
has comment: http://stackoverflow.com/comment/88865330
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/50932607
has title: trouble with scope related variables
type: AnsweredQuestion
has body: Hello fellow programmers, I'm developing a simple interface application in Python that will enable easy and intuitive entry of inventory forms in an access database. I currently have a function as follows: def spawnerror(self, errormsg): self.running = False content = Button(text=errormsg) popup = Popup(title='ERROR!', content=content, auto_dismiss=False) content.bind(on_press=popup.dismiss) popup.open() And I have appropriate error handling done, and the application uses this function as intended. For example, if someone doesn't enter in a required field, it calls this function and spawns an error page with an error and informs the user. My issue that I run into is that, it needs to set the class variable running to False, because at the end of the main function "submit" it checks for that and if self.running == False, then it needs to skip the execution of data entry in the access database. Why is this function not setting the class variable of running to false?

http://stackoverflow.com/q/50950802
tagged with: scrapy
downvote count: 1
type: Question
score: -1
tagged with: web-crawler
upvote count: 0
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: css
linked to: http://stackoverflow.com/q/50957522
has body: I'm trying to create a web crawler (in python, using scrapy) that extracts information from an ad, extract what is on the main page and enter the sub page of the same ad and extract the remaining information, but is giving this error when I run the code. Any suggestion? import scrapy class SapoSpider(scrapy.Spider): name = "imo" start_urls = ['https://www.imovirtual.com/comprar/apartamento/lisboa/'] def parse(self,response): for Property in response.css('div.offer-item-details'): youritem = { 'preco':Property.css('span.offer-item title::text').extract_first(), 'autor':Property.css('li.offer-item-price::text').extract(), 'data':Property.css('li.offer-item-area::text').extract(), 'data_2':Property.css('li.offer-item-price-perm::text').extract() } yield scrapy.Request(subpage_link, callback=self.parse_subpage) # next_page = response.css('li.pager-next a::attr(href)').extract_first() # if next_page is not None: # next_page = response.urljoin(next_page) # yield scrapy.Request(next_page, callback=self.parse) def parse_subpage(self,youritem): for i in response.css('header[class=offer-item-header] a::attr(href)'): youritem = { 'info': i.css('ul.main-list::text').extract(), } yield youritem
has answer: http://stackoverflow.com/a/50951292
has title: ERROR: Spider error processing <GET https://www.imovirtual.com/comprar/apartamento/lisboa/> (referer: None)

http://stackoverflow.com/comment/88785923
has text: `Happy Coding`. @Tico I am not sure but if you have question posted I can try to help.
type: Comment
comment on: http://stackoverflow.com/a/50892566
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88947603
score: 0
comment on: http://stackoverflow.com/a/50963246
type: AnswerComment
type: Comment
has text: Optional Regular Expression Validation is your script

http://stackoverflow.com/q/50882796
has body: how to slice a string in dataframe, start from left, based on different characters, such as ' /- . , I only want the first time this character shows up. key name 1 McDonald's 2 CVS/PHARMACY 3 CVS/Store 4 WAL-MART 5 AMAZON.CO expect result: key name for_Group 1 McDonald's McDonald 2 CVS/PHARMACY CVS 3 CVS/Store CVS 4 WAL-MART WAL 5 AMAZON.CO AMAZON I'm not sure if this need to use regular expression?
upvote count: 2
has title: slice a string by different characters using Python Pandas
answer count: 2
tagged with: pandas
favorite count: 0
accepted answer: http://stackoverflow.com/a/50882836
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/50882847
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50882836
score: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/50882847
type: Question

http://stackoverflow.com/comment/88907042
has text: I've tested the handler but same behaviour . I've already tried a lot of things like test if there is alpha channel (true), getting alpha data of some pixels with diferent values on gradient zone (from 0 to 255), removing the alpha channel (then the whole box becomes red), and converting the alpha into mask with the built-in function... That's why I ask, I've searched about two days and tested a lot of things and I don't know what else to try. I'll give a try with mask again.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50953966
type: Comment

http://stackoverflow.com/comment/88798425
type: Comment
comment on: http://stackoverflow.com/q/50899158
type: QuestionComment
has text: So which is the question here? You told us what you want, but where are you struggling? You dont know which framework to use? You dont know how to use it? You dont know where to start? Depending on which the question is too broad.
score: 1

http://stackoverflow.com/q/50997189
type: Question
has answer: http://stackoverflow.com/a/50999322
possible better answer: http://stackoverflow.com/a/50997741
answer count: 3
upvote count: 1
has answer: http://stackoverflow.com/a/50999699
accepted answer: http://stackoverflow.com/a/50999699
has title: selenium python can't detect id nor name
favorite count: 0
has comment: http://stackoverflow.com/comment/88990579
tagged with: python
has body: I tried to access a website whit selenium but python cant find the id nor the name. Here is the code: from selenium import webdriver from selenium.webdriver.common.keys import Keys browser = webdriver.Firefox(executable_path='D:\code\geckodriver.exe') browser.get('http://admin.chhs.edu.my/schooladmin/jw/login.php') assert "教务系统" in browser.title def login(): elem = browser.find_element_by_name('txtUserName') elem.send_keys('sportday') elem = browser.find_element_by_name('txtPassWord') elem.send_keys('xxxxxx') elem.send_keys(Keys.RETURN) def search(): elem2 = browser.find_element_by_name('txtFind') elem2.send_keys('14066') elem2.send_keys(Keys.RETURN) login() search() And the html of the website I am accessing: &lt;form name="search" method="post" action="http://admin.chhs.edu.my/schooladmin/jw/index.php"&gt; &lt;input name="txtFind" id="txtFind" type="text"&gt; &lt;input name="button" id="button" value="搜寻" type="submit"&gt; &lt;/form&gt; NOTE the password isn't correct due to some privacy problems. BTW this thread have been solved, thank you everyone
has answer: http://stackoverflow.com/a/50997741
has comment: http://stackoverflow.com/comment/88988625
type: AnsweredQuestion
downvote count: 0
score: 1
tagged with: selenium

http://stackoverflow.com/q/50925366
has answer: http://stackoverflow.com/a/50925914
has answer: http://stackoverflow.com/a/50925411
type: AnsweredQuestion
score: 2
accepted answer: http://stackoverflow.com/a/50925411
possible better answer: http://stackoverflow.com/a/50925430
has comment: http://stackoverflow.com/comment/88850039
has answer: http://stackoverflow.com/a/50925628
has answer: http://stackoverflow.com/a/50925430
linked to: http://stackoverflow.com/q/25073064
type: Question
duplicate of: http://stackoverflow.com/q/25073064
has body: Recently I have started learning python programming language and I got stuck while printing 123..n sequence using this: n=10 print(i for i in range(1,n+1)) I got this output: &lt;generator object &lt;genexpr&gt; at 0x7f5990f20db0&gt; Expecting Output: 1234....n (Note: Only continuous output)
answer count: 6
has answer: http://stackoverflow.com/a/50925499
upvote count: 3
has title: Why this line does not printing 123...n in python?
downvote count: 1
tagged with: python
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88850252
has answer: http://stackoverflow.com/a/50925435
has comment: http://stackoverflow.com/comment/88849947
tagged with: generator-expression
has comment: http://stackoverflow.com/comment/88849952

http://stackoverflow.com/q/50879057
tagged with: python-3.x
type: UnansweredQuestion
has title: Extract Data from OpenDAP Dataset for multi dimensional variables
tagged with: opendap
has answer: http://stackoverflow.com/a/50879632
tagged with: netcdf4
linked to: http://stackoverflow.com/q/29476182
linked to: http://stackoverflow.com/q/38917173
type: Question
answer count: 1
score: 0
tagged with: multidimensional-array
has body: I am creating an API that would extract data from an ocean dataset I am using netCDF4 python module to work with this data. There is a multi dimensional variable vozocrtx with input params time_counter, deptht, y, x. As per the documentation if I want to extract data from the dataset for this particular variable I can do import netCDF4 url = 'http://navigator.oceansdata.ca/thredds/dodsC/giops/daily/201806/giops_2018061300_024.nc' dataset = netCDF4.Dataset(url) variable = dataset.variables['vozocrtx'] extracted_data = variable[0:1:1,0:50:1,0:10:1,0:10:1] However, what I want is to have a variable that contains the extraction and slicing indexes, something like data_indexes = 0:1:1,0:50:1,0:10:1,0:10:1 extracted_data = variable[data_indexes] The reason why I want to do is to create a generic function that would extract the data based on the input (start, end, and stride) * no. of dimensions. I tried a few things and also read the document, but couldn't find anything helpful. Any hint or direction would be appreciated.
tagged with: python

http://stackoverflow.com/comment/88863099
has text: In order to select every except for the first column,I did `df.loc[:, df.columns != 'ID'].applymap(lambda x: datetime.strptime('1582/10/15', "%Y/%m/%d") + timedelta(days=x))`
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50931771
type: Comment

http://stackoverflow.com/comment/88797733
score: 0
has text: Have you tried setting the referer before the post? s.headers.update({'referer': logurl})
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50898876

http://stackoverflow.com/a/50866718
score: 7
has comment: http://stackoverflow.com/comment/88739091
accepted answer of: http://stackoverflow.com/q/50866585
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50866585
type: Answer
has body: The premise is false; the in operator can be chained. See Comparisons in the docs: comp_operator ::= "&lt;" | "&gt;" | "==" | "&gt;=" | "&lt;=" | "!=" | "is" ["not"] | ["not"] "in" So, just as with any other chained comparison, a in b in c is equivalent to (a in b) and (b in c) (except that b is only evaluated once. The reason 'a' in arr in arr is false is that arr in arr is false. The only time x in x is true is if x is type that does substring comparisons for __contains__ (like str or bytes), or if it's a container that actually contains itself (like lst = []; lst.append(lst)).
upvote count: 7
has comment: http://stackoverflow.com/comment/88739146

http://stackoverflow.com/comment/88856650
type: AnswerComment
has text: in the example wrong numbers instead should be [2,4] but if I use != instead of == would it mayby work
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50928367

http://stackoverflow.com/q/51009667
has comment: http://stackoverflow.com/comment/89012237
downvote count: 0
has comment: http://stackoverflow.com/comment/89012358
has comment: http://stackoverflow.com/comment/89012657
has answer: http://stackoverflow.com/a/51010122
accepted answer: http://stackoverflow.com/a/51010122
answer count: 1
favorite count: 0
upvote count: 5
has comment: http://stackoverflow.com/comment/89012664
has body: I'm trying to slice loop in django template with variable USUAL WAY {% for article in module.module_article_key.module_article_category.article_category_key.all|slice:":2" %} {{ article.article_title }} {% endfor %} WHAT NEEDS {% for article in module.module_article_key.module_article_category.article_category_key.all|slice:":module.module_article_key.module_article_count" %} {{ article.article_title }} {% endfor %} so we have working variable {{ module.module_article_key.module_article_count }} normaly this variable gives integer value stored for this module, however wen i use it to slice loop - nothing happens
tagged with: django
tagged with: python
type: AnsweredQuestion
tagged with: django-templates
has title: How to pass template variable to slice filter in Django templates
type: Question
score: 5

http://stackoverflow.com/q/50954839
tagged with: concatenation
tagged with: profiling
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
upvote count: 4
has title: Why does concatenation in Python appear to be getting slower?
has comment: http://stackoverflow.com/comment/88907297
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88907496
has body: Why does it appear that concatenation in Python 3 is slower in some cases than in Python 2? The most impacted method of concatenation appears to be successive concatenation of bytes objects, which has gone from an O(n) to O(n²) operation. The bulk of my profiling code is here: #!/usr/bin/env python from operator import concat from sys import version, version_info from timeit import timeit # Compatibility: ver &gt;= 2.6 # ver = version.partition('\n')[0].rstrip() ver = '.'.join(str(v) for v in version_info[:3]) print(ver) if version_info[0] == 2: from StringIO import StringIO else: from io import StringIO from functools import reduce xrange = range def build_plus(): output = '' for _ in xrange(input_len): output += 'a' return output def build_join(): return ''.join('a' for _ in xrange(input_len)) def build_bytes_plus(): output = b'' for _ in xrange(input_len): output += b'a' return output def build_stringio(): output = StringIO() for _ in xrange(input_len): output.write('a') return output.getvalue() def build_reduce(): return reduce(concat, ('a' for _ in xrange(input_len))) builds = {'str+': build_plus, 'join': build_join, 'reduce': build_reduce, 'bytes+': build_bytes_plus, 'StringIO': build_stringio} if version_info[0] == 2: import cStringIO def build_cstringio(): output = cStringIO.StringIO() for _ in xrange(input_len): output.write('a') return output.getvalue() builds['cStringIO'] = build_cstringio else: from io import BytesIO def build_bytesio(): output = BytesIO() for _ in xrange(input_len): output.write(b'a') return output.getvalue() builds['BytesIO'] = build_bytesio resfile = open('times.csv', 'a') size_range = 50 # Number of points over the size axis min_order = 1.0 # 10^x byte input min max_order = 5.0 # 10^x byte input max for allow_gc in (False, True): setup = 'gc.enable()' if allow_gc else 'pass' for build_name, build_fun in builds.items(): # For a roughly constant confidence interval, aim for uniform sample density across the # (logarithmic) input size a…
has comment: http://stackoverflow.com/comment/88907422
type: Question
has answer: http://stackoverflow.com/a/50954921
accepted answer: http://stackoverflow.com/a/50954921
score: 4

http://stackoverflow.com/a/50979171
type: Answer
answers question: http://stackoverflow.com/q/50969641
has body: The edited code is The server: """ Server module for game server """ import tornado.httpserver import tornado.ioloop import tornado.options import tornado.web import tornado.websocket import uuid import json class Controller(object): def __init__(self): self.players = set() self.connections = set() def check(self): return "Hi" def run_somthing(self, text): new_text = "Server: " + text return new_text class InitMessageHandler(tornado.web.RequestHandler): def get(self): print("Client has asked for initial details") user_data = {} user_data['user_id'] = str(uuid.uuid4()) self.write(json.dumps(user_data)) class GameHandler(tornado.websocket.WebSocketHandler): def open(self): # called anytime a new connection with this server is opened print("Client connected") print("Client sent: ", self) if self not in self.application.controller.connections: self.application.controller.connections.add(self) def on_message(self, message): # called anytime a new message is received print("Received from client ,msg=", message) msg = "Server: " + message self.write_message(json.dumps(msg)) def check_origin(self, origin): return True def on_close(self): # called a websocket connection is closed if self in self.application.controller.connections: self.application.controller.connections.remove(self) class Server(tornado.web.Application): def __init__(self): self.controller = Controller() handlers = [ (r"/join", InitMessageHandler), (r"/game", GameHandler) ] tornado.web.Application.__init__(self, handlers) if __name__ == "__main__": tornado.options.parse_command_line() try: application = Server() server = tornado.httpserver.HTTPServer(application) server.listen(8888) tornado.ioloop.IOLoop.instance().start() except KeyboardInterrupt: tornado.ioloop.IOLoop.instance().stop() print("Server closed") The client import tornado.ioloop import tornado.websocket import requests import json import sys import tornado.gen class Client(object): def __init__(self, join_url, play_url): self.wsconn = None self…
score: 0

http://stackoverflow.com/q/50974304
tagged with: python
accepted answer: http://stackoverflow.com/a/50974400
type: AnsweredQuestion
score: 2
has body: Say I make a class named Bird which I only want to be used as a parent class and derived classes are expected to have a method flap_wings: class Bird: def fly(self): self.flap_wings() An expected derived class might look like: class Eagle(Bird): def flap_wings(self): print('flapping wings') What is a nice, clear way for Bird to both assert that its derived classes have the method flap_wings as well as include documentation on what flap_wings is expected to do? Right now, I'm using __init_subclass__: class Bird: def fly(self): self.flap_wings() def __init_subclass__(cls, **kwargs): assert hasattr(cls, 'flap_wings'), ( "Derived classes have to have a flap_wings method which should " "print 'flapping wings'." ) But, the assert expression only shows up after you create a Bird class and is not a "real" docstring that can be accessed through help. I know this is an open ended question but what are other better ways? It's not against the rules to define flap_wings within Bird first, maybe just with the body pass and a docstring. But I just couldn't find the "standard" ways to handle this situation. So I'm looking for any suggestions.
has answer: http://stackoverflow.com/a/50974400
linked to: http://stackoverflow.com/q/4382945
type: Question
downvote count: 0
tagged with: inheritance
tagged with: python-3.6
tagged with: docstring
has comment: http://stackoverflow.com/comment/88945520
upvote count: 2
tagged with: assertions
answer count: 1
favorite count: 0
duplicate of: http://stackoverflow.com/q/4382945
duplicate of: http://stackoverflow.com/q/13646245
has title: Assertion & documentation in a class for methods that are expected in derived classes

http://stackoverflow.com/q/51002266
has comment: http://stackoverflow.com/comment/88998730
tagged with: list
score: -5
upvote count: 3
has answer: http://stackoverflow.com/a/51002329
has title: Turn string into a list and remove carriage returns (Python)
has answer: http://stackoverflow.com/a/51008908
has comment: http://stackoverflow.com/comment/89005832
type: Question
linked to: http://stackoverflow.com/q/16566268
tagged with: split
tagged with: arrays
has comment: http://stackoverflow.com/comment/88998313
answer count: 3
tagged with: string
favorite count: 0
has answer: http://stackoverflow.com/a/51002306
downvote count: 8
type: UnansweredQuestion
has body: I have a string like this: ['过\r\n啤酒\r\n小心\r\n照顾\r\n锻炼\r\n过去\r\n忘记\r\n哭\r\n包\r\n个子\r\n瘦\r\n选择\r\n奶奶\r\n突然\r\n节目\r\n'] How do I remove all of the "\r\n", and then turn the string into a list like so: [过, 啤酒, 小心, 照顾, 过去, etc...]
tagged with: python

http://stackoverflow.com/comment/88872778
type: QuestionComment
has text: k, posting solution soon.
comment on: http://stackoverflow.com/q/50900340
score: 0
type: Comment

http://stackoverflow.com/comment/89013669
has text: What do you mean? The `countplot` does exactly what I thought you were asking.
score: 0
comment on: http://stackoverflow.com/q/51010142
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50930084
has comment: http://stackoverflow.com/comment/88859300
has body: You can pass the format '%b-%y' to to_datetime: In[42]: df = pd.DataFrame({'date':["Feb-15","Dec-46"]}) df['new_date'] = pd.to_datetime(df['date'], format='%b-%y') df Out[42]: date new_date 0 Feb-15 2015-02-01 1 Dec-46 2046-12-01 Note that the new dtype is datetime64, you cannot control the display output, if you insist on DD-MM-YYYY then you would have to convert to a string using dt.strftime: In[43]: df['str_date'] = df['new_date'].dt.strftime('%d-%m-%Y') df Out[43]: date new_date str_date 0 Feb-15 2015-02-01 01-02-2015 1 Dec-46 2046-12-01 01-12-2046 but then you have strings which is not that useful if you need to perform arithmetic operations or filtering EDIT You cannot store dates earlier than 1970 so '01-01-1946' is not a valid datetime that can be represented by datetime64
score: 0
answers question: http://stackoverflow.com/q/50929953
accepted answer of: http://stackoverflow.com/q/50929953
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88859327
type: Answer

http://stackoverflow.com/comment/89029351
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51010644
has text: Well I don't know who downvoted, wasn't me. The question was clear enough to be salvagable if additional information were to be added.
score: 0

http://stackoverflow.com/a/50885960
type: AcceptedAnswer
has body: You can use the resample method with the H argument to group by hour. It is more efficient than using groupby for large sets of time series data. Aggregating with the 'ohlc' argument will then give you the buckets you want for price, while the 'sum' argument will give you the total volume. df.resample('H').agg({'Price': 'ohlc', 'Volume': 'sum'})
answers question: http://stackoverflow.com/q/50885861
accepted answer of: http://stackoverflow.com/q/50885861
type: Answer
score: 0

http://stackoverflow.com/a/50950086
accepted answer of: http://stackoverflow.com/q/50949973
upvote count: 1
type: AcceptedAnswer
downvote count: 0
has body: Do you have python3.4 installed on your machine? If so specify full path. For example: virtualenv -p /usr/local/bin/python3.4 newenv
type: Answer
answers question: http://stackoverflow.com/q/50949973
has comment: http://stackoverflow.com/comment/88899360
score: 1

jenkins
tags question: http://stackoverflow.com/q/50953930
tag name: jenkins
tags question: http://stackoverflow.com/q/50915886
tags question: http://stackoverflow.com/q/50929883
tags question: http://stackoverflow.com/q/50977867
type: Tag

http://stackoverflow.com/comment/88866451
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50922579
has text: I have added an image along with the description of the image.
score: 0

http://stackoverflow.com/a/50871330
has comment: http://stackoverflow.com/comment/88787955
upvote count: 0
has comment: http://stackoverflow.com/comment/88745769
score: -1
has body: finditer returns an iterable of matched objects which is contain all the captured groups and when you print a matched object it returns the first matched group which is contain the whole matched string. If you want the string matched by captured groups you need to use group() method that accepts the number of captured group as its argument. for i in re.finditer(r"ca(p)", text): print(i.group(1)) In other hand, re.findall() returns strings matched by all the captured groups in your regex in a list. It's roughly equivalent to following finditer() code: [i for m in re.finditer(r"ca(p)", text) for i in m.groups()]
downvote count: 1
answers question: http://stackoverflow.com/q/50871254
type: Answer

http://stackoverflow.com/comment/88804421
type: Comment
comment on: http://stackoverflow.com/a/50902142
type: AnswerComment
score: 0
has text: @miradulo Yeah, I use a greasemonkey script for that, and it works fine for Python itself (so I go to `/3/` instead of `/3.5/`), and a few other things, but for some reason it keeps breaking for the readthedocs and scipy results every few months…

http://stackoverflow.com/comment/88913442
has text: Anyway, the most likely problem is that you're using Apple's pre-installed Python 2.7, not your Python 3.6, because you're just typing `python`, or using `#!/usr/bin/env python` in your script, or similar. (Even if the 2.7 `python` comes before the 3.6 `python` in your PATH, `pip` will still pick up the 3.6 version, because Apple's 2.7 doesn't include `pip`.) If so, the solution is to use `python3` instead of `python`.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50957750
score: 1

http://stackoverflow.com/a/50987134
has body: Thanks for all your answers! But this link is really comprehensive. https://nedbatchelder.com/text/names.html This is the same as: m=[1,2,3] i=m[0] #here i refers to m[0], namely 1 i=4 #here i refers to a new value The result is obviously: m=[1,2,3] i=4 For the reason that the int-name can't be changed originally. Once the value of i changed, it refers to another value (object). So the List won't change. Thank you all the same.
has comment: http://stackoverflow.com/comment/88969380
downvote count: 0
answers question: http://stackoverflow.com/q/50986441
has comment: http://stackoverflow.com/comment/88970318
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/q/50906254
has answer: http://stackoverflow.com/a/50906555
type: Question
tagged with: multiprocessing
has title: python multiprocessing pool and logging
linked to: http://stackoverflow.com/q/641420
score: 0
has body: My application uses multiprocessing.pool to parallelize the calculations. Now I would like to add logging feature. The code (unfortunately) needs to run on Windows. I found one related post on stackoverflow, but it not working. I suppose the package multiprocessing_logging doesn't support pools. Here is my code: from multiprocessing_logging import install_mp_handler def main(): # main function filename = "XXX" + datetime.datetime.now().strftime('%Y-%m-%d-%H.%M.%S') + ".log" log_file = os.path.abspath(os.path.join('logs',filename)) multiprocessing.freeze_support() # support multiprocessing logging.basicConfig(filename=log_file, filemode='a', format='%(asctime)s:%(msecs)d (%(processName)s) %(levelname)s %(name)s \t %(message)s', datefmt='%H:%M:%S', level=logging.DEBUG) logger.info("Start application") def run(): # main exection logger.info("Generate outputs for every metrics") num_cores = multiprocessing.cpu_count() logger.info("Output Generation execute on " + str(num_cores) + " cores" ) pool = Pool(num_cores, initializer=install_mp_handler ) processed_metrics = pool.map(_generate_outputs, metrics_list) pool.close() pool.join() map(_create_report,processed_metrics) The implementation of helper function _generate_outputs and _create_report are irrelevant to the problem. When I execute the code the logs generated by the modules from the main process are correctly stored, but not from the child processes. [EDIT] I changed my code according to the comments. Now, my code looks like this: num_cores = multiprocessing.cpu_count() logger.info("Output Generation execute on " + str(num_cores) + " cores" ) install_mp_handler() pool = Pool(num_cores, initializer=install_mp_handler ) processed_metrics = pool.map(_generate_outputs, metrics_list) pool.close() pool.join() map(_create_report,processed_metrics) But still, logs from child processes are not captured. After program termination I see an error: Traceback (most recent call last): File "C:\Python27\lib\site-packages\multiproc…
answer count: 1
tagged with: python
type: UnansweredQuestion
tagged with: logging

http://stackoverflow.com/q/50916071
has answer: http://stackoverflow.com/a/50916176
has comment: http://stackoverflow.com/comment/88832207
has body: I am using the InstagramAPI module from this github to create a script that posts pictures at certain time. A snippet below shows part of the code: Insta = InstagramAPI(account_name, password) Insta.login() InstagramAPI.uploadPhoto(post_path, caption) InstagramAPI.logout() This works fine, unless the picture is in the wrong format. If it is in the wrong format, nothing is posted and this is printed: Request return 400 error! {u'status': u'fail', u'message': u"Uploaded image isn't in the right format"} I have a function that will re-size if it isn't in the correct format. However, it is just print and not an error. Therefor, I can not put this in a try/except. So if the file isn't in the right format, it just skips and posts nothing. Does anyone know of a way I could have my code save the print output to a variable so I can check if it contains "Uploaded image isn't in the right format" and raise an error if so?
type: AnsweredQuestion
favorite count: 0
has comment: http://stackoverflow.com/comment/88864665
tagged with: python-2.7
type: Question
accepted answer: http://stackoverflow.com/a/50916176
tagged with: python
has comment: http://stackoverflow.com/comment/88832169
score: 0
has comment: http://stackoverflow.com/comment/88832254
upvote count: 1
downvote count: 1
answer count: 1
has title: Python: raising error for print output of function
has comment: http://stackoverflow.com/comment/88864586

http://stackoverflow.com/comment/88912395
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50955987
has text: @BryanOakley: I don't disagree; I was being pedantic.
score: 0

geoalchemy2
tag name: geoalchemy2
type: Tag
tags question: http://stackoverflow.com/q/50913589

http://stackoverflow.com/q/50972668
has answer: http://stackoverflow.com/a/50973100
has body: I'm exploring tkinter as of now and trying to do sample exercises I can think of. What I want is when I enter an input like this: I've entered this I want to display them that way as well but I'm only getting this: I'veenteredthis This is a snippet from my code for this part: input = textBox.get("1.0", 'end-1c') logBox.insert(tk.END, input) I've tried doing these: input = input.replace("\n", "\n"), logBox.insert(tk.END, input+ "\n") Please do understand that I'm not well equipped with knowledge in Python as I am still trying to learn the language. Thank you in advance! Edit: Here is the full code just don't mind the other parts since I'm trying to do something import sys import os import time import operator import tkinter as tk from tkinter import * def test(): input = textBox.get("1.0", 'end-1c') # input = input.replace("\n", "\n") logBox.insert(tk.END, input+ "\n") window = tk.Tk() window.geometry("{0}x{1}+0+0".format(window.winfo_screenwidth(), window.winfo_screenheight())) window.title("Test") mainFrame = Frame(window, width=8000, height=8000) mainFrame.pack(side=TOP) LabelText = Label(mainFrame, text="Type your text below:", anchor='center', pady=10) LabelText.pack() textBox = tk.Text (mainFrame, font=('averdana', 10), height=18, width=180) textBox.pack() BTNRun = Button(mainFrame, text="Run", height=1, width=10, command=test) BTNRun.pack(padx=10, pady=10) LogText = Label(mainFrame, text="Console Log", anchor='ne', pady=10) LogText.pack() logBox = tk.Listbox(mainFrame, font=('averdana', 10), height=10, width=180) logBox.pack() BTNExit = Button(mainFrame, text="Exit", height=1, width=10, command=quit) BTNExit.pack() window.mainloop()```
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/88941780
favorite count: 0
has comment: http://stackoverflow.com/comment/88941952
has comment: http://stackoverflow.com/comment/88941977
accepted answer: http://stackoverflow.com/a/50973100
tagged with: python
has title: Python GUI using Tkinter how to print input exactly the way you enter them?
type: AnsweredQuestion
tagged with: tkinter
score: 1
upvote count: 1
type: Question

resnet
tags question: http://stackoverflow.com/q/50901159
tag name: resnet
type: Tag

http://stackoverflow.com/comment/89007281
has text: syntaxerror points at the : after "entities"
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51006844

http://stackoverflow.com/a/50977465
type: Answer
answers question: http://stackoverflow.com/q/50977237
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50977237
has body: Default mode for pandas.merge is 'inner' which will take the intersection of the two lists. So your script work and it will continue if one file had a date entry that the other does not but if you want your result file to have all data then you should use 'outer' mode. More info here : https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html For example with PV.csv like : date,PVkW 2018/03/05 11:00,887.4 2018/03/05 12:00,940.9 2018/03/05 13:00,927.2 2018/03/05 14:00,845.9 2018/03/05 15:00,683.0 2018/03/05 16:00,423.1 2018/03/05 17:00,186.4 2018/03/05 18:00,186.4 TBL.csv like : date,TBLkW 2018/03/05 11:00,277.01953 2018/03/05 12:00,285.30783 2018/03/05 13:00,236.8461 2018/03/05 14:00,243.26564 2018/03/05 15:00,274.98438 2018/03/05 16:00,255.20079 2018/03/05 17:00,262.28046 And this script : import pandas as pd a = pd.read_csv('PV.csv') b = pd.read_csv('TBL.csv') b = b.dropna(axis=1) merged = a.merge(b, how='outer', on='date') merged.to_csv("combined.csv", index=False) You get : date,PVkW,TBLkW 2018/03/05 11:00,887.4,277.01953 2018/03/05 12:00,940.9,285.30782999999997 2018/03/05 13:00,927.2,236.8461 2018/03/05 14:00,845.9,243.26564 2018/03/05 15:00,683.0,274.98438 2018/03/05 16:00,423.1,255.20078999999998 2018/03/05 17:00,186.4,262.28046 2018/03/05 18:00,186.4,

http://stackoverflow.com/a/51013413
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51010852
has body: I believe you are looking for index of node nnn in the adjacency matrix ? If that is the case then you can simply look up the index of nnn in the list created by G.nodes(). The function documentation of the function adjacency_matrix(G, nodelist,weight) specifies how the order of nodes is taken for adjacency matrix nodelist : list, optional The rows and columns are ordered according to the nodes in nodelist. If nodelist is None, then the ordering is produced by G.nodes(). So I think the following code should work for you nodes_list = list(G.nodes()) nodes_list.index(nnn)
type: Answer
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/51010852

http://stackoverflow.com/q/50904810
has comment: http://stackoverflow.com/comment/88840555
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50942299
type: Question
has comment: http://stackoverflow.com/comment/88810056
tagged with: cartopy
has comment: http://stackoverflow.com/comment/88811210
has comment: http://stackoverflow.com/comment/88810247
score: 0
has title: Import cartopy.io.img_tiles in Python 3.6
answer count: 1
accepted answer: http://stackoverflow.com/a/50942299
has comment: http://stackoverflow.com/comment/88810542
linked to: http://stackoverflow.com/q/19943022
has body: I would like to import the module cartopy.io.img_tiles using: import cartopy.io.img_tiles as cimgt I have Cartopy 0.16.0 installed via Anaconda on Python 3.6. However, the string above yields: File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 705, in runfile execfile(filename, namespace) File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "C:/Users/Me/Test.py", line 18, in import cartopy.io.img_tiles as cimgt File "C:\ProgramData\Anaconda3\lib\site-packages\cartopy\io\img_tiles.py", line 32, in from PIL import Image File "C:\ProgramData\Anaconda3\lib\site-packages\PIL\Image.py", line 58, in from . import _imaging as core ImportError: DLL load failed: The specified module could not be found. I cannot figure out how to get the package to work. Cartopy is updated to its latest version and I cannot find out how to import the module or install it (using pip). I've tried multiple solutions, such as this and this. I'm probably overlooking something, but is there a simple way to get the module to work?
has comment: http://stackoverflow.com/comment/88811554
has comment: http://stackoverflow.com/comment/88810079

http://stackoverflow.com/comment/88788630
comment on: http://stackoverflow.com/q/50894168
score: 0
has text: slightly faster: `result[j] += result[j-1]` don't make it FORTRAN style
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50986575
has comment: http://stackoverflow.com/comment/88970543
has comment: http://stackoverflow.com/comment/88968814
has comment: http://stackoverflow.com/comment/88970209
type: AnsweredQuestion
has title: communicate with mongodb from aws lambda function
has body: I have created a lambda function and executed a program which include numpy by uploading zip file and it executed successfully. but when I connect the mongodb using public ip then it throughing exception as "time out". Please help me . thanks in advance.
type: Question
tagged with: mongodb
score: -2
tagged with: amazon-web-services
downvote count: 4
answer count: 1
has answer: http://stackoverflow.com/a/50988113
tagged with: aws-lambda
favorite count: 0
upvote count: 2
accepted answer: http://stackoverflow.com/a/50988113
tagged with: machine-learning
tagged with: python

http://stackoverflow.com/q/50915911
accepted answer: http://stackoverflow.com/a/50916413
score: 29
possible better answer: http://stackoverflow.com/a/50916087
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/88832648
upvote count: 29
type: AnsweredQuestion
has body: Maybe I misunderstand the purpose of Django's update_or_create Model method. Here is my Model: from django.db import models import datetime from vc.models import Cluster class Vmt(models.Model): added = models.DateField(default=datetime.date.today, blank=True, null=True) creation_time = models.TextField(blank=True, null=True) current_pm_active = models.TextField(blank=True, null=True) current_pm_total = models.TextField(blank=True, null=True) ... more simple fields ... cluster = models.ForeignKey(Cluster, null=True) class Meta: unique_together = (("cluster", "added"),) Here is my test: from django.test import TestCase from .models import * from vc.models import Cluster from django.db import transaction # Create your tests here. class VmtModelTests(TestCase): def test_insert_into_VmtModel(self): count = Vmt.objects.count() self.assertEqual(count, 0) # create a Cluster c = Cluster.objects.create(name='test-cluster') Vmt.objects.create( cluster=c, creation_time='test creaetion time', current_pm_active=5, current_pm_total=5, ... more simple fields ... ) count = Vmt.objects.count() self.assertEqual(count, 1) self.assertEqual('5', c.vmt_set.all()[0].current_pm_active) # let's test that we cannot add that same record again try: with transaction.atomic(): Vmt.objects.create( cluster=c, creation_time='test creaetion time', current_pm_active=5, current_pm_total=5, ... more simple fields ... ) self.fail(msg="Should violated integrity constraint!") except Exception as ex: template = "An exception of type {0} occurred. Arguments:\n{1!r}" message = template.format(type(ex).__name__, ex.args) self.assertEqual("An exception of type IntegrityError occurred.", message[:45]) Vmt.objects.update_or_create( cluster=c, creation_time='test creaetion time', # notice we are updating current_pm_active to 6 current_pm_active=6, current_pm_total=5, ... more simple fields ... ) count = Vmt.objects.count() self.assertEqual(count, 1) On the last update_or_create call I get this error: IntegrityErr…
tagged with: django-models
tagged with: django-tests
type: Question
has answer: http://stackoverflow.com/a/63765442
has answer: http://stackoverflow.com/a/50916413
has comment: http://stackoverflow.com/comment/88831804
downvote count: 0
has title: django update_or_create gets "duplicate key value violates unique constraint "
answer count: 3
has answer: http://stackoverflow.com/a/50916087
favorite count: 0
tagged with: model

http://stackoverflow.com/q/51008885
type: AnsweredQuestion
tagged with: python
has body: I have this link: s3://some_path/200_files/*.gz I have the corresponding ACCESS ID and SECRET KEY. How to copy the complete folder (200_files) OR all the .gz to the local system? Ubuntu CLI or Python based solution. I understand that this is not a up to the mark question, answers in comments would work. Thanks :)
accepted answer: http://stackoverflow.com/a/51008944
score: 0
has title: Copy amazon s3 bucket folder to local
answer count: 1
tagged with: amazon-s3
tagged with: s3-bucket
has answer: http://stackoverflow.com/a/51008944
type: Question

http://stackoverflow.com/a/50920070
answers question: http://stackoverflow.com/q/50919465
score: 3
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50919465
upvote count: 3
has body: The reason your attempt did not work is explained in Delete all objects in a list - when looping over [x, y] you are deleting additional references to the objects (created in the process of iteration), while the original references stay in place. You can delete x and y by accessing them via globals() as follows symbolsToDelete = ('x', 'y') for z0 in symbolsToDelete: del globals()[z0]

http://stackoverflow.com/q/50989913
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88983231
tagged with: python
answer count: 0
type: Question
tagged with: raspbian
tagged with: raspberry-pi
has title: MAX7219 (7-segment display) with Raspberry Zero W doesn´t work
score: 0
has comment: http://stackoverflow.com/comment/88992846
has body: I tried everything I found but the display didn´t work. I connected the display and installed the libraries according to these instructions but still does not work.(https://max7219.readthedocs.io/en/0.2.3/) Do not you know what could still be wrong? I have a LED connected to Raspberry, so if it is not enough to power the display yet, is it possible? Once I hit Raspberry and the display turned on for a moment, then it went out. When I want to upload a python script, it does not respond at all and throws bugs with libraries. Thanks for your help.
tagged with: linux

http://stackoverflow.com/comment/109690537
score: 0
type: Comment
type: QuestionComment
has text: Can you add some sample data, please ?
comment on: http://stackoverflow.com/q/50893052

http://stackoverflow.com/q/50901166
has comment: http://stackoverflow.com/comment/88802193
score: 1
has comment: http://stackoverflow.com/comment/88802175
type: Question
has title: Appending part of a tuple into a new list
has answer: http://stackoverflow.com/a/50901462
accepted answer: http://stackoverflow.com/a/50901462
upvote count: 2
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/88802344
favorite count: 0
tagged with: python-3.x
has body: I created a dictionary and I need to add the value of the single tuple into a new dictionary.I cannot seem to get my keys method to work. I get this error "TypeError: 'int' object is not subscriptable" This is where my key method is located. I get an error in the line that has newlist.append(i[0]). I am trying to append the key part of the tuple into a > new list name newlist def keys(self): newlist = self.flattened() keylist = [] for i in newlist: newlist.append(i[0]) return newlist This is my TestCase for the keys method class test_keys(unittest.TestCase): def test(self): s = Dictionary([[0, "zero"], [1, "one"], [2, "two"], [3, "three"] self.assertEqual(s.keys(), [0, 1, 2, 3])
has comment: http://stackoverflow.com/comment/88802220
tagged with: python
has comment: http://stackoverflow.com/comment/88802742
tagged with: dictionary
type: AnsweredQuestion

http://stackoverflow.com/comment/88787372
score: 1
type: AnswerComment
has text: I'd add a note regarding the fact that the error on the fraction representation is then 1/(2 * max_denominator)
type: Comment
comment on: http://stackoverflow.com/a/50893523

http://stackoverflow.com/a/50863402
answers question: http://stackoverflow.com/q/50863315
score: 0
type: Answer
has body: There is no such method as findchildren, so trying to call it is an error. With most Python code, you’d get a clearer AttributeError saying that findchildren doesn’t exist. But BS4 nodes have that nice shortcut where you can write node.spam instead of node.find('spam'). So it’s calling find('findchildren'), which returns None, and then you try to call that None. As for how to fix it… I’m not sure what you’re trying to call here (usually errors like this, someone has copied and pasted some BS3 code that was already deprecated in 3.0 and doesn’t exist in 4.x, but that’s not the case here). So all I can suggest is that you read the docs to find the method you actually need. There are multiple ways to search, iterate, etc. both immediate children and all descendants, and I assume one of them is what you want.

lstm
tags question: http://stackoverflow.com/q/50856936
tags question: http://stackoverflow.com/q/50936396
tags question: http://stackoverflow.com/q/50903862
tags question: http://stackoverflow.com/q/50958077
tags question: http://stackoverflow.com/q/50939347
tags question: http://stackoverflow.com/q/50947079
tags question: http://stackoverflow.com/q/50858871
tags question: http://stackoverflow.com/q/50898628
tag name: lstm
tags question: http://stackoverflow.com/q/50901731
tags question: http://stackoverflow.com/q/50976658
tags question: http://stackoverflow.com/q/50895891
tags question: http://stackoverflow.com/q/50992840
tags question: http://stackoverflow.com/q/50859714
tags question: http://stackoverflow.com/q/50998702
tags question: http://stackoverflow.com/q/51010350
tags question: http://stackoverflow.com/q/50865774
type: Tag
tags question: http://stackoverflow.com/q/50994090

http://stackoverflow.com/q/50914996
has answer: http://stackoverflow.com/a/50915067
accepted answer: http://stackoverflow.com/a/50915067
favorite count: 0
tagged with: django
tagged with: python
upvote count: 4
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/88830060
type: Question
has title: Dynamically creating a dictionary in python
score: 4
has body: I want to dynamically build a dictionary based on the string. I have 5 strings: ABC ABC BCD DEF ABC BCD FGH ABC BCD FGH IJK ABC DEF GHI I want to create this into a dict: dict = { "ABC" : { "BCD": {"DEF": {}, "FGH":{IJK}}, "DEF": {"GHI"}, } } This is what I have tried so far, but I'm not sure how to create the new key if there is a key error. # orgs = list of string from about for org in orgs: org_path_sp = org .strip().split() org_cur = org_dict for org_el in org_path_sp: try: org_cur = org_cur[org_el.strip()] except KeyError: pass # create the new entry
answer count: 1

http://stackoverflow.com/q/50893508
favorite count: 0
possible better answer: http://stackoverflow.com/a/50897147
tagged with: curve-fitting
tagged with: python
type: AnsweredQuestion
downvote count: 1
type: Question
has title: difficult python curve_fit multi-dimensional task requiring an optional argument
answer count: 2
has answer: http://stackoverflow.com/a/50897147
score: 0
has body: I have a set of data made up of (2-dimensional) observations of multiple objects. The observations can be described by a general function plus an offset that is unique to each object. I want to use curve_fit to simultaneously recover the general function and the offsets for each object (with associated errors). I do not know in advance how many objects the data-set will be made up of, only that there are likely to be multiple observations of each. So a generalised data set of 7 observations might look like this: [[x[0], y1[0], y2[0], lab='A'], [x[1], y1[1], y2[1], lab='B'], [x[2], y1[2], y2[2], lab='A'], [x[3], y1[3], y2[3], lab='A'], [x[4], y1[4], y2[4], lab='B'], [x[5], y1[5], y2[5], lab='C'], [x[6], y1[6], y2[6], lab='A']] I could do the task by passing the parameters of the general function (say g = [g0, g1, g2]) and the object offsets offsets = n x [o1, o2] to fit_func and then using an object label to decide which of the n offsets needs to be added to the general function, except that I can't figure out how to pass the label. def fit_func(x, g, offsets, lab): y1 = g[0] * cos(2*(x - g[1])) + offsets['lab',0] + g[2] y2 = g[0] * sin(2*(x - g[1])) + offsets['lab',1] + g[2] return [y1, y2] The problem is that lab is not a float to be fit, so I can't figure out how to pass it. From reading some other threads I believe I will need a wrapper function, but I can't figure out what form it should take, and then how to call it in such a way that I can specify sigma and p0. Can anyone point me in the right direction? Edit: I managed to produce a function that I thought would work. It used a global parameter call to choose options within the function call. So, for example I interleaved the y1 and y2 arrays, and had the function call the second equation every second run with a global getEven() and setEven(bool) call. However curve_fit really didn't like that. The fit values were nonsensical. At the moment I am fitting the equation for y1 and the equation for y2 separately an…
has answer: http://stackoverflow.com/a/50899421
accepted answer: http://stackoverflow.com/a/50899421
upvote count: 1

http://stackoverflow.com/q/50891974
tagged with: pandas
has comment: http://stackoverflow.com/comment/88784634
tagged with: python
linked to: http://stackoverflow.com/q/47777710
type: AnsweredQuestion
upvote count: 1
type: Question
score: 1
tagged with: dataframe
has body: I am struggling with something simple and it drives me crazy. Why concatenating like below doesn't replace df1 with df1 + additional column?? df1 = pd.DataFrame({'A':[1, 2, 3], 'B':[4, 5, 6]}) df2 = pd.DataFrame({'A':[1, 2, 3], 'B':[4, 5, 6]}) df3 = pd.DataFrame({'C':[999, 999, 999]}) for table in [df1, df2]: table = pd.concat((table, df3), axis=1) df1 Thanks! [edit] I need to obtain separatly for df1 and df2:
has title: Concatenating dataframes in loop
has answer: http://stackoverflow.com/a/50892044
accepted answer: http://stackoverflow.com/a/50892044
tagged with: concatenation
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/88784680
favorite count: 0

http://stackoverflow.com/q/50969271
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50969426
accepted answer: http://stackoverflow.com/a/50969426
type: Question
has title: Running into AttributeError when trying to access a list from another class in wxpython
tagged with: wxpython
score: 0
answer count: 1
tagged with: user-interface
tagged with: python
has body: I have the following code: import wx import pandas as pd import pickle from runpy import run_path ######################################################################## class Prototype(wx.Frame): #---------------------------------------------------------------------- def __init__(self, parent, title): wx.Frame.__init__(self, None, title="Tennis Form", size=(800,600)) self.UI() self.Centre() self.Show() #---------------------------------------------------------------------- def UI(self): _icon = wx.NullIcon _icon.CopyFromBitmap(wx.Bitmap("C:\\Users\\XXX\\Desktop\\Project-Tennis\\Tennis-icon.png", wx.BITMAP_TYPE_ANY)) self.SetIcon(_icon) self.SetBackgroundColour(wx.Colour(192, 192, 192)) self.button_1 = wx.Button(self, wx.ID_ANY, "ATP") self.button_1.SetMinSize((250, 50)) self.button_1.SetBackgroundColour(wx.Colour(216, 216, 191)) self.button_2 = wx.Button(self, wx.ID_ANY, "WTA") self.button_2.SetMinSize((250, 50)) self.button_2.SetBackgroundColour(wx.Colour(216, 216, 191)) self.button_2.SetForegroundColour(wx.Colour(0, 0, 0)) self.button_3 = wx.Button(self, wx.ID_ANY, "Update ATP") self.button_3.SetBackgroundColour(wx.Colour(216, 216, 191)) self.button_3.SetForegroundColour(wx.Colour(0, 0, 0)) self.button_4 = wx.Button(self, wx.ID_ANY, "Update WTA") self.button_4.SetBackgroundColour(wx.Colour(216, 216, 191)) self.button_4.SetForegroundColour(wx.Colour(0, 0, 0)) sizer_1 = wx.BoxSizer(wx.VERTICAL) sizer_2 = wx.BoxSizer(wx.HORIZONTAL) sizer_1.Add((20, 200), 0, 0, 0) sizer_1.Add(self.button_1, 0, wx.ALIGN_CENTER | wx.EXPAND | wx.LEFT | wx.RIGHT, 163) sizer_1.Add((20, 20), 0, 0, 0) sizer_1.Add(self.button_2, 0, wx.ALIGN_CENTER | wx.EXPAND | wx.LEFT | wx.RIGHT, 163) sizer_1.Add((20, 180), 0, 0, 0) sizer_2.Add((550, 20), 0, 0, 0) sizer_2.Add(self.button_3, 0, 0, 0) sizer_2.Add(self.button_4, 0, 0, 0) sizer_1.Add(sizer_2, 1, wx.EXPAND, 0) self.SetSizer(sizer_1) self.Layout() self.Centre() self.button_1.Bind(wx.EVT_BUTTON, self.OnButton1) self.button_2.Bind(wx.EVT_BUTTON, s…

http://stackoverflow.com/comment/88796395
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50898312
has text: What error? Also, `clo` != `col`.
score: 0

http://stackoverflow.com/a/51004182
upvote count: 1
downvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/104543631
answers question: http://stackoverflow.com/q/50992771
has body: I recommend using Tensorflow scopes like so: with tf.device_scope('/gpu:0'): model1.fit() with tf.device_scope('/gpu:1'): model2.fit() with tf.device_scope('/gpu:2'): model3.fit()
has comment: http://stackoverflow.com/comment/134878127
score: 0
has comment: http://stackoverflow.com/comment/103537606

http://stackoverflow.com/comment/89000561
type: Comment
comment on: http://stackoverflow.com/q/51003479
type: QuestionComment
has text: `wthreshold` is not a number. It's a string. Convert it to a number with `int()`
score: 0

http://stackoverflow.com/comment/88836310
has text: Thank you for the response. I have tried running ffplay command but the terminal says the command is not found. I have not tested VideoCapture with cv2.CAP_FFMPEG yet, but would it be possible that this is the reason why the OpenCV video capture did not work? I have tried googling on adding ffplay onto the ffmpeg installation, but I have not been successful as of now.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50917584
type: AnswerComment

http://stackoverflow.com/q/50930770
has body: For example we plot a line with transparent color here import numpy as np import matplotlib.pyplot as plt a = np.array([1, 2, 3, 4, 5]) b = 2*a plt.plot(a, b, 'blue', alpha=0.3) plt.show() but wenn I plot the same line multiple times, that overlaps with itself, so that the more it overlaps with itself, the darker it becomes. import numpy as np import matplotlib.pyplot as plt a = np.array([1, 2, 3, 4, 5]) b = 2*a for i in range(3): plt.plot(a, b, 'blue', alpha=0.3) plt.show() so How can I prevent the color-overlaps? Thank you all in advance! Update: Why I need this? I am doing a Tolerance-Analysis. That means, the parameter change themselfs within a samll range and I will plot the curve for each change. Then I can find the worst case. If I pick a solid but lighter color. It will looks like: As you can see, with untransparent color I can not observe the node, which is covered by other line. Update 2:
tagged with: python
upvote count: 4
type: AnsweredQuestion
downvote count: 0
accepted answer: http://stackoverflow.com/a/50931008
tagged with: plot
type: Question
tagged with: matplotlib
score: 4
has answer: http://stackoverflow.com/a/50931008
has title: Matplotlib: How to prevent transparent color overlay when curve overlaps?
tagged with: alpha
has comment: http://stackoverflow.com/comment/88862958
answer count: 1
has comment: http://stackoverflow.com/comment/88860482
linked to: http://stackoverflow.com/q/41798232
tagged with: alpha-transparency
favorite count: 0
has comment: http://stackoverflow.com/comment/88860544
has comment: http://stackoverflow.com/comment/88862965

http://stackoverflow.com/a/51182346
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/50895836
accepted answer of: http://stackoverflow.com/q/50895836
has comment: http://stackoverflow.com/comment/89410824
type: AcceptedAnswer
downvote count: 0
has body: Wonder if this is still relevant for you, but I've marked it as fun puzzle to revisit later... Long story short: It adds directory of location where this script file is with all symbolic links resolved (neither the acquired filename nor a directory leading up to is is a symbolic link) to PYTHONPATH. It's basically the same thing as doing so using readlink (or realpath): export PYTHONPATH="$(dirname $(readlink -f ${BASH_SOURCE})):${PYTHONOATH}" Line by line dissection: SOURCE="${BASH_SOURCE[0]}" This sets SOURCE to be path with which this script was called or sourced. while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink We enter the wile loop if SOURCE path refers to a symbolic link. I.e. in the first iteration of this file was a symbolic link. Subsequently if this was a link pointing to another link. DIR="$( cd -P "$( dirname "$SOURCE" )" &amp;&amp; pwd )" This (a bit simplified explanation of -P) changes into directory where SOURCE is resolving symbolic links along the way (i.e. lands in the directory the link(s) was/were pointing to) and prints working directory after that change (absolute path). All that happens in a subshell and result is assign to variable DIR. SOURCE="$(readlink "$SOURCE")" SOURCE is assigned a new value of path resulting from symlink resolution. Literally a target the link points to (as seen by for instance ls -l) relative or absolute. $SOURCE != \/* &amp;&amp; SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located If the SOURCE value we have obtained by symbolic link resolution does not begin with / (i.e. is an absolute path), DIR (directory where the SOURCE with which we have entered the loop resides) and resolved symbolic link SOURCE are concatenated over / to form a new SOURCE (we make it into an absolute path) and we go back to the top of this loop. NOTE: escaping of / by \ seems in this case unnecessary and arbitrary. do…

http://stackoverflow.com/comment/88876385
type: Comment
score: 1
has text: Yeah, plus I'd probably also need a drop_duplicates() in the case that a name has multiple instances of the names. This is the way :D.
type: AnswerComment
comment on: http://stackoverflow.com/a/50939081

http://stackoverflow.com/q/50985979
tagged with: python
has title: Using character value to create new rows in Pandas
type: AnsweredQuestion
downvote count: 0
score: 1
tagged with: fill
possible better answer: http://stackoverflow.com/a/50988429
linked to: http://stackoverflow.com/q/43794429
type: Question
tagged with: split
linked to: http://stackoverflow.com/q/44878959
has comment: http://stackoverflow.com/comment/88967558
linked to: http://stackoverflow.com/q/50965844
answer count: 2
accepted answer: http://stackoverflow.com/a/50986065
tagged with: pandas
upvote count: 1
has answer: http://stackoverflow.com/a/50988429
favorite count: 0
linked to: http://stackoverflow.com/q/47394793
has body: I need to create new rows in a pandas dataframe based on a value that occurs in a specific column. The pattern to create the Split is that there is a semi colon that indicates where I need to initiate a new row. df animal cat;dog;cat animal dog animal fish color black;green color red desired_df animal cat animal dog animal cat animal dog animal fish color black color green color red I have seen solutions that use pandas split to create new columns or rows using a given character or values in the df (such as here: and here: ), however, I have not seen a solution that does this with text values. I have also seen solutions (as well as one that I requested myself here) that is able to accurately fill in the null values in pandas. However, I need to combine these two techniques and it is not clear to me if this is feasible to do in a one-liner (or two).
has answer: http://stackoverflow.com/a/50986065

http://stackoverflow.com/comment/88815318
comment on: http://stackoverflow.com/q/50907023
has text: `json.load` will not work in the required format.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50892250
type: AnsweredQuestion
downvote count: 0
accepted answer: http://stackoverflow.com/a/50892400
tagged with: scipy
type: Question
score: 3
has body: I have a sparse matrix with shape (346679, 86). &lt;346679x86 sparse matrix of type '&lt;type 'numpy.int8'&gt;' with 470018 stored elements in COOrdinate format&gt; To train and evaluate my model, I need to split it into train and test sets respectively. from sklearn.model_selection import train_test_split x_train, x_test = train_test_split(sparse_matrix, test_size=0.2, random_state=11) Once this is done, I find the x_train and x_test have changed i.e some entire rows are turned to 0. I have checked the occurrence of rows with zero non-zero values for the original matrix using the code below: def get_zero_rows(sparse_matrix): sparse_matrix = sparse_matrix.tocsr() count = 0 for index, each in enumerate(sparse_matrix): if each.getnnz() &lt; 1: count += 1 return count It returns 0 for the original matrix but non-zero value for the split matrices. I don't understand why this happens?
has answer: http://stackoverflow.com/a/50892400
upvote count: 3
answer count: 1
tagged with: scikit-learn
favorite count: 0
tagged with: python
has title: sklearn train_test_split on scipy sparse matrix gives wrong result

http://stackoverflow.com/q/50974057
type: Question
has body: I have two lists (keys and values) that define a single sparsely defined list with values at every key location. I want to convert this to a dense list with values in every location. I can do this with a for loop as follows. keys = [1,3,5] values = [1.0, 3.0, 5.0] column = [None]*10 for i, k in enumerate(keys): column[k] = values[i] column &gt;&gt;&gt; [None, 1.0, None, 3.0, None, 5.0, None, None, None, None] Is it possible to create column using a list comprehension?
tagged with: list-comprehension
tagged with: sparse-matrix
upvote count: 2
answer count: 3
possible better answer: http://stackoverflow.com/a/50974299
has answer: http://stackoverflow.com/a/50974299
favorite count: 0
has comment: http://stackoverflow.com/comment/88944595
has answer: http://stackoverflow.com/a/50974312
accepted answer: http://stackoverflow.com/a/50974312
tagged with: python
has answer: http://stackoverflow.com/a/50991866
type: AnsweredQuestion
score: 2
downvote count: 0
has title: Create python list comprehension from sparse data

http://stackoverflow.com/q/51011297
tagged with: graph-theory
tagged with: algorithm
has answer: http://stackoverflow.com/a/51012629
tagged with: python-2.7
score: 0
answer count: 1
tagged with: graph-algorithm
accepted answer: http://stackoverflow.com/a/51012629
tagged with: python
type: AnsweredQuestion
has title: Karger's Min Cut Implementation in python 2.7 not giving the correct cuts
has body: from random import randint from collections import defaultdict ###################### def getGraph(filename): ''' The function takes a txt file as input and returns the Graph with 1st element of each row as a vertex. ''' with open(filename, 'r') as f_in: G = defaultdict(list) for row in f_in: row = row.split() G[row[0]] = row[1 : ] return G ###################### def getVEPair(range): ''' The function takes the range as input and returns a pair of random integers. ''' v = randint(1, range) e = randint(1, range) return v, e ###################### def removeVEPair(G, V, E): ''' The function takes Graph, Vertex and Edge as input and removes this pair from the Graph. The function then returns the resulting Graph. ''' while E in G[V]: G[V].remove(E) return G ###################### def contractNodes(G, V, E): ''' The function takes a Graph, vertex and edge as the input and contracts the two nodes which the edge connects. The function then returns the resulting Graph. ''' edges = G[E] for edge in edges: if edge != V: G[V].append(edge) return G ###################### def removeNode(G, V, E): ''' The function intakes the graph and the node to be deleted. The function deletes the node and updates all instances of the deleted node in the Graph. The function then returns the resulting Graph. ''' del G[E] for Vertex in G: while E in G[Vertex]: G[Vertex].remove(E) if V != Vertex: G[Vertex].append(V) return G ###################### def kargerMinCut(): ''' The function takes a graph as input and returns the min cut of the graph. ''' minCut = [] for i in range(0, 100): G = getGraph('dataGraph.txt') while(len(G) &gt; 2): v, e = getVEPair(8) V = str(v) E = str(e) keys = G.keys() if V in keys and E != V: if E in G[V]: G = removeVEPair(G, V, E) G = contractNodes(G, V, E) G = removeNode(G, V, E) else: continue print G for v in G: minCut.append(len(G[v])) break return minCut ###################### minCut = kargerMinCut() print '######################' print minCut print min(minCut) I exec…
type: Question

concurrency
tag name: concurrency
tags question: http://stackoverflow.com/q/50919547
tags question: http://stackoverflow.com/q/50919318
tags question: http://stackoverflow.com/q/50958595
type: Tag
tags question: http://stackoverflow.com/q/50900825

http://stackoverflow.com/comment/88819301
comment on: http://stackoverflow.com/q/50909219
score: 0
type: QuestionComment
has text: Seaborn heatmap plots categorical data. Here it seems you want to plot numeric data. Hence better use a `pyplot.pcolormesh` plot. (Note that I could provide an answer with code if there was a [mcve] in the question.)
type: Comment

http://stackoverflow.com/q/50917450
answer count: 1
has answer: http://stackoverflow.com/a/50918151
has title: Use different target vectors for CNN
accepted answer: http://stackoverflow.com/a/50918151
has comment: http://stackoverflow.com/comment/88835216
linked to: http://stackoverflow.com/q/1756096
tagged with: python
type: AnsweredQuestion
tagged with: conv-neural-network
has comment: http://stackoverflow.com/comment/88835125
type: Question
has body: I wish to use different target vectors (not the standard one-hot encoded) for training my CNN. My image data lies in 10 different folders (10 different categories). How do I use my desired target vectors? The flow_from_directory() outputs a one-hot encoded array of labels. I have the label vectors stored in a dictionary. Also, the names of the folders are the labels, if that helps.
has comment: http://stackoverflow.com/comment/88835087
tagged with: keras
has comment: http://stackoverflow.com/comment/88835561
has comment: http://stackoverflow.com/comment/88835286
score: 0
tagged with: deep-learning

http://stackoverflow.com/q/50966466
score: 29
tagged with: python
tagged with: dictionary
possible better answer: http://stackoverflow.com/a/75610693
upvote count: 29
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/75610693
has body: Consider, dataframe d: d = pd.DataFrame({'a': [0, 2, 1, 1, 1, 1, 1], 'b': [2, 1, 0, 1, 0, 0, 2], 'c': [1, 0, 2, 1, 0, 2, 2]}) > a b c 0 0 2 1 1 2 1 0 2 1 0 2 3 1 1 1 4 1 0 0 5 1 0 2 6 1 2 2 I want to split it by column a into dictionary like that: {0: a b c 0 0 2 1, 1: a b c 2 1 0 2 3 1 1 1 4 1 0 0 5 1 0 2 6 1 2 2, 2: a b c 1 2 1 0} The solution I've found using pandas.groupby is: {k: table for k, table in d.groupby("a")} What are the other solutions?
has answer: http://stackoverflow.com/a/50966605
has title: Convert pandas.groupby to dict
type: Question
has comment: http://stackoverflow.com/comment/88929219
tagged with: group-by
answer count: 2
tagged with: pandas
accepted answer: http://stackoverflow.com/a/50966605
downvote count: 0
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/comment/119586820
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50917379
has text: Does this answer your question? [How to close IPython Notebook properly?](https://stackoverflow.com/questions/10162707/how-to-close-ipython-notebook-properly)

http://stackoverflow.com/comment/88905528
type: Comment
comment on: http://stackoverflow.com/a/50938653
has text: That worked perfectly, thanks man! What exactly is the logic behind this? What does the $ mean?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88880533
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50941223
type: QuestionComment
has text: Can you post the whole code including your classifier ?

http://stackoverflow.com/comment/88749007
type: QuestionComment
score: 0
has text: [while](https://docs.python.org/3/reference/compound_stmts.html#while) and [more on while](https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops) and basically [start here:](https://docs.python.org/3/tutorial/) .. SO is no tutorial site that teaches basics of a language. We care about specific problems _if_ you already did your research on this and other site and are stuck.
comment on: http://stackoverflow.com/q/50873376
type: Comment

http://stackoverflow.com/q/50899162
tagged with: jupyter-notebook
favorite count: 0
has comment: http://stackoverflow.com/comment/88798121
has comment: http://stackoverflow.com/comment/88798065
tagged with: cpu-usage
accepted answer: http://stackoverflow.com/a/50900574
has comment: http://stackoverflow.com/comment/88798229
tagged with: python
upvote count: 6
type: AnsweredQuestion
tagged with: cpu-architecture
downvote count: 1
has title: Can I run two seperate jupyter notebook files at the same time, without slowdown on a single CPU computer?
type: Question
score: 5
has body: I am currently running a python function in jupyter notebook, which is taking quite some time. Python says it is running at about 98% of the CPU, however, still about 60% of my CPU is unused. Now after some googling I have found that this has to do something with threading of my processor (I am not a computer engineer so sorry if this is incorrect). However, I was wondering if can run another function in jupyter notebook, and will it take up some of that 60% unused activity, or will it divide the 99% among two functions, slowing down both functions. I hope you guys can help. If anything is unclear please let me know. P.S. I am using a macbook pro retina late 2012 (i know), 2,5 gHZ intel core i5, with 8 gbs of ram. It has two cores and one processor.
has answer: http://stackoverflow.com/a/50900574
answer count: 1

http://stackoverflow.com/comment/88907407
type: AnswerComment
type: Comment
score: 1
has text: Interesting! But I'm getting the following error: "TypeError: on_button_clicked() takes 1 positional argument but 2 were given"
comment on: http://stackoverflow.com/a/50952534

http://stackoverflow.com/a/50866978
has comment: http://stackoverflow.com/comment/88762426
type: Answer
has comment: http://stackoverflow.com/comment/88768592
has comment: http://stackoverflow.com/comment/88763808
answers question: http://stackoverflow.com/q/50866385
upvote count: 2
has comment: http://stackoverflow.com/comment/88763661
accepted answer of: http://stackoverflow.com/q/50866385
score: 2
has comment: http://stackoverflow.com/comment/88768690
has comment: http://stackoverflow.com/comment/88768836
has body: Everyone seems attracted to a dict-only solution, but why not try converting to pandas? import pandas as pd # given tuple_list = [('Player1', 'A', 1, 100), ('Player1', 'B', 15, 100), ('Player2', 'A', 7, 100), ('Player2', 'B', 65, 100), ('Global Total', None, 88, 100)] # make a dataframe df = pd.DataFrame(tuple_list , columns = ['player', 'game','score', 'pct']) del df['pct'] df = df[df.player!='Global Total'] df = df.pivot(index='player', columns='game', values='score') df.columns.name='' df.index.name='' # just a check assert df.to_dict() == {'A': {'Player1': 1, 'Player2': 7}, 'B': {'Player1': 15, 'Player2': 65}} # A B #player #Player1 1 15 #Player2 7 65 print('Obtained dataset:\n', df) Basically, all you need is 'df' dataframe, and the rest you can compute and add later, no need to save it to dictionary. Below is updated on OP request: # the sum across columns is this - this was the 'Grand Total' in the dicts # A 8 # B 80 sum_col = df.sum(axis=0) # lets calculate the share of each player score: shares = df / df.sum(axis=0) * 100 assert shares.transpose().to_dict() == {'Player1': {'A': 12.5, 'B': 18.75}, 'Player2': {'A': 87.5, 'B': 81.25}} # in 'shares' the columns add to 100%: # A B #player #Player1 12.50 18.75 #Player2 87.50 81.25 # lets mix up a dataframe close to original dictionary structure mixed_df = pd.concat([df.A, shares.A, df.B, shares.B], axis=1) totals = mixed_df.sum(axis=0) totals.name = 'Total' mixed_df = mixed_df.append(totals.transpose()) mixed_df.columns = ['A', 'A_pct', 'B', 'B_pct'] print('\nProducing some statistics\n', mixed_df)
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/88793975
type: AnswerComment
has text: Didn't work. Funny thing is that if I do this with direct references instead of the for loop it works. This works but I want to do it for all of the refs references=[pack_data["actual_box_barcode"].unique()] ref_utilization={} total_utilization=len(pack_data["actual_box_barcode"]) print(total_utilization) ref_filtered=pack_data[pack_data["actual_box_barcode"]=="BG2"] ref_utilizations=len(ref_filtered["actual_box_barcode"])
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50896927

http://stackoverflow.com/comment/89006205
has text: Even if it wasn't a `numpy` array, the syntax `...[i, dev_lables[i]]` just means you are indexing something with a tuple `(i, dev_labels[i])`. Only the comma is used to define a tuple; the parentheses are optional in many contexts.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51006303

http://stackoverflow.com/q/50879309
has body: Using Python, I want to check whether a circle has an equal radius along all 360 degrees. Actually, I have segmented a circular shape from an image and then want to check whether it has a same-sized and equal radius along all the 360 degrees or not. Can someone kindly help and tell how to do that?
has comment: http://stackoverflow.com/comment/88775053
type: Question
linked to: http://stackoverflow.com/q/32793703
score: -2
has answer: http://stackoverflow.com/a/50879538
has comment: http://stackoverflow.com/comment/88760884
tagged with: image-segmentation
downvote count: 2
has comment: http://stackoverflow.com/comment/88760695
answer count: 1
favorite count: 0
tagged with: geometry
has comment: http://stackoverflow.com/comment/88760746
type: UnansweredQuestion
has title: Python: How to check whether a Circle has equal radius along all 360 degrees
tagged with: python
has comment: http://stackoverflow.com/comment/88760785
tagged with: radius
has comment: http://stackoverflow.com/comment/88760996
upvote count: 0

http://stackoverflow.com/q/50886042
has comment: http://stackoverflow.com/comment/88787825
has comment: http://stackoverflow.com/comment/88835064
has comment: http://stackoverflow.com/comment/88803563
type: UnansweredQuestion
has title: Missing environment variables when using python's subprocess
tagged with: windows
tagged with: python
has body: When I open a cmd in windows 10 and enter the set command I will normally get a list of all the environment variables on the system (output was truncated due to irrelevent content only the path variable is conserved as it is the problematic one) Output (cmd): Path=C:\smth;C:\Program Files\ImageMagick-7.0.8-Q16;C:\Program Files (x86)\Common Files\Intel\Shared Libraries\redist\ia32_win\compiler;C:\Program Files (x86)\Common Files\Intel\Shared Libraries\redist\intel64_win\compiler;C:\Program Files (x86)\Razer Chroma SDK\bin;C:\Program Files\Razer Chroma SDK\bin;C:\Program Files\Microsoft MPI\Bin\;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\ATI Technologies\ATI.ACE\Core-Static;C:\Program Files\dotnet\;C:\Program Files\Microsoft SQL Server\130\Tools\Binn\;C:\WINDOWS\system32\config\systemprofile\AppData\Local\Microsoft\WindowsApps;C:\Program Files\Git\cmd;C:\Program Files\CMake\bin;C:\Program Files (x86)\AMD APP SDK\3.0\bin\x86_64;C:\Program Files (x86)\AMD APP SDK\3.0\bin\x86;C:\Program Files (x86)\AMD\ATI.ACE\Core-Static;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Users\R3QU13M\AppData\Local\Microsoft\WindowsApps;;C:\Program Files\Microsoft VS Code\bin Output using subprocess.call('set', shell=True)) Path=C:\Users\R3QU13M\Anaconda3\envs\StyleTransfer\Library\bin;C:\Program Files (x86)\Common Files\Intel\Shared Libraries\redist\ia32_win\compiler;C:\Program Files (x86)\Common Files\Intel\Shared Libraries\redist\intel64_win\compiler;C:\Program Files (x86)\Razer Chroma SDK\bin;C:\Program Files\Razer Chroma SDK\bin;C:\Program Files\Microsoft MPI\Bin\;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\ATI Technologies\ATI.ACE\Core-Static;C:\Program Files\dotnet\;C:\Program Files\Microsoft SQL Server\130\Tools\Binn\;C:\WINDOWS\system32\confi…
answer count: 0
has comment: http://stackoverflow.com/comment/88774383
type: Question
has comment: http://stackoverflow.com/comment/88785065
score: 0
tagged with: environment-variables

http://stackoverflow.com/q/50912696
score: 0
tagged with: git-ls-files
answer count: 1
has title: Dulwich cheat sheet: how to reproduce "git ls-files"?
tagged with: git
has comment: http://stackoverflow.com/comment/88827749
has comment: http://stackoverflow.com/comment/88854900
type: UnansweredQuestion
has body: Dear community members, I'm working on a code analysis system and would like to replace calls to CLI Git application with Dulwich module. As the first step I need to replace "git ls-files" command with Dulwich equivalent. I did it in the following way: import os import stat import subprocess from tempfile import TemporaryDirectory from dulwich import porcelain from dulwich.repo import Repo from dulwich.objects import Commit, Tree def _flatten_git_tree(r, object_sha, prefix=b'', sep=b'/'): result=[] git_object=r.get_object(object_sha) if git_object.type_name==b'tree': for item in git_object.iteritems(): if stat.S_ISREG(item.mode): result.append(sep.join([prefix, item.path])) if stat.S_ISDIR(item.mode): result.extend(_flatten_git_tree(r, item.sha, prefix+sep+item.path, sep)) if git_object.type_name==b'commit': result.extend(_flatten_git_tree(r, git_object.tree, prefix, sep)) return result def _run_git_cmd(git_arguments): return subprocess.Popen(git_arguments, stdout=subprocess.PIPE).communicate()[0] with TemporaryDirectory() as temp_dir: git_clone_url=r"https://github.com/dulwich/dulwich.git" repo=porcelain.clone(git_clone_url, temp_dir, checkout=True) dulwich_ls_files=_flatten_git_tree(repo, repo.head()) git_ls_files=_run_git_cmd(['git', '-C', os.path.join(temp_dir, 'dulwich'), 'ls-files']) git_ls_files=git_ls_files.decode('utf-8').splitlines() assert len(dulwich_ls_files)==len(git_ls_files) Quick assert shows that outputs differ. What could be a reason? Answering my own question with the help from @jelmer. The reason for the problem was in the line I commented. Now outputs match. import os import subprocess from tempfile import TemporaryDirectory from dulwich import porcelain from dulwich.repo import Repo def _run_git_cmd(git_arguments): return subprocess.Popen(git_arguments, stdout=subprocess.PIPE).communicate()[0] with TemporaryDirectory() as temp_dir: git_clone_url=r"https://github.com/dulwich/dulwich.git" repo=porcelain.clone(git_clone_url, temp_dir) dulwich_ls_…
has answer: http://stackoverflow.com/a/50934660
tagged with: dulwich
has comment: http://stackoverflow.com/comment/88832538
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/88855810
has comment: http://stackoverflow.com/comment/88863289

http://stackoverflow.com/q/50982111
tagged with: regex
has comment: http://stackoverflow.com/comment/88960109
has title: regular expression
has comment: http://stackoverflow.com/comment/88959760
upvote count: 1
has comment: http://stackoverflow.com/comment/88959648
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88960342
has comment: http://stackoverflow.com/comment/88960534
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/88959752
has answer: http://stackoverflow.com/a/50984839
has body: I need to match Regular expression for txt = "orderType not in ('connect', 'Modify', 'random', 'more')" correct data: txt = "orderType is in ('connect')" txt = "orderType not in ('connect', 'Modify')" N number of items can be inside bracket, with quotes and comma separated like above. Rest of all should not be matched, like below txt = "orderType not in ('connect', Modify, 'ran=dom', 'more')" import re pattern1 = '\w+\s+(?:is|not)\sin\s+\(' pattern2 = '\'\w+\'' pattern3 = '\s?,\s?'+pattern2+'+' print(re.findall(pattern3, txt)) pattern6 = pattern1+pattern2 pattern5 = pattern1+pattern2+pattern3 pattern4 = (pattern2+ pattern3) +'|'+ (pattern2 ) pattern = pattern5+ '|' + pattern6 print(re.findall(pattern,txt)) my output is ["orderType not in ('connect', 'Modify'"] expected output should: orderType not in ('connect', 'Modify', 'random', 'more') Be it entire line, I won't mind if it returns true for all matched and false for the rest
favorite count: 0
has answer: http://stackoverflow.com/a/50986372
has comment: http://stackoverflow.com/comment/88959549
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88959597
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/50909252
score: 0
has comment: http://stackoverflow.com/comment/88819182
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50908946
has body: Python uses /bin/sh by default to execute commands. Running your second command there produced the following error message for me: cut: the delimiter must be a single character Try 'cut --help' for more information. In cut, the default delimiter is \t, so try running the following command instead: cut -f2,4,8,46,63,65,66 raw_extract_{}.tsv &gt; extract_{}_reduced.tsv Alternatively, you can use the command /bin/bash -c "cut -d$'\t' -f2,4,8,46,63,65,66 raw_extract_{}.tsv &gt; extract_{}_reduced.tsv"
type: Answer
has comment: http://stackoverflow.com/comment/88818877
has comment: http://stackoverflow.com/comment/88818938
accepted answer of: http://stackoverflow.com/q/50908946

http://stackoverflow.com/q/50961821
upvote count: 0
has answer: http://stackoverflow.com/a/50962066
answer count: 1
favorite count: 0
has title: setting two different multiple regression layers
accepted answer: http://stackoverflow.com/a/50962066
has body: I'm now working on a small project, but I don't know how I should build the model. So, the number of inputs is 27, outputs is 163. I need to find weights and biases by training, and I am done with this by using 5 layers including relu and dropout. When I see a cost graph about training loss and validation loss from a tensorboard, it looks ok. 1) However, what I also need to concern about is uniformity, which is calculated as below: uniformity = (max. of y - min. of y) / (max. of y + max. of y) I have a real uniformity data which are given, and when I find uniformities from y_predict value, and the difference is too big from the real uniformity value. Is there any way to add uniformity while training, so that it not only care about finding the right weights and biases, but also close uniformity? Thank you!
tagged with: python
downvote count: 1
type: AnsweredQuestion
score: -1
tagged with: tensorflow
type: Question

http://stackoverflow.com/comment/89095568
type: Comment
type: QuestionComment
has text: I've deleted my previous comment, it didn't make sense. If `{{ form }}` displays the error, then `form.filename.errors` should display the error as well. Your template is more complicated than it needs to be (e.g. unnecessary `form.is_bound` check), but I can't see anything that explains why the error isn't displayed.
comment on: http://stackoverflow.com/q/50970667
score: 1

http://stackoverflow.com/comment/99889684
type: QuestionComment
type: Comment
has text: Try multiplying your batch size by the number of gpus used.
comment on: http://stackoverflow.com/q/50900736
score: 0

http://stackoverflow.com/comment/88867717
has text: Storing a list in a cell is usually a bad enough idea, but it's really hard to work with one in a column. Is there a saner storage method you'd settle for?
score: 0
comment on: http://stackoverflow.com/q/50917384
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51005206
tagged with: python
answer count: 0
type: UnansweredQuestion
upvote count: 1
has body: I have a multi frame TIF file which is a recording of neuronal fluorescence intensity changes over time. The TIF file has 80 x 60 pixels and 2000 frames. I would like to analyse the frequency of the fluorescence intensity changes for each pixel and for that I would need to define the sampling rate of the frames. Right now I have a 3D array with (x,y) coordinates of the pixels for each frame and the number of frames in z axis projection. I have converted the multi frame TIF file in a 3D numpy array with the following script. from PIL import Image import numpy as np img = Image.open('C:/Users/Desktop/demoMovie.tif') images = [] for i in range(2000): try: img.seek(i) slice_ = np.zeros((80, 60)) for j in range(slice_.shape[0]): for k in range(slice_.shape[1]): slice_[j,k] = img.getpixel((j, k)) images.append(slice_) except EOFError: # Not enough frames in img break return np.array(images) Is there any way how to convert the number of the frames (z axis) in time which correspond to the frequency of the frame rate so that I can analyse the fluorescence intensity frequency for each pixel? Thank you very much for your help.
has title: How to define the sampling rate in a 3D numpy array for a multi frame TIFF file?
score: 1
tagged with: frequency-analysis
type: Question
tagged with: tiff
tagged with: numpy-ndarray
downvote count: 0
favorite count: 0
tagged with: frames

http://stackoverflow.com/q/51000606
tagged with: django
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
tagged with: file
has answer: http://stackoverflow.com/a/51000934
type: Question
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/88995293
has body: CODE: if request.is_ajax(): testpic = TestPic.objects.get(pk=1) form = TestPicForm(request.POST, request.FILES) if form.is_valid(): from PIL import Image from io import BytesIO data = request.FILES['file'] data_50 = request.FILES['file'] input_file = BytesIO(data.read()) image_crop = Image.open(input_file) print('print 2') # Problem starts. input_file_50 = BytesIO(data_50.read()) image_crop_50 = Image.open(input_file_50) image_crop = image_crop.crop((1,1,100,100)) image_crop_50 = image_crop_50.crop((40, 40, 140, 140)) image_resize = image_crop.resize((300, 300), Image.ANTIALIAS) image_resize_50 = image_crop_50.resize((50, 50), Image.ANTIALIAS) image_file = BytesIO() image_resize.save(image_file, 'JPEG') image_file_50 = BytesIO() image_resize_50.save(image_file_50, 'JPEG') data.file = image_file testpic.file = data data_50.file = image_file_50 testpic.file_50 = data_50 testpic.save() return JsonResponse({'success': 'file_uploaded'}) return JsonResponse({'success': 'failed'}) And Traceback is like this: print 2 Traceback (most recent call last): ... I remove some lines ... File "D:\pythonDev\project\upward\chatkaboo\authapp\views.py", line 844, in crop image_crop_50 = Image.open(input_file_50) File "D:\pythonDev\interpreters\forMultichat\lib\site-packages\PIL\Image.py", line 2590, in open % (filename if filename else fp)) OSError: cannot identify image file &lt;_io.BytesIO object at 0x0000024B40510BF8&gt; Description: As you can see on above my code's purpose is that saving requested image file. I tried to find what happened and which line has problem. So print 2 was printed, and therefore input_file_50 = BytesIO(data_50.read()) line has problem. Question: Why this error happened? BytesIO can only deal with just one file at a time? How can I deal with a file and save it as two or more files?
accepted answer: http://stackoverflow.com/a/51000934
favorite count: 0
has title: Django, saving image, OSError: cannot identify image file

http://stackoverflow.com/comment/88921308
type: Comment
has text: What data do you want to compare? If you want to check how well your model has predicted, please see http://scikit-learn.org/stable/modules/generated/sklearn.metrics.classification_report.html
score: 1
comment on: http://stackoverflow.com/a/50961890
type: AnswerComment

http://stackoverflow.com/a/50936381
answers question: http://stackoverflow.com/q/50936332
downvote count: 0
has comment: http://stackoverflow.com/comment/88871763
type: Answer
has body: Use itertools.count: for row, name, time in zip(itertools.count(), Linklist, Timelist): ...
has comment: http://stackoverflow.com/comment/88872004
upvote count: 2
has comment: http://stackoverflow.com/comment/88871722
score: 2

http://stackoverflow.com/a/50898431
has comment: http://stackoverflow.com/comment/88796689
downvote count: 0
has body: You can use the standard library's textwrap module. import textwrap s = "you'll never know the truth, said the artificially emlengthened example string" for chunk in textwrap.wrap(s, 15): print(chunk) outputs you'll never know the truth, said the artificially emlengthened example string
type: Answer
has comment: http://stackoverflow.com/comment/88796634
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/50898184

http://stackoverflow.com/q/50995179
type: Question
has body: I have a dataset with two columns: customer id and addresses: id addresses 1111 asturias 32, benito juarez, CDMX 1111 JOSE MARIA VELASCO, CDMX 1111 asturias 32 DEPT 401, INSURGENTES, CDMX 1111 deportes 1111 asturias 32, benito juarez, MIXCOAC, CDMX 1111 cd. de los deportes 1111 deportes, wisconsin 2222 TORRE REFORMA LATINO, CDMX 2222 PERISUR 2890 2222 WE WORK, CDMX 2222 WEWORK, TORRE REFORMA LATINO, CDMX 2222 PERISUR: 2690, COYOCAN 2222 TORRE REFORMA LATINO I am interested to find number of different addresses for each customers. For example, for the customer id 1111, there are 3 different addresses: [asturias 32, benito juarez, CDMX, asturias 32 DEPT 401, INSURGENTES, CDMX, asturias 32, benito juarez, MIXCOAC, CDMX] [JOSE MARIA VELASCO, CDMX] [deportes, cd. de los deportes, deportes, wisconsin] I wrote a code in python which can only show similarity between two consecutive rows: row i and row i+1 (score of 0 means completely dissimilar and 1 means completely similar). id addresses score 1111 asturias 32, benito juarez, CDMX 0 1111 JOSE MARIA VELASCO, CDMX 0 1111 asturias 32 DEPT 401, INSURGENTES, CDMX 0 1111 deportes 0 1111 asturias 32, benito juarez, MIXCOAC, CDMX 0 1111 cd. de los deportes 0.21 1111 deportes, wisconsin 0 2222 TORRE REFORMA LATINO, CDMX 0 2222 PERISUR 2890 0 2222 WE WORK, CDMX 0.69 2222 WEWORK, TORRE REFORMA LATINO, CDMX 0 2222 PERISUR: 2690, COYOCAN 0 2222 TORRE REFORMA LATINO If score > 0.20, I am considering them two different addresses. Following is my code: import nltk import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import re import unicodedata import unidecode import string from sklearn.feature_extraction.text import TfidfVectorizer data=pd.read_csv('address.csv') nltk.download('punkt') stemmer = nltk.stem.porter.PorterStemmer() remove_punctuation_map = dict((ord(char), None) for char in string.punctuation) def stem_tokens(tokens): return [stemmer.stem(item) for item in tokens] '''remove punctuati…
tagged with: python
tagged with: nlp
has comment: http://stackoverflow.com/comment/89003966
has comment: http://stackoverflow.com/comment/89112484
has answer: http://stackoverflow.com/a/51036531
upvote count: 1
has comment: http://stackoverflow.com/comment/89001243
answer count: 1
tagged with: numpy
tagged with: nltk
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51036531
has title: How to find number of similar addresses for each customer?
downvote count: 0
score: 1
tagged with: scikit-learn
favorite count: 0
has comment: http://stackoverflow.com/comment/88985787

http://stackoverflow.com/comment/88924439
score: 0
has text: I followed your instruction and found that `FFMPEG` is `NO`. So I reinstall the `opencv` with `ffmpeg` support and fixed the problem.
type: Comment
comment on: http://stackoverflow.com/a/50962166
type: AnswerComment

http://stackoverflow.com/comment/88832194
type: QuestionComment
comment on: http://stackoverflow.com/q/50916074
has text: You're going to have to include the contents of `urls.py` but my guess is that you're missing a comma.
score: 4
type: Comment

http://stackoverflow.com/a/50936233
has body: The easiest way is to rebuild the soup after each pass. from bs4 import BeautifulSoup import re html = """ love blah blah war blah blah love blah blah war love blah blah blah blah love blah blah blah blah love blah blah war blah blah love blah blah war blah blah """ listOfWords = ["war", "love"] for a in listOfWords: soup = BeautifulSoup(html, 'html.parser') for text in soup.find_all(text=True): if re.search(r'(\w*)%s\b' %a, text): text.replaceWith(BeautifulSoup(re.sub(r'(\w*)%s\b' %a, r'%s' %(a, a), text, re.UNICODE), 'html.parser')) html = str(soup) print (soup) Outputs: love blah blah war blah blah love blah blah war love blah blah blah blah love blah blah blah blah love blah blah war blah blah love blah blah war blah blah
type: Answer
answers question: http://stackoverflow.com/q/50931907
score: 0

http://stackoverflow.com/comment/88913276
comment on: http://stackoverflow.com/q/50957861
has text: Damn, case closed!
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50929539
answer count: 1
has body: I'm trying to experiment a bit with python asyncio to improve in that area, for self teaching purposes I'm trying to connect to redis, send some commands and read the response, this can fall under generic "read a stream of data from some source". The problem I cannot solve is how to read data in chunks, since the connection is not being closed between server and client and the termination sequence \r\n could be met more than once. If I await when there is no more data of course the call will block until something else will be received. class Client: def __init__(self, loop, host='127.0.0.1', port=6379): self.host = host self.port = port self.reader = None self.writer = None self.loop = loop @asyncio.coroutine def _connect(self): self.reader, self.writer = yield from asyncio.open_connection( self.host, self.port, loop=self.loop) async def read(self, b=4096): resp = b'' while True: chunk = await self.reader.read(b) if chunk: resp += chunk else: break return resp Let's pretend I want to read the response in chunks of 2 bytes (yes is stupid but it's just for this learning purpose) so: loop = asyncio.get_event_loop() client = Client(loop) ..... sends some commands here .... resp = await client.read(2) I cannot figure out how while not knowing the length of the server response the code can still be safe when the response is longer than the bytes read from the socket.
has comment: http://stackoverflow.com/comment/88881671
has answer: http://stackoverflow.com/a/50930939
upvote count: 3
has title: How to avoid blocking when reading from a socket with python asyncio?
tagged with: python-sockets
downvote count: 0
accepted answer: http://stackoverflow.com/a/50930939
tagged with: python-asyncio
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/88860819
has comment: http://stackoverflow.com/comment/88859510
has comment: http://stackoverflow.com/comment/88872683
has comment: http://stackoverflow.com/comment/88881944
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88860929
type: Question
has comment: http://stackoverflow.com/comment/88858900
tagged with: python

http://stackoverflow.com/q/50892908
tagged with: pytorch
type: UnansweredQuestion
tagged with: python
has body: First, I should mention I’m on torch version 0.3.1, but am happy to upgrade if necessary. I am still learning, so please let me know if I misunderstood anything here. I am building several graphs imperatively, using Variables. The mathematical expressions might be quite complicated as time goes on, and certain parts of the graphs may be generated using autograd’s gradient functions, which may then be operated on. I can create whatever expression I want just fine. The only catch is building up this graph can be quite “slow” - for relatively simple operations (4x4 matrices being multiplied together), it can take a few ms. Once these graphs are generated, though, I expect that I should be able to update certain Variables’ values, and evaluate the output of the graph (or any node, really), much faster. I believe that that is probably the case since evaluation should be able to happen completely in the C back-end, which should be pretty otimized for speed? In other words, building the graph in python might be slow, since it involves python for loops and the like, but re-evaluating a graph with static topology should be fast. Is this intuition correct? If so, how can I efficiently re-assign a value and re-evaluate the graph?
score: 1
tagged with: autograd
type: Question
has answer: http://stackoverflow.com/a/50895775
has title: Updating Pytorch variables
upvote count: 1
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/88918322
type: Comment
comment on: http://stackoverflow.com/a/50948350
score: 1
type: AnswerComment
has text: oh, I got your point. but it's my fault to make your misunderstanding the primary key. You identify each row with unique a column combinations. Great job! But the [primary keys](https://en.wikipedia.org/wiki/Primary_key) I need have to come from same columns. Anyway,your answer is very inspiring, thank you again!

http://stackoverflow.com/comment/88786694
score: 0
type: Comment
type: QuestionComment
has text: Are you trying to implement ```FV = PV * (1 + i) ** n``` compound interest formula?
comment on: http://stackoverflow.com/q/50893048

http://stackoverflow.com/comment/88934736
comment on: http://stackoverflow.com/a/50969194
has text: Sorry that was a typo.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88878871
has text: @zimdero It was to stop the crawler after browsing certain amount of Wikipedia articles
comment on: http://stackoverflow.com/q/50940424
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50897860
tagged with: for-loop
tagged with: python-itertools
has comment: http://stackoverflow.com/comment/88795486
has comment: http://stackoverflow.com/comment/88795503
has comment: http://stackoverflow.com/comment/88795560
score: 0
has comment: http://stackoverflow.com/comment/88795380
has comment: http://stackoverflow.com/comment/88795550
answer count: 1
has comment: http://stackoverflow.com/comment/88795505
has answer: http://stackoverflow.com/a/50897981
has comment: http://stackoverflow.com/comment/88795564
type: UnansweredQuestion
has body: Is there a quicker way (perhaps using itertools) to implement the code below? for i in range(0,10): for j in range(0,i+1): do stuff do stuff Thanks.
tagged with: python
has comment: http://stackoverflow.com/comment/88795490
has comment: http://stackoverflow.com/comment/88795472
tagged with: performance
has comment: http://stackoverflow.com/comment/88795460
has title: Efficient double for loop where range of second loop depends on value of first
type: Question

http://stackoverflow.com/q/51005163
accepted answer: http://stackoverflow.com/a/51005720
tagged with: django-rest-framework
favorite count: 0
tagged with: python
has title: Retrieving a Django model with only a subset of related objects
possible better answer: http://stackoverflow.com/a/51005252
score: 1
tagged with: django
has body: I'm attempting to retrieve a specific Django model with only a subset of its related objects that match a certain criteria. For example, I want to get a specific Restaurant, and return all of the Pizzas served at this restaurant that are vegetarian. For example, if I have a Restaurant named Papa's Pizza that serves some pizza. Let's say I have a Pizza model like this: class Pizza(models.Model): ... type = models.CharField(...) restaurant = models.ForeignKey('Restaurant', related_name='pizzas_offered') ... And Papa's Pizza offers the following Pizzas: Margherita (type='vegetarian') Pepperoni (type='carnivore') Pineapple-Only (type='vegetarian) I'd like to retrieve the Papa's Pizza model with only the Margherita and Pineapple-Only pizzas in the pizzas_offered field. How would I go about accomplishing this? If it helps at all, I'm also using Django Rest Framework, so if you have any experience with that and the functionality might exist in a Serializer rather than in the model, that will work too. Thank you very much!
type: AnsweredQuestion
tagged with: django-models
has answer: http://stackoverflow.com/a/51005252
type: Question
answer count: 3
upvote count: 1
has answer: http://stackoverflow.com/a/51005409
downvote count: 0
has answer: http://stackoverflow.com/a/51005720

http://stackoverflow.com/a/51000977
type: Answer
has comment: http://stackoverflow.com/comment/88997748
has comment: http://stackoverflow.com/comment/89002321
score: 1
has comment: http://stackoverflow.com/comment/88996235
has body: You have a minor issue. You are trying to print id outside the for loop where the id is not accessible. So, it should be placed inside the loop. Also, due to this reason, there is no reason that you should have iFoundTheLine variable as it is unnecessary. EDIT: for line in f should be for line in f.readlines() With some refactoring of your code: import glob strname = "ntpq -p" for File in glob.glob("/home/xxx/*.txt"): with open(File, 'r', encoding='utf-8') as f: for line in f.readlines(): line = line.rstrip() id = line.split("&lt;|&gt;")[0] if strname in line: print ("%s is ok" % id) break else: # Since, `id` is accessible inside the loop print ("Problem with NTP%s" % id) Since the text file contains special characters, I recommend using UTF-8 encoding with the file rather than accessing it in binary, as it makes the file interaction easier.
answers question: http://stackoverflow.com/q/51000788
has comment: http://stackoverflow.com/comment/88996292
has comment: http://stackoverflow.com/comment/88996131
has comment: http://stackoverflow.com/comment/88996044
upvote count: 1
has comment: http://stackoverflow.com/comment/89000296
downvote count: 0
has comment: http://stackoverflow.com/comment/88996174

http://stackoverflow.com/comment/88845408
has text: it looks like there is something wrong with the second image maybe?
comment on: http://stackoverflow.com/q/50921967
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88716633
has text: It is 'repeating' because you count `gameon` each time you see the word as you iterate (i.e. twice- first time there are 2, second time you've replaced them all with empty strings, so there are 0 in the string but the list remain uneffected of course)
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50857000

http://stackoverflow.com/comment/88877326
score: 1
has text: Thanks @zimdero but this would operate on the DOM of the page if I'm not wrong. I need to calculate not just the time take to load the DOM but also the time taken to complete AJAX calls as well, even if they are inside some iframe of the page.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50936735

http://stackoverflow.com/q/50998899
tagged with: python-requests
answer count: 1
has body: I'm attempting to make a bot, although the post request requires to be in XML, I have no experience dealing with XML and I'd like your help. The request payload looks a bit like this: ------WebKitFormBoundaryyXmSIiVhzetQj7u9 Content-Disposition: form-data; name="Name" asdafa ------WebKitFormBoundaryyXmSIiVhzetQj7u9 Content-Disposition: form-data; name="Description" ------WebKitFormBoundaryyXmSIiVhzetQj7u9 Content-Disposition: form-data; name="Genre" All ------WebKitFormBoundaryyXmSIiVhzetQj7u9 Content-Disposition: form-data; name="thumbnailImageFile"; filename="" Content-Type: application/octet-stream How would I replicate that in python? I've tried simple things such as create = s.post(url='https://www.url.com/', data=xml) I've also tried having a header like {'Content-Type': 'application/xml'} and I've had no success.
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51000247
has title: Python, XML sending POST requests with format
type: Question
linked to: http://stackoverflow.com/q/12509888
tagged with: python
has comment: http://stackoverflow.com/comment/88994076
tagged with: http://stackoverflow.com/tag/xml
has comment: http://stackoverflow.com/comment/88992481
score: 0

http://stackoverflow.com/comment/88988073
comment on: http://stackoverflow.com/a/50996673
type: Comment
has text: Thank you, your completely right. I'm not the best at finding good sources to learn from, I appreciate you linking me the material! ^-^
type: AnswerComment
score: 1

http://stackoverflow.com/comment/88862002
has text: When I tried with the bash command and VideoCapture with cv2.CAP_FFMPEG, they both stop at a distorted black image and crashes (same as what I described in the original post). I am still confused about why I can stream on VLC but not on FFMPEG. I have updated the original post with the error messages.
type: Comment
comment on: http://stackoverflow.com/a/50917584
score: 1
type: AnswerComment

http://stackoverflow.com/comment/88736059
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50866681
has text: I added a function wich always causes the exception. The exception only occurs when 'frozen'. I tried it with the same file 'frozen' and 'unfrozen'.
score: 0

http://stackoverflow.com/comment/88908419
type: Comment
score: 1
type: AnswerComment
has text: @Huzo the syntax is wrong. When using dual list comprehension you have to reverse the for: `[c for x in texts for c in x]`
comment on: http://stackoverflow.com/a/50955369

http://stackoverflow.com/comment/88944455
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50973384
has text: Did you run your migrations?

http://stackoverflow.com/q/50929266
tagged with: python
has comment: http://stackoverflow.com/comment/88895129
has comment: http://stackoverflow.com/comment/88897318
downvote count: 0
tagged with: tensorflow
type: Question
score: 9
tagged with: tfrecord
has comment: http://stackoverflow.com/comment/88864461
answer count: 3
linked to: http://stackoverflow.com/q/50742757
has title: Tensorflow object detection API killed - OOM. How to reduce shuffle buffer size?
has comment: http://stackoverflow.com/comment/88895055
favorite count: 0
upvote count: 9
has answer: http://stackoverflow.com/a/56573009
has answer: http://stackoverflow.com/a/59781455
tagged with: object-detection-api
has body: System information OS Platform and Distribution: CentOS 7.5.1804 TensorFlow installed from: pip install tensorflow-gpu TensorFlow version: tensorflow-gpu 1.8.0 CUDA/cuDNN version: 9.0/7.1.2 GPU model and memory: GeForce GTX 1080 Ti, 11264MB Exact command to reproduce: python train.py --logtostderr --train_dir=./models/train --pipeline_config_path=mask_rcnn_inception_v2_coco.config Describe the problem I am attempting to train a Mask-RCNN model on my own dataset (fine tuning from a model trained on COCO), but the process is killed as soon as the shuffle buffer is filled. Before this happens, nvidia-smi shows memory usage of around 10669MB/11175MB but only 1% GPU utilisation. I have tried adjusting the following train_config settings: batch_size: 1 batch_queue_capacity: 10 num_batch_queue_threads: 4 prefetch_queue_capacity: 5 And for train_input_reader: num_readers: 1 queue_capacity: 10 min_after_dequeue: 5 I believe my problem is similar to TensorFlow Object Detection API - Out of Memory but I am using a GPU rather than CPU-only. The images I am training on are comparatively large (2048*2048), however I would like to avoid downsizing as the objects to be detected are quite small. My training set consists of 400 images (in a .tfrecord file). Is there a way to reduce the size of the shuffle buffer to see if this reduces the memory requirement? Traceback INFO:tensorflow:Restoring parameters from ./models/train/model.ckpt-0 INFO:tensorflow:Restoring parameters from ./models/train/model.ckpt-0 INFO:tensorflow:Running local_init_op. INFO:tensorflow:Running local_init_op. INFO:tensorflow:Done running local_init_op. INFO:tensorflow:Done running local_init_op. INFO:tensorflow:Starting Session. INFO:tensorflow:Starting Session. INFO:tensorflow:Saving checkpoint to path ./models/train/model.ckpt INFO:tensorflow:Saving checkpoint to path ./models/train/model.ckpt INFO:tensorflow:Starting Queues. INFO:tensorflow:Starting Queues. INFO:tensorflow:global_step/sec: 0 INFO:tensorflow:…
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/66684498

http://stackoverflow.com/q/51001214
has body: I have two lists: list1 = ['a','d'] list2 = [('a', '1'), ('b', '2'), ('c', '3'), ('d', '4')] I want to either append list1 or create a new list that results in: [('a', '1'), ('d', '4')] I've tried using index with no luck.
has answer: http://stackoverflow.com/a/51001238
has answer: http://stackoverflow.com/a/51001446
score: 0
has comment: http://stackoverflow.com/comment/88996458
has title: Joining common items in python lists
favorite count: 0
has answer: http://stackoverflow.com/a/51001243
answer count: 5
has comment: http://stackoverflow.com/comment/88996346
possible better answer: http://stackoverflow.com/a/51001331
tagged with: python
has answer: http://stackoverflow.com/a/51001331
accepted answer: http://stackoverflow.com/a/51001446
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51001234
upvote count: 1
downvote count: 1
type: Question

http://stackoverflow.com/a/50996216
has comment: http://stackoverflow.com/comment/89045887
answers question: http://stackoverflow.com/q/50996166
type: AcceptedAnswer
type: Answer
has body: If you're just trying to create a subdirectory in every grandchild of the root directory, using os.walk is just going to make things more confusing. I'll explain why, but first, I'll explain the easier way. Just explicitly loop two levels down: for child in os.scandir(current_path): if child.is_dir(): for grandchild in os.scandir(child.path): newpath = os.path.join(grandchild.path, 'new') os.path.mkdir(newpath) Now, why is your existing code broken? walk walks the whole tree. It visits the root, and the children, and the grandchildren, and the great-grandchildren, and even the new grandchildren that you create while you're in the middle of walking. For example, try this: for dirpath, _, _ in os.walk(current_path): print(dirpath) What you get is: . ./Folder b ./Folder b/Folder 2 ./Folder b/Folder 1 ./Folder a ./Folder a/Folder 2 ./Folder a/Folder 1 It's mixing all the different "levels" together. But you don't want to do the same thing at every level. You only want to create new directories in the grandchildren, not the children, and not the great-grandchildren, and especially not any descendants that you create along the way. Sure, you can try to keep track of the level as you go up and down, or you can probably see how you could recreate it on the fly from the dirpath, but why? If you want to do something exactly 2 levels down, don't loop over all levels and then test for level 2, just go 2 levels down.
accepted answer of: http://stackoverflow.com/q/50996166
score: 0

http://stackoverflow.com/comment/88982261
type: AnswerComment
type: Comment
has text: @user2357112 how many end users do you know of that use whitespace in a password?
comment on: http://stackoverflow.com/a/50993207
score: 0

http://stackoverflow.com/comment/88822544
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50906844
has text: In fact I have to connect already installed couchbase with non default port
score: 0

http://stackoverflow.com/q/50985129
has body: What would be the best way to execute command line tools from nodejs to python? I'm working on a app that can generate blockchain certificates. https://github.com/blockchain-certificates/cert-tools This is a python based command line tool, where you can generate blockchain certificates. I have followed the steps and everything is working fine in the virtual env. But now I want to know how to implement this in to a app, where I can run the command line tools external from NodeJS. Is this possible? I have found some libraries where you can run python script from nodejs. Example I have used python shell. Whenever I run the setup script, I get missing file errors. Can someone guide me what the best way will be to solve this problem. Thanks in advance.
tagged with: javascript
score: 0
has title: Executing python command line tools from NodeJS
tagged with: python
tagged with: node.js
tagged with: command
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50985399
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/50985307

http://stackoverflow.com/comment/88764137
comment on: http://stackoverflow.com/q/50880660
type: Comment
type: QuestionComment
score: 0
has text: It's a possibility that the space key is already bound with another listener somewhere in the interface. That could be why you're getting a different effect than you expect

http://stackoverflow.com/comment/88892339
type: Comment
type: QuestionComment
has text: @api55 thank you. i knew good information, because of you. vlc server program is binary file on vlc server pc. so i think that i can't change udp to tcp. i will have to consider how to solve this problem...
score: 0
comment on: http://stackoverflow.com/q/50939323

http://stackoverflow.com/q/50875911
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88754885
has answer: http://stackoverflow.com/a/50876656
type: Question
has body: I want to record video (not audio) from webcam. I have put two buttons for start recording &amp; stop recording. As program starts it pick image from camera &amp; shows on screen.works perfect. My problem is when i click start recording &amp; after some times stop recording, only avi file created ,with 0K or 6K size found. No further recording found. import tkinter import cv2 import PIL.Image, PIL.ImageTk stopb = None class App(): def __init__(self, window, window_title): self.window = window self.window.title = window_title self.ok = False self.video = cv2.VideoCapture(0) self.width = self.video.get(cv2.CAP_PROP_FRAME_WIDTH) self.height = self.video.get(cv2.CAP_PROP_FRAME_HEIGHT) #create videowriter self.fourcc = cv2.VideoWriter_fourcc(*'XVID') self.out = cv2.VideoWriter('output.avi',self.fourcc,10,(640,480)) # Create a canvas that can fit the above video source size self.canvas = tkinter.Canvas(window, width=self.width, height=self.height) self.canvas.pack() self.opencamera = tkinter.Button(window, text="open camera", command=self.open_camera) self.opencamera.pack() self.closecamera = tkinter.Button(window, text="close camera", command=self.close_camera) self.closecamera.pack() self.delay = 10 self.update() # After it is called once, the update method will be automatically called every delay milliseconds self.window.mainloop() def update(self): ret, frame = self.video.read() if self.ok == 'T': self.out.write(frame) if ret: self.photo = PIL.ImageTk.PhotoImage(image=PIL.Image.fromarray(frame)) self.canvas.create_image(0, 0, image=self.photo, anchor=tkinter.NW) self.window.after(self.delay, self.update) def open_camera(self): self.ok = True print("camera opened") print(self.ok) def close_camera(self): print("camera closed") self.ok = False self.video.release() self.out.release() def __del__(self): if self.video.isOpened(): self.video.release() self.out.release() App(tkinter.Tk(), "mywindow")
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/88753834
has comment: http://stackoverflow.com/comment/88754772
has title: webcam recording with python tkinter
tagged with: python
has answer: http://stackoverflow.com/a/67042726

http://stackoverflow.com/comment/88929729
has text: It would be easier to understand if you could give the URL of where the HTML is, or the HTML itself if it can be cut down in size. Use the [edit] button to include it into your question.
comment on: http://stackoverflow.com/q/50964844
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88784243
score: 0
type: Comment
type: QuestionComment
has text: But i don't want to filter it in model . I want filtered it in template
comment on: http://stackoverflow.com/q/50891705

http://stackoverflow.com/comment/88913775
comment on: http://stackoverflow.com/q/50906532
score: 0
has text: Not sure what maybe causing this behavior but fasttext was only built for Linux/MacOS. It requires good C++ support. Check the official [github repo](https://github.com/facebookresearch/fastText#requirements). You can also check out this [answer](https://stackoverflow.com/questions/38817753/make-error-2-on-windows-when-building-fasttext)
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50866072
has body: First transform dates to months: mydf["date"] = mydf["date"].dt.strftime("%Y%m") Then use groupby.agg: def total_type_A(x): return sum(x == "A") def percentage(x): return sum(x == "A") / len(x) mydf.groupby(["date", "state"]).agg([len, total_type_A, percentage])
score: 2
downvote count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/88735166
has comment: http://stackoverflow.com/comment/88762809
type: Answer
has comment: http://stackoverflow.com/comment/88760619
answers question: http://stackoverflow.com/q/50865860

http://stackoverflow.com/comment/92548428
comment on: http://stackoverflow.com/q/50976740
has text: I've just posted a solution to this problem over at https://stackoverflow.com/a/52815347/393652
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/50983760
downvote count: 0
type: Answer
has body: You have two issues: If there is no file (or if it is empty) you would want to have a header line added. If you are appending a new row to an existing file, you are trying to ensure that the last character in your file is a newline. writerow() will add a trailing newline so normally this would not be a problem. If however the file has been manually edited and the trailing newline is missing, this would cause the new row to be appended to the end of the last line. The first issue can be resolved by first testing the size of the file. If it is 0 then it exists but is empty. If the file does not exist, an OSError exception is raised. write_header is used to signal this. The second issue is a bit more tricky. If you open the file in binary mode, it is possible to seek to the last byte of the file and read it in. This can be checked to see if it is a newline. If your file ever used another encoding, this would need to be changed. The file can then be reopened in append mode and the new row written. This can all be done as follows: import csv filename = '/Users/[my name]/Documents/Webscraper/tests/output_sheet_1.csv' bigdict = {'ex_1': 1, 'ex_2': 2, 'ex_3': 3} # Does the file exist? If not (or it is empty) write a header try: write_header = os.path.getsize(filename) == 0 except OSError: write_header = True # If the file exists, does it end with a newline? if write_header: no_ending_newline = False else: with open(filename, 'rb') as f_input: f_input.seek(-1, 2) # move to the last byte of the file no_ending_newline = f_input.read() != b'\n' with open(filename, 'a', newline='') as f_output: fieldnames = ['ex_1','ex_2','ex_3'] csv_writer = csv.DictWriter(f_output, fieldnames=fieldnames) if write_header: csv_writer.writeheader() if no_ending_newline: f_output.write('\n') csv_writer.writerow(bigdict)
upvote count: 1
answers question: http://stackoverflow.com/q/50979628
score: 1

http://stackoverflow.com/comment/88768909
type: AnswerComment
type: Comment
has text: @Glu, you can expriment with `df['name'].str.contains('\*$')` too.
comment on: http://stackoverflow.com/a/50883349
score: 0

http://stackoverflow.com/comment/88793382
score: 0
comment on: http://stackoverflow.com/q/50896798
type: Comment
type: QuestionComment
has text: It doesn't raise a specific error, however here is the traceback: File C:\Users..... line 337, in _get_more_data assert left > 0 AssertionError Hope this is helpful..

http://stackoverflow.com/comment/88768750
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/50883285
type: Comment
has text: If you're just using fixed strings like this, there's no reason to use regex; just string operations.

http://stackoverflow.com/q/50978944
tagged with: scikit-learn
accepted answer: http://stackoverflow.com/a/50979022
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50979022
type: Question
has body: I have a dataset that I am trying to run a logistic regression on using sklearn, but the dataset has NaNs which cause problems. Most of the questions I see online deal with imputing the missing values. However, I don't feel comfortable imputing the missing values. Is there a way to drop all the NaN values in the dataframe or to include only the rows where there is no NaN in all the columns? I ended up creating a new dataframe keep only the rows that have answers in all columns. df2 = df1[(df1['var1']&gt;=0) &amp; (df1['var2']&gt;=0) &amp; (df1['var3']&gt;=0)] But what if I have 100 columns. What's the best and simplest way to do this?
has title: NaN causing sklearn model to not run
score: 0
possible better answer: http://stackoverflow.com/a/50979041
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/50979041

http://stackoverflow.com/a/50879659
has comment: http://stackoverflow.com/comment/88826447
has comment: http://stackoverflow.com/comment/88808372
downvote count: 0
has comment: http://stackoverflow.com/comment/88812289
has comment: http://stackoverflow.com/comment/88826459
type: Answer
answers question: http://stackoverflow.com/q/50878134
score: 1
upvote count: 1
has body: I believe that the problem is that you shouldn't have the following line: Py_INCREF(pValue) The reason is that PyObject_CallMethod has already incremented the reference count for you. If you do the extra Py_INCREF call the reference count for the given PyObject will never go to 0. According to the documentation, PyObject_CallMethod returns a new reference. To understand the meaning of "new reference", as opposed to "borrowed reference" look at the first paragraph of the Reference Count Details section of the documentation:

http://stackoverflow.com/a/50866495
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/50865953
has body: If missing quotation marks are the only problem with the text and there are no escaped quotation marks within the fields, then you can repair the text by looking for the four types of irregularities. s = '{name":"John","last" : Doe", "Food:"Fries","Coffee" : "Need}' A missing quotation mark after a semicolon: s = re.sub('"\s*:\s*(?=[^\s"])', '":"', s) A missing quotation mark before a semicolon: s = re.sub('(?&lt;=[^\s"])\s*:\s*"', '":"', s) A missing quotation mark before the closing brace: s = re.sub('(?&lt;=[^\s"])\s*\}', '"}', s) A missing quotation mark after the opening brace: s = re.sub('\{\s*(?=[^\s"])', '{"', s) Apply all four transformations one after another, and hopefully the problem is gone: print(s) #{"name":"John","last":"Doe", "Food":"Fries","Coffee" : "Need"}
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50865953
type: Answer

http://stackoverflow.com/comment/89533721
type: Comment
has text: @Schnick - Please check solution now.
comment on: http://stackoverflow.com/a/51277799
score: 0
type: AnswerComment

http://stackoverflow.com/q/50874219
accepted answer: http://stackoverflow.com/a/50874944
type: AnsweredQuestion
upvote count: 1
type: Question
has body: I'm trying to change a cell format to horizontal alignment for the text. Can't get it to work. Here is my code so far. data={ "requests":[ { "horizontalAlignment": { 'range': { "sheetId": sheetId, "startRowIndex": 0, "endRowIndex": 10, "startColumnIndex": 0, "endColumnIndex": 1 }, 'Center' } } ] } result = g.service.spreadsheets().batchUpdate(spreadsheetId=key, body=data).execute() not sure how to specify the range in there with the horizontal alignment.
tagged with: google-sheets-api
answer count: 2
has title: google sheets horizontal alignment
has answer: http://stackoverflow.com/a/50874944
downvote count: 0
score: 1
possible better answer: http://stackoverflow.com/a/58836581
favorite count: 0
has answer: http://stackoverflow.com/a/58836581
tagged with: python

http://stackoverflow.com/a/50966921
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88930440
accepted answer of: http://stackoverflow.com/q/50966579
answers question: http://stackoverflow.com/q/50966579
type: Answer
has body: Here's one approach - def reduced_box(a): # Store shape info M,N = a.shape # Mask of valid places in the array mask = a!=0 # Get boolean array with at least a valid one per row m_col = mask.any(1) # Get the starting and ending valid rows with argmax. # More info : https://stackoverflow.com/a/47269413/ r0,r1 = m_col.argmax(), M-m_col[::-1].argmax() # Repeat for cols m_row = mask.any(0) c0,c1 = m_row.argmax(), N-m_row[::-1].argmax() # Finally slice with the valid indices as the bounding box limits return a[r0:r1,c0:c1] Sample run - In [210]: a Out[210]: array([[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 4, 1, 0, 2, 0, 4, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 4, 0, 1, 0, 0, 0], [0, 0, 0, 4, 0, 0, 4, 3, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]]) In [211]: reduced_box(a) Out[211]: array([[4, 1, 0, 2, 0, 4], [0, 0, 0, 0, 0, 0], [1, 4, 0, 1, 0, 0], [0, 4, 0, 0, 4, 3]])
has comment: http://stackoverflow.com/comment/88930297
score: 2
downvote count: 0
upvote count: 2

http://stackoverflow.com/comment/88864706
comment on: http://stackoverflow.com/q/50932336
has text: What do you mean by `tag`? Node labels can be created with `networkx.draw_networkx_node_labels`, IIRC.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88774516
score: 0
type: Comment
has text: you want to say that instead of `ac_name = 'ac'` you want to search `col = ['ab', 'ac']` ?
type: AnswerComment
comment on: http://stackoverflow.com/a/50886124

http://stackoverflow.com/q/50956686
accepted answer: http://stackoverflow.com/a/50956773
has title: Recycling in Pandas Dataframe
tagged with: python
score: 11
has answer: http://stackoverflow.com/a/50956773
has body: When filling an array with values from a shorter array in R, R will "recycle" the elements in the shorter array. For example, setting an array of length 7 [ , , , , , , ] with the array ['a','b','c'] will give ['a','b','c','a','b','c','a']. Is there a built-in method to fill a pandas column (or numpy array) using a similar style of recycling?
type: AnsweredQuestion
tagged with: list
downvote count: 0
has answer: http://stackoverflow.com/a/50956732
type: Question
tagged with: numpy
answer count: 2
upvote count: 11
favorite count: 0
tagged with: pandas
possible better answer: http://stackoverflow.com/a/50956732

http://stackoverflow.com/a/50990953
score: 2
downvote count: 0
upvote count: 2
has body: compare = [i or '.' for i in compare]
type: Answer
answers question: http://stackoverflow.com/q/50990874

http://stackoverflow.com/comment/88921832
has text: And for the records, multiple write locks are possible on a file.
comment on: http://stackoverflow.com/a/50962175
type: AnswerComment
score: 0
type: Comment

pygame
tags question: http://stackoverflow.com/q/50917702
tags question: http://stackoverflow.com/q/50950046
tags question: http://stackoverflow.com/q/50863654
tags question: http://stackoverflow.com/q/50919315
tags question: http://stackoverflow.com/q/50868499
tags question: http://stackoverflow.com/q/50941727
tags question: http://stackoverflow.com/q/50859819
tags question: http://stackoverflow.com/q/50885142
tags question: http://stackoverflow.com/q/51006375
tags question: http://stackoverflow.com/q/50958642
tags question: http://stackoverflow.com/q/50939298
tags question: http://stackoverflow.com/q/50960031
tags question: http://stackoverflow.com/q/50900226
tag name: pygame
tags question: http://stackoverflow.com/q/50900422
tags question: http://stackoverflow.com/q/50910912
tags question: http://stackoverflow.com/q/50978669
tags question: http://stackoverflow.com/q/50886888
tags question: http://stackoverflow.com/q/50991358
tags question: http://stackoverflow.com/q/50933935
tags question: http://stackoverflow.com/q/50884426
tags question: http://stackoverflow.com/q/51006279
tags question: http://stackoverflow.com/q/50956897
tags question: http://stackoverflow.com/q/50945295
tags question: http://stackoverflow.com/q/50954786
tags question: http://stackoverflow.com/q/50976841
tags question: http://stackoverflow.com/q/51000165
tags question: http://stackoverflow.com/q/50966406
type: Tag
tags question: http://stackoverflow.com/q/50886896

http://stackoverflow.com/comment/88824915
has text: Is there any difference between `ast.literal_eval` and plain `eval`?
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50912448

http://stackoverflow.com/comment/88774211
comment on: http://stackoverflow.com/q/50876767
type: QuestionComment
type: Comment
score: 1
has text: Although I'm not sure whether this is what you want, how about ``res = [e['body']['size'] for e in message['payload']['parts']]`` or ``res = [e['body']['data'] for e in message['payload']['parts']]``? ``message`` is from your snippet.

file
type: Tag
tags question: http://stackoverflow.com/q/50937567
tags question: http://stackoverflow.com/q/50863778
tags question: http://stackoverflow.com/q/50924879
tag name: file
tags question: http://stackoverflow.com/q/50958510
tags question: http://stackoverflow.com/q/50897121
tags question: http://stackoverflow.com/q/50889570
tags question: http://stackoverflow.com/q/50958584
tags question: http://stackoverflow.com/q/50862015
tags question: http://stackoverflow.com/q/51009492
tags question: http://stackoverflow.com/q/50939381
tags question: http://stackoverflow.com/q/50948075
tags question: http://stackoverflow.com/q/50961538
tags question: http://stackoverflow.com/q/50873711
tags question: http://stackoverflow.com/q/50976390
tags question: http://stackoverflow.com/q/50998481
tags question: http://stackoverflow.com/q/50899359
tags question: http://stackoverflow.com/q/51000606
tags question: http://stackoverflow.com/q/50965175
tags question: http://stackoverflow.com/q/50947718
tags question: http://stackoverflow.com/q/50940661
tags question: http://stackoverflow.com/q/50932925

http://stackoverflow.com/comment/88978119
has text: the way is worked for the image but the width of the background-image is not changed .
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50974932

http://stackoverflow.com/comment/88861397
type: QuestionComment
comment on: http://stackoverflow.com/q/50931196
has text: This sounds like a better fit for subclassing. (And note that decorator in Python means something different; better to refer to this as a wrapper.)
score: 0
type: Comment

http://stackoverflow.com/comment/88734653
comment on: http://stackoverflow.com/a/50866115
has text: Locates the timestamp pattern `r'(\d{2}\:\d{2}\:\d{2})'` and replaces it with the matched pattern with a comma after `r'\1,'`.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89149761
score: 0
type: AnswerComment
type: Comment
has text: Then replace `{"test_key":"test_value"}` dict with some text as `"some text"`
comment on: http://stackoverflow.com/a/50924550

http://stackoverflow.com/comment/88723719
has text: Is that your question? Then you should say so.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50860461

http://stackoverflow.com/comment/90027340
comment on: http://stackoverflow.com/a/50886262
type: AnswerComment
score: 0
type: Comment
has text: @JonathanFarrow (re: shuffling) either one works, posting as another thread is probably what is expected on the site but I don't mind either way. (re: brackets to accept multiple answers) you could do that, but then you'd want to enclose *all* answers in brackets (even single-accepted-answer questions), otherwise your tests would fail for those cases.

http://stackoverflow.com/comment/88718939
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50857672
score: 0
has text: i already posted, exactly variable soup doesn't have full content of the HTML page

http://stackoverflow.com/a/56992964
has body: pip install pyyaml This should serve the purpose
score: 347
type: Answer
downvote count: 4
upvote count: 351
has comment: http://stackoverflow.com/comment/124836965
has comment: http://stackoverflow.com/comment/110426727
has comment: http://stackoverflow.com/comment/118035475
answers question: http://stackoverflow.com/q/50868322

http://stackoverflow.com/a/53554026
type: Answer
answers question: http://stackoverflow.com/q/50904444
score: 0
has body: You could use the function from_records() splitting each string item in the input list and taking care of the fact that the first line of your data contains the columns' labels &gt;&gt;&gt; data = ['Timestamp;T;Pressure [bar];Input line pressure [bar];Speed \ [rpm];Angular Position [degree];Wheel speed [rpm];Wheel angular position [degree];', \ ';1;5,281;5,303;219,727;10,283;216,363;45;', \ ';1;5,273;5,277;219,727;11,602;216,363;45;', \ ';1;5,288;5,293;205,078;12,832;216,363;45;', \ ';1;5,316;5,297;219,727;14,15;216,363;45;', \ ';1;5,314;5,307;219,727;15,469;216,363;45;', \ ';1;5,288;5,3;219,727;16,787;216,363;45;', \ ';1;5,318000000000001;5,31;219,727;18,105;216,363;45;', \ ';1;5,304;5,3;219,727;19,424;216,388;56,25;', \ ';1;5,291;5,29;219,947;20,742;216,388;56,25;', \ ';1;5,316;5,297;219,507;22,061;216,388;56,25;'] &gt;&gt;&gt; df = pd.DataFrame.from_records([r.split(';') for r in data[1:]], columns=data[0].split(';')) &gt;&gt;&gt; df Timestamp T Pressure [bar] Input line pressure [bar] Speed [rpm] \ 0 1 5,281 5,303 219,727 1 1 5,273 5,277 219,727 2 1 5,288 5,293 205,078 3 1 5,316 5,297 219,727 4 1 5,314 5,307 219,727 5 1 5,288 5,3 219,727 6 1 5,318000000000001 5,31 219,727 7 1 5,304 5,3 219,727 8 1 5,291 5,29 219,947 9 1 5,316 5,297 219,507 ...

http://stackoverflow.com/a/66966265
answers question: http://stackoverflow.com/q/50951955
has body: for me it worked by putting single quote pytesseract.pytesseract.tesseract_cmd =r'C:/Program Files/Tesseract-OCR/tesseract.exe' actually putting inside double quotes was automatically inserting unwanted chracter
downvote count: 0
type: Answer
score: 3
upvote count: 3

http://stackoverflow.com/comment/88884494
score: 0
comment on: http://stackoverflow.com/a/50942748
type: Comment
has text: It worked. However, the number of bins is messing up the text in the top of them. I will try different font sizes and alignments to try to minimize this issue. Thank you so much.
type: AnswerComment

http://stackoverflow.com/comment/88732919
comment on: http://stackoverflow.com/a/50865014
has text: `__init__` and `__repr__` are methods that define how instances of the class are initialized and represented when printed, respectively. Here's some reading about [magic methods](https://rszalski.github.io/magicmethods/). And the reason that `self` is a parameter in class methods is that when you call them using `<instance>.<method>()`, the instance gets passed in as the first argument -- so you can access instance variables and other methods. 500 characters isn't really enough to explain all the nuances there but feel free to ask more questions in chat.
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/a/50930250
answers question: http://stackoverflow.com/q/50930190
downvote count: 0
has comment: http://stackoverflow.com/comment/88859938
accepted answer of: http://stackoverflow.com/q/50930190
has comment: http://stackoverflow.com/comment/88859672
has comment: http://stackoverflow.com/comment/88859567
score: 9
has comment: http://stackoverflow.com/comment/88859871
has comment: http://stackoverflow.com/comment/88859761
has comment: http://stackoverflow.com/comment/88859856
type: AcceptedAnswer
upvote count: 9
has comment: http://stackoverflow.com/comment/88859676
type: Answer
has body: Use pd.DataFrame.applymap to take care of data. Use pd.DataFrame.rename to take care of column names. df.applymap(str.strip).rename(columns=str.strip) A B C 0 1 2 3 1 4 5 6 7 2 8 9 1 0 To account for that little quote guy f = lambda x: "'" + x.strip("'").strip() + "'" df.applymap(f).rename(columns=f) 'A' 'B' 'C' 0 '1' '2' '3' 1 '4' '5 6' '7' 2 '8' '9' '1 0'

http://stackoverflow.com/q/50872498
type: AnsweredQuestion
has body: From the Python 3.7 changelog: the insertion-order preservation nature of dict objects has been declared to be an official part of the Python language spec. Would this mean that OrderedDict will become redundant? The only use I can think of it will be to maintain backwards compatibility with older versions of Python which don't preserve insertion-order for normal dictionaries.
linked to: http://stackoverflow.com/q/39980323
type: Question
accepted answer: http://stackoverflow.com/a/50872567
has comment: http://stackoverflow.com/comment/105705020
tagged with: python-3.7
has title: Will OrderedDict become redundant in Python 3.7?
downvote count: 0
answer count: 1
upvote count: 142
tagged with: ordereddict
favorite count: 0
tagged with: python-3.x
linked to: http://stackoverflow.com/q/34305003
score: 142
has answer: http://stackoverflow.com/a/50872567
linked to: http://stackoverflow.com/q/49159238
tagged with: python
tagged with: dictionary

http://stackoverflow.com/a/50871050
downvote count: 0
has comment: http://stackoverflow.com/comment/103299202
type: Answer
score: 15
answers question: http://stackoverflow.com/q/50870405
has body: You can use this solution. It makes the job -> croping + zoom + array up and array down. import cv2 def show_webcam(mirror=False): scale=10 cam = cv2.VideoCapture(0) while True: ret_val, image = cam.read() if mirror: image = cv2.flip(image, 1) #get the webcam size height, width, channels = image.shape #prepare the crop centerX,centerY=int(height/2),int(width/2) radiusX,radiusY= int(scale*height/100),int(scale*width/100) minX,maxX=centerX-radiusX,centerX+radiusX minY,maxY=centerY-radiusY,centerY+radiusY cropped = image[minX:maxX, minY:maxY] resized_cropped = cv2.resize(cropped, (width, height)) cv2.imshow('my webcam', resized_cropped) if cv2.waitKey(1) == 27: break # esc to quit #add + or - 5 % to zoom if cv2.waitKey(1) == 0: scale += 5 # +5 if cv2.waitKey(1) == 1: scale = 5 # +5 cv2.destroyAllWindows() def main(): show_webcam(mirror=True) if __name__ == '__main__': main()
upvote count: 15
has comment: http://stackoverflow.com/comment/110610167
accepted answer of: http://stackoverflow.com/q/50870405
type: AcceptedAnswer

http://stackoverflow.com/a/51002447
answers question: http://stackoverflow.com/q/50997512
score: 3
upvote count: 3
has body: Depending on how your data is stored, you can do a number of things. Assuming your months are stored in a column of time-stamps, you can do something like this, using the month TimeUnit to extract just the month from the time-stamp: import pandas as pd import altair as alt df = pd.DataFrame({'months': pd.date_range('2018-01-01', periods=12, freq='M'), 'Difference': [7552, 8080, 7707, 7718, 13895, 14423, 14375, 11898, 12326, 12211, 12739, 12927]}) alt.Chart(df).mark_line().encode( x='month(months):T', y='Difference' )
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50997512
type: Answer

http://stackoverflow.com/comment/88887785
has text: Alright, I will check it out. The network works smoothly with MNIST (I just import it from pytorch framework), so I am pretty sure it is my dataloader but I am not seeing it.
comment on: http://stackoverflow.com/a/50930566
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/50963499
type: UnansweredQuestion
tagged with: python
has body: With the code def myfunction(): myfunction.counter += 1 myfunction.counter = 0 from https://stackoverflow.com/a/21717084/2729627 you can keep track of the number of times the function is called. But how do I keep track of the number of times a function is called when (one of) its input arguments takes on a certain value? So for instance def myfunction(a): # Do some calculations... b = a**2 # Increase counter for specific value of 'a'. myfunction.counter[a] += 1 # Return output argument. return b myfunction.counter[5] = 0 myfunction.counter[79648763] = 0 print(myfunction.counter[5]) print(myfunction.counter[79648763]) myfunction(5) myfunction(79648763) myfunction(79648763) print(myfunction.counter[5]) # Should return 1. print(myfunction.counter[79648763]) # Should return 2. How should I modify this code to get it to work?
score: 1
upvote count: 1
has title: Count number of function calls for distinct input argument values
has answer: http://stackoverflow.com/a/50963601
type: Question
linked to: http://stackoverflow.com/q/21716940
downvote count: 0
answer count: 1
favorite count: 0

http://stackoverflow.com/a/50950493
downvote count: 0
has comment: http://stackoverflow.com/comment/88898862
upvote count: 2
has body: Using workerid and a list comprehension it would be: a=np.array(self.a) ids=np.unique(a[:,0]) #array of unique ids pos_mean=[np.mean(a[a[:,0]==i, 1:], axis=0) for i in ids] But considering there always seem to be 3 consecutive measurements, there should be a relatively easy way to vectorize it
type: Answer
score: 2
answers question: http://stackoverflow.com/q/50950231

http://stackoverflow.com/q/50856563
tagged with: discord.py
possible better answer: http://stackoverflow.com/a/50907680
has title: How to Start a Loop Infinitely
has answer: http://stackoverflow.com/a/50907680
has comment: http://stackoverflow.com/comment/88719383
score: 0
accepted answer: http://stackoverflow.com/a/50856677
has comment: http://stackoverflow.com/comment/88715557
answer count: 2
has body: My Experience So I'm creating Discord bots to help teach me how to program Python, and programming in general. What I know about programming is mostly from an AP Computer Science Principles I took this High School Year (I'm gonna be a Junior in High School after summer). In the course we created apps with with MIT App Inventor which literally lets you make apps with blocks of Pseudocode. We learned binary, bits, bytes, parity bits, some search and sort algorithms, loops (index and stuff), variables, procedures (pretty much functions), and that's pretty much it. I used to learn C# game dev off of a course by copying them mostly but gave a little after when I decided I wanna pursue a career in Software Engineering What I'm looking for I was trying to make a for loop or somekind of loop just to experiment and maybe use it later. Mostly to find out the syntax of it and what I would write everytime I would include it. # LearnBot by George D # Libraries and stuff to import import discord from discord.ext import commands from discord.ext.commands import Bot import asyncio import chalk import time # Variables and initiate related code bot = commands.Bot(command_prefix='$') i = 1 # This variable is super simple yet very important varTest = 8 charTest = 'Code' nullTest = None timeTestDelay = .5 while i&gt;0: await bot.say("This is a for loop test, so It's gonna be annoying!") time.sleep(1.5) i=i+1 print (i) Any help is appreciated :)
has comment: http://stackoverflow.com/comment/88716029
favorite count: 0
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50856677
tagged with: loops
upvote count: 1
downvote count: 1
type: Question
tagged with: indexing

http://stackoverflow.com/comment/88922351
type: Comment
comment on: http://stackoverflow.com/a/50957321
has text: Thank you for your speedy reply!
score: 0
type: AnswerComment

http://stackoverflow.com/comment/93314899
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50863516
has text: Possible duplicate of [Download Kaggle Dataset by using Python](https://stackoverflow.com/questions/49386920/download-kaggle-dataset-by-using-python)
score: 0

http://stackoverflow.com/a/50877342
accepted answer of: http://stackoverflow.com/q/50877281
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50877281
score: 3
upvote count: 3
has body: You have to escape the * character using \, as it is being read as the special regex character * (meaning zero or more). In your case: df[~df['title'].str.contains('\*\*')] Example: &gt;&gt;&gt; df title 0 xyz 1 x**yz 2 ** 3 x* df[~df['title'].str.contains('\*\*')] title 0 xyz 3 x*

http://stackoverflow.com/q/50956810
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
score: 3
has body: I need to check whether arrow keys are being pressed on the PC and do something while it is being held down. For example if: if arrow up is held down the console will print: up,up,up,up.. -until released. How can i do that? I tried some libraries but every one seems to only register a click but not a repeated hold.. Thank you!
upvote count: 3
has answer: http://stackoverflow.com/a/50956973
has answer: http://stackoverflow.com/a/50956894
type: Question
possible better answer: http://stackoverflow.com/a/50956894
answer count: 2
accepted answer: http://stackoverflow.com/a/50956973
has title: How can i check for a keyhold in python
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/88897047
has text: can you edit your question to include sample data of the csv? also include the headers of the column and your desired output.
comment on: http://stackoverflow.com/q/50936747
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50980661
linked to: http://stackoverflow.com/q/437589
has title: python linkedin learning course download
downvote count: 4
upvote count: 0
answer count: 1
favorite count: 0
has body: I got an isssue while executing the script python lld.py to download linkedin course for offline use C:\Users\Srilokan\Downloads\linkedin>python lld.py Traceback (most recent call last): File "lld.py", line 13, in reload(sys) NameError: name 'reload' is not defined I have taken this code from https://github.com/mclmza/linkedin-learning-downloader Please rectify the error
has answer: http://stackoverflow.com/a/50980978
type: UnansweredQuestion
score: -4
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/88957194
tagged with: linkedin-api

http://stackoverflow.com/comment/88845313
has text: Don't put your attempts in the comments, put it in your original question
score: 1
comment on: http://stackoverflow.com/q/50922326
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88758130
comment on: http://stackoverflow.com/a/50877894
type: Comment
has text: Sure Thanks! Will try both ways!
score: 0
type: AnswerComment

http://stackoverflow.com/q/50992374
tagged with: python
has comment: http://stackoverflow.com/comment/89281530
answer count: 0
type: UnansweredQuestion
score: 1
upvote count: 1
tagged with: namespaces
type: Question
has title: Rdflib namespaces - how to avoid 'Can't split URI' error?
has comment: http://stackoverflow.com/comment/90769219
tagged with: rdflib
has body: I would like to define my own namespace "http://example.org/" in rdflib, but apparently that can't be done. Can't figure out what is the proper way to do it... In [1]: import rdflib INFO:rdflib:RDFLib Version: 4.2.2 In [2]: g = rdflib.Graph() In [3]: from rdflib import Namespace In [4]: n1 = Namespace("http://example.org/") In [5]: u1 = n1['1'] In [6]: u1 Out[6]: rdflib.term.URIRef(u'http://example.org/1') In [7]: g.bind('ex', n1) In [8]: g.add((u1, u1, u1) ...: ) In [9]: g.serialize() --------------------------------------------------------------------------- Exception Traceback (most recent call last) &lt;ipython-input-9-25a09aa9a7b5&gt; in &lt;module&gt;() ----&gt; 1 g.serialize() /usr/local/lib/python2.7/site-packages/rdflib/graph.pyc in serialize(self, destination, format, base, encoding, **args) 937 if destination is None: 938 stream = BytesIO() --&gt; 939 serializer.serialize(stream, base=base, encoding=encoding, **args) 940 return stream.getvalue() 941 if hasattr(destination, "write"): /usr/local/lib/python2.7/site-packages/rdflib/plugins/serializers/rdfxml.pyc in serialize(self, stream, base, encoding, **args) 64 # assert( 65 # namespaces["http://www.w3.org/1999/02/22-rdf-syntax-ns#"]=='rdf') ---&gt; 66 bindings = list(self.__bindings()) 67 bindings.sort() 68 /usr/local/lib/python2.7/site-packages/rdflib/plugins/serializers/rdfxml.pyc in __bindings(self) 31 32 for predicate in set(store.predicates()): ---&gt; 33 prefix, namespace, name = nm.compute_qname(predicate) 34 bindings[prefix] = URIRef(namespace) 35 /usr/local/lib/python2.7/site-packages/rdflib/namespace.pyc in compute_qname(self, uri, generate) 328 329 if not uri in self.__cache: --&gt; 330 namespace, name = split_uri(uri) 331 namespace = URIRef(namespace) 332 prefix = self.store.prefix(namespace) /usr/local/lib/python2.7/site-packages/rdflib/namespace.pyc in split_uri(uri) 500 return (ns, ln) 501 break --&gt; 502 raise Exception("Can't split '%s'" % uri) Exception: Can't split 'http://example.org/…
downvote count: 0
favorite count: 0

django
tags question: http://stackoverflow.com/q/50986813
tags question: http://stackoverflow.com/q/50870950
tags question: http://stackoverflow.com/q/50913391
tags question: http://stackoverflow.com/q/50951338
tags question: http://stackoverflow.com/q/50893335
tags question: http://stackoverflow.com/q/50976330
tags question: http://stackoverflow.com/q/51010999
tags question: http://stackoverflow.com/q/50898193
tags question: http://stackoverflow.com/q/50909393
tags question: http://stackoverflow.com/q/50915625
tags question: http://stackoverflow.com/q/50970582
tags question: http://stackoverflow.com/q/50917685
tags question: http://stackoverflow.com/q/50857631
tags question: http://stackoverflow.com/q/51001598
tags question: http://stackoverflow.com/q/50871526
tags question: http://stackoverflow.com/q/50981884
tags question: http://stackoverflow.com/q/50866961
tags question: http://stackoverflow.com/q/50993624
tags question: http://stackoverflow.com/q/50888049
tags question: http://stackoverflow.com/q/50954741
tags question: http://stackoverflow.com/q/50867343
tags question: http://stackoverflow.com/q/50860932
tags question: http://stackoverflow.com/q/50977361
tags question: http://stackoverflow.com/q/50950009
tags question: http://stackoverflow.com/q/50879154
tags question: http://stackoverflow.com/q/50900153
tags question: http://stackoverflow.com/q/50997115
tags question: http://stackoverflow.com/q/50870442
tags question: http://stackoverflow.com/q/50865739
tags question: http://stackoverflow.com/q/50892254
tags question: http://stackoverflow.com/q/51006771
tags question: http://stackoverflow.com/q/50916493
tags question: http://stackoverflow.com/q/50861076
tags question: http://stackoverflow.com/q/50858231
tags question: http://stackoverflow.com/q/50867953
tags question: http://stackoverflow.com/q/50946055
tags question: http://stackoverflow.com/q/50877963
tags question: http://stackoverflow.com/q/50892879
tags question: http://stackoverflow.com/q/51000385
tags question: http://stackoverflow.com/q/50931337
tags question: http://stackoverflow.com/q/50878551
tags question: http://stackoverflow.com/q/50866421
tags question: http://stackoverflow.com/q/50867947
tags question: http://stackoverflow.com/q/50888014
tags question: http://stackoverflow.com/q/50966180
type: Tag
tags question: http://stackoverflow.com/q/50955863
tags question: http://stackoverflow.com/q/50916730
tags question: http://stackoverflow.com/q/50920598
tags question: http://stackoverflow.com/q/50865974
tags question: http://stackoverflow.com/q/50895643
tags question: http://stackoverflow.com/q/50956539
tags question: http://stackoverflow.com/q/50893756
tags question: http://stackoverflow.com/q/51008494
tags question: http://stackoverflow.com/q/50921502
tags question: http://stackoverflow.com/q/50947137
tags question: http://stackoverflow.com/q/50929437
tags question: http://stackoverflow.com/q/50971705
tags question: http://stackoverflow.com/q/50862127
tags question: http://stackoverflow.com/q/50925513
tags question: http://stackoverflow.com/q/50870824
tags question: http://stackoverflow.com/q/50968724
tags question: http://stackoverflow.com/q/50954875
tags question: http://stackoverflow.com/q/50982334
tags question: http://stackoverflow.com/q/50938369
tags question: http://stackoverflow.com/q/50926614
tags question: http://stackoverflow.com/q/50982757
tags question: http://stackoverflow.com/q/50972222
tags question: http://stackoverflow.com/q/50930821
tags question: http://stackoverflow.com/q/50969522
tags question: http://stackoverflow.com/q/50956139
tags question: http://stackoverflow.com/q/50923553
tags question: http://stackoverflow.com/q/50993171
tags question: http://stackoverflow.com/q/50870978
tags question: http://stackoverflow.com/q/50946723
tags question: http://stackoverflow.com/q/50915911
tags question: http://stackoverflow.com/q/51008710
tags question: http://stackoverflow.com/q/50967854
tags question: http://stackoverflow.com/q/50918382
tags question: http://stackoverflow.com/q/50866574

http://stackoverflow.com/comment/88789144
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50894497
has text: @Chris Thanks for your reply, what is the main advantage of Py2App? (I was planning on using it yesterday, but I found platypus way easier)

http://stackoverflow.com/comment/89088027
type: AnswerComment
type: Comment
has text: @SonaliJain It may be better to ask another question rather than change your question once someone provided a satisfactory answer.
comment on: http://stackoverflow.com/a/51012830
score: 0

http://stackoverflow.com/q/50905066
answer count: 1
accepted answer: http://stackoverflow.com/a/50905165
tagged with: python
tagged with: regex
downvote count: 4
has answer: http://stackoverflow.com/a/50905165
favorite count: 0
upvote count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88809963
score: -4
has title: What is the regular expression to match the string after id= in python
type: AnsweredQuestion
type: Question
has body: I am trying to match the string after id= from the below selenium exception so that I can use it in a ui pop up to tell the user which is the attribute causing error. selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: [id="dragg"] In this case I am expecting the regex to return dragg I am not able to create a good regex pattern to match this. Can anyone help?

http://stackoverflow.com/q/50921241
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88841997
has comment: http://stackoverflow.com/comment/88843468
type: Question
has title: multiply the numbers in a specific column by factor of 3
has answer: http://stackoverflow.com/a/50922125
tagged with: numpy
score: 0
answer count: 1
has body: I want to multiply all the numbers in a specific column (z column in the following input file xyz.txt) by factor of 3 and output it in a in text file. When I run ./script.py xyz.txt &gt; output.txt I get this error: Traceback (most recent call last): File "./script.py", line 23, in sys.exit(main(sys.argv)) File "./script.py", line 18, in main result.append(z.split(' ')[2]*3) IndexError: list index out of range Do you know how I can fix this error? script.py: #!/usr/bin/env python3 def main(argv): inputfile = open(argv[1]) line = inputfile.readline() while line: print(line, end="") if line.startswith('[ xyz ]'): break line = inputfile.readline() result=[] for z in line: result.append(z.split(' ')[2]*3) print(z.rstrip(), '; modified') if __name__ == "__main__": import sys sys.exit(main(sys.argv)) Input file xyz.txt: [ xyz ] ; x y z 1.5 3.5 6.3 2.4 4.2 2.4 3.2 8.9 8.9 4.3 2.1 9.2 5.4 6.3 3.5 Requested output file output.txt: [ xyz ] ; x y z 1.5 3.5 18.9 ; modified 2.4 4.2 7.2 ; modified 3.2 8.9 26.7 ; modified 4.3 2.1 27.6 ; modified 5.4 6.3 10.5 ; modified
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88841983

http://stackoverflow.com/a/50878944
has body: Using dict Ex: d1 = {'user1': 5, 'user2': 50, 'user3': 75, 'user4': 100} d2 = {5: 1, 50: 2, 75: 3, 100: 4} print( dict((k,d2[v]) for k, v in d1.items() ) ) Output: {'user4': 4, 'user2': 2, 'user3': 3, 'user1': 1}
answers question: http://stackoverflow.com/q/50878915
has comment: http://stackoverflow.com/comment/88759938
type: Answer
upvote count: 1
downvote count: 1
score: 0

http://stackoverflow.com/comment/88862981
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50929997
has text: @user1058210 make sense, and what would you like in this case? if you want 0, I think you can try: `new_dfp['Stock'] = new_dfp.groupby('Product')['Stock'].ffill().fillna(0).astype(int)` like this, the one not filled by `ffill` should end up to be 0
score: 0

http://stackoverflow.com/q/50857701
has title: scapy no answer to fragmented tcp get
tagged with: python
tagged with: scapy
type: Question
has answer: http://stackoverflow.com/a/50889341
has body: I am trying to make a quick TCP connection with scapy. in this scenario I will be using HTTP and I expect the server to redirect me and close the connection. and this works for the most part. after opening the connection, I send a HTTP GET and get a redirect reply. But now I want to fragment my get. I used scapy's fragment method to split the payload and I am sending each of them out. I captured the sequence with tshark and everything looks fine: Capturing on eth1 0.000000 10.80.0.8 -&gt; 30.0.0.1 TCP 40823 &gt; http [SYN] Seq=0 Win=8192 Len=0 0.003022 30.0.0.1 -&gt; 10.80.0.8 TCP http &gt; 40823 [SYN, ACK] Seq=0 Ack=0 Win=2048 Len=0 MSS=1024 0.020846 10.80.0.8 -&gt; 30.0.0.1 TCP 40823 &gt; http [ACK] Seq=0 Ack=1 Win=8192 Len=0 0.042347 10.80.0.8 -&gt; 30.0.0.1 IP Fragmented IP protocol (proto=TCP 0x06, off=0) 0.562284 10.80.0.8 -&gt; 30.0.0.1 IP Fragmented IP protocol (proto=TCP 0x06, off=16) 1.079767 10.80.0.8 -&gt; 30.0.0.1 IP Fragmented IP protocol (proto=TCP 0x06, off=32) 1.599802 10.80.0.8 -&gt; 30.0.0.1 HTTP GET /index.php HTTP/1.1 1.603175 30.0.0.1 -&gt; 10.80.0.8 TCP http &gt; 40823 [ACK] Seq=1 Ack=44 Win=2048 Len=0 1.603245 30.0.0.1 -&gt; 10.80.0.8 HTTP HTTP/1.1 302 Moved temporarily 3.648274 30.0.0.1 -&gt; 10.80.0.8 HTTP [TCP Retransmission] HTTP/1.1 302 Moved temporarily The way I send my packets in scapy is using srp(pkt,timeout=0.5,multi=1). but this seems like it does not work with IP fragments as it does not find a response to the final fragment being send, despite there being 3 (ACK, redirect and retransmit) Scapy will print: Begin emission: Finished to send 1 packets. .. Received 2 packets, got 0 answers, remaining 1 packets (it only received 2 because it only waits for 0.5 seconds and the retransmit comes much later) is there a way to tell scapy to capture these packets as valid answers? or somehow return the "invalid" answers too?
answer count: 1
score: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/88863568
comment on: http://stackoverflow.com/q/50930330
has text: then why are you tagging as `multithreading?`
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50974312
answers question: http://stackoverflow.com/q/50974057
score: 0
accepted answer of: http://stackoverflow.com/q/50974057
has comment: http://stackoverflow.com/comment/88978394
type: AcceptedAnswer
has body: keys = [1,3,5] values = [1.0, 3.0, 5.0] column = [values[keys.index(i)] if i in keys else None for i in range(10)] print(column) Output [None, 1.0, None, 3.0, None, 5.0, None, None, None, None]
has comment: http://stackoverflow.com/comment/88950977
type: Answer
has comment: http://stackoverflow.com/comment/88950540

http://stackoverflow.com/comment/88734132
has text: In the first case, `dictstr` is a dict. In the second case, `dictstr` is a string.
type: Comment
comment on: http://stackoverflow.com/q/50865770
type: QuestionComment
score: 2

http://stackoverflow.com/q/50914335
tagged with: matplotlib
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/50915171
has title: How to plot in Wireframe with CSV file - Numpy / Matplotlib
accepted answer: http://stackoverflow.com/a/50915171
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
upvote count: 1
tagged with: python
has body: I would like to plot in 3D with Pandas / MatplotLib / Numpy as a Wireframe I'm using RFID sensors and I'm trying to record the signal I receive at different distance + different angles. And I want to see the correlation between the rising of the distance and the angle. I've already a full CSV file which looks like this : Distance;0 ;23 ;45 ;90 0 ;-33.24 ;-36.72;-39.335;-35.21 5 ;-31.73 ;-35.26;-41.56 ;-27.41 15 ;-31.175;-36.91;-40.74 ;-44.615 25 ;-35.305;-51.13;-45.515;-50.485 40 ;-35.205;-49.27;-55.565;-53.64 60 ;-41.8 ;-62.19;-58.14 ;-54.685 80 ;-47.79 ;-64.24;-58.285;-56.08 100 ;-48.43 ;-63.37;-64.595;-60.0 120 ;-49.07 ;-66.07;-63.475;-76.0 140 ;-50.405;-61.43;-62.635;-76.5 160 ;-52.805;-69.25;-71.0 ;-77.0 180 ;-59.697;-66.45;-70.1 ;nan 200 ;-56.515;-68.60;-73.4 ;nan So that's why I want to plot in 3D : X Axis : Angle Y Axis : Distance Z Axis : signal (for each couple angle/distance) On the first row we have the name of the index : Distanceand the different angles : 0°, 23°, 45°, 90° And on the first column we have the different distances which represent the Y axis. And the matrix inside represents the signal, so, values of Z Axis... I loaded my rawdata with Numpy : raw_data = np.loadtxt('data/finalData.csv', delimiter=';', dtype=np.string_) Then I used matplotlib to generate my wireframe : angle = raw_data[0 , 1:].astype(float) distance = raw_data[1:, 0 ].astype(float) data = ???? fig = plt.figure() ax = fig.add_subplot(111, projection='3d') Z = data X, Y = np.meshgrid(angle, distance) ax.plot_wireframe(X, Y, Z) ax.set_xticks(angle) ax.set_yticks(distance[::2]) ax.set_xlabel('angle') ax.set_ylabel('distance') plt.title('RSSI/angle/distance in wireframe') plt.savefig('data/3d/3d.png') plt.show() But I don't know how to extract the signal for each couple angle/distance and put it in data. I would like to know how to select the data to create the wireframe or to find another way to extract the data. Thank you !
type: AnsweredQuestion
score: 1

http://stackoverflow.com/a/51002140
has body: It may be postman bug. try to remove Content-Type from request header in postman before sending request. Sometime postman doesn't set correct header(content type).that may be the problem.
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51001598
answers question: http://stackoverflow.com/q/51001598
type: Answer
score: 3
upvote count: 3
type: AcceptedAnswer

http://stackoverflow.com/a/50937971
has comment: http://stackoverflow.com/comment/88874371
accepted answer of: http://stackoverflow.com/q/50937891
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50937891
type: Answer
has comment: http://stackoverflow.com/comment/88874393
has comment: http://stackoverflow.com/comment/88874484
upvote count: 4
downvote count: 0
score: 4
has body: Just tell Pandas not to convert the axes: result = pd.read_json('test1', orient='index', convert_axes=False) # contributors coordinates created_at #666020888022790149 NaN NaN 2015-11-15 22:32:08 #666029285002620928 NaN NaN 2015-11-15 23:05:30 #666033412701032449 NaN NaN 2015-11-15 23:21:54 The index is of type string: result.index.dtype #dtype('O') As a side note, 'test1' is a bad name for a CSV file. 'test1.csv' is much better.
has comment: http://stackoverflow.com/comment/88874470

http://stackoverflow.com/q/50949015
has comment: http://stackoverflow.com/comment/88896100
type: Question
has answer: http://stackoverflow.com/a/50949179
accepted answer: http://stackoverflow.com/a/50949179
score: 0
answer count: 1
has body: I'm working on a purge script in Python. The following script is working fine. The script browse a list of directories and, according to each file date, remove or keep any files. So if any files exist after X days or minutes, these files are removed. purge_files_path = ['x:/path/destination', 'x:/path/destination', ] kwargs = {"weeks":0, "days": 0, "hours": 0, "minutes": 23} def purge(purge_files_path, kwargs): import os from datetime import datetime, timedelta for folder in purge_files_path: for(dir, _, files) in os.walk(folder): for file in files: path = os.path.join(dir, file) if os.path.exists(path): file_date = datetime.fromtimestamp(os.path.getmtime(path)) delta = datetime.now() - file_date if delta &gt;= timedelta(**kwargs): os.remove(path) Now, I just want to add a new functionality. I want, before to remove a file, to save it in another folder. It could be easy, but I want to keep the folder architecture of any files. So if a file which has to be purged and located on: c:/source/folder1/folder2/file.txt It has to be back up on : c:/backup/folder1/folder2/file.txt I could use shutil.copytree, but I have an error of existing folders.
has title: A purge script - saving and deleting files according to it date
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/89014911
type: QuestionComment
comment on: http://stackoverflow.com/q/51011057
has text: I am adding an answer
score: 0
type: Comment

http://stackoverflow.com/comment/88861174
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50913648
has text: Put the statement, waiting for connection i.e. `self.clientsocket, self.addr = self.serversocket.accept()` in a loop before receiving / sending data (nested loops).

http://stackoverflow.com/q/50937966
linked to: http://stackoverflow.com/q/15843883
upvote count: 31
has answer: http://stackoverflow.com/a/50938287
type: Question
accepted answer: http://stackoverflow.com/a/50938015
score: 31
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88874353
possible better answer: http://stackoverflow.com/a/50938287
has comment: http://stackoverflow.com/comment/88874427
tagged with: iterator
answer count: 3
has answer: http://stackoverflow.com/a/67381701
downvote count: 0
has body: I am curious what the fastest way to consume an iterator would be, and the most Pythonic way. For example, say that I want to create an iterator with the map builtin that accumulates something as a side-effect. I don't actually care about the result of the map, just the side effect, so I want to blow through the iteration with as little overhead or boilerplate as possible. Something like: my_set = set() my_map = map(lambda x, y: my_set.add((x, y)), my_x, my_y) In this example, I just want to blow through the iterator to accumulate things in my_set, and my_set is just an empty set until I actually run through my_map. Something like: for _ in my_map: pass or a naked [_ for _ in my_map] works, but they both feel clunky. Is there a more Pythonic way to make sure an iterator iterates quickly so that you can benefit from some side-effect? Benchmark I tested the two methods above on the following: my_x = np.random.randint(100, size=int(1e6)) my_y = np.random.randint(100, size=int(1e6)) with my_set and my_map as defined above. I got the following results with timeit: for _ in my_map: pass 468 ms ± 20.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) [_ for _ in my_map] 476 ms ± 12.6 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) No real difference between the two, and they both feel clunky. Note, I got similar performance with list(my_map), which was a suggestion in the comments.
has title: Fastest (most Pythonic) way to consume an iterator
has comment: http://stackoverflow.com/comment/114897266
favorite count: 0
tagged with: optimization
has comment: http://stackoverflow.com/comment/128572764
has answer: http://stackoverflow.com/a/50938015
tagged with: python
tagged with: python-3.x

pyinstaller
tags question: http://stackoverflow.com/q/50987126
tags question: http://stackoverflow.com/q/50982375
type: Tag
tags question: http://stackoverflow.com/q/50950266
tag name: pyinstaller
tags question: http://stackoverflow.com/q/50972087
tags question: http://stackoverflow.com/q/50866952
tags question: http://stackoverflow.com/q/50959340
tags question: http://stackoverflow.com/q/50886642
tags question: http://stackoverflow.com/q/50879667

bin
tags question: http://stackoverflow.com/q/50952539
type: Tag
tag name: bin

http://stackoverflow.com/q/50860112
has comment: http://stackoverflow.com/comment/88729217
has comment: http://stackoverflow.com/comment/88727079
accepted answer: http://stackoverflow.com/a/50863820
tagged with: python-2.7
score: 2
downvote count: 0
answer count: 1
tagged with: doctest
tagged with: unicode
has body: I have a README.rst file containing several doctests for my Python library. They all work, except for the last doctest, which prints Unicode output, encoded in UTF-8: Here is a failing example:: &gt;&gt;&gt; print(u'\xE5\xE9\xEE\xF8\xFC') åéîøü (The use of print rather than just a string is very important to my actual use-case, as the real string contains embedded newlines and I need to show off how things on different lines are aligned.) Running pytest README.rst works successfully with Python 3.6.5 and pytest 3.6.1, but under Python 2.7.10, it fails with a very long traceback that ends with: input = 'åéîøü ', errors = 'strict' def decode(input, errors='strict'): &gt; return codecs.utf_8_decode(input, errors, True) E UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-4: ordinal not in range(128) /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/encodings/utf_8.py:16: UnicodeEncodeError Setting setenv = LC_ALL=en_US.UTF-8 in tox.ini and running under tox changes nothing; neither does adding doctest_encoding = utf-8 to the [pytest] section of tox.ini. I see no doctest options relevant to my plight. How do I get the test to run successfully under Python 2.7? Update: The bug responsible for this problem has been fixed in pytest 3.6.2.
favorite count: 0
upvote count: 2
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50863820
tagged with: pytest
has title: pytest can't handle Unicode in doctest in README under Python 2.7
type: Question

http://stackoverflow.com/a/50905122
has comment: http://stackoverflow.com/comment/88810052
has body: You can use negative indexing. a[-1] indicates your last element,a[-2] indicates your second last element and so on. Suppose you want to get last 5 elements. The you can write : my_list = a[-5:] Also follow shash678's answer. You can read What is negative index in Python?
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/88810426
has comment: http://stackoverflow.com/comment/88810112
downvote count: 0
has comment: http://stackoverflow.com/comment/88810357
answers question: http://stackoverflow.com/q/50905021
type: Answer

http://stackoverflow.com/comment/88838716
has text: Those are apache access/error logs and the patterns in the program will parse the given input log lines.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50919318
score: 0

http://stackoverflow.com/a/50987820
answers question: http://stackoverflow.com/q/50974722
type: Answer
has body: This seems like a task best suited for a Pelican plugin. The first thing I would do is look at the Pelican Plugin Repository and see if there is an existing plugin that can deliver the functionality you want. If not, you might consider finding a plugin that is close enough and modifying it to achieve your desired result. The documentation for Pelican plugins is reasonably extensive, and if you run into trouble, you can most likely solicit assistance from the folks in the Pelican IRC channel,
score: 0

http://stackoverflow.com/comment/88735787
score: 0
has text: Make sure your script works first. Once frozen if you have run it through command prompt, that is the best you will do for debugging at console level. The next level is to find out at what point it goes wrong and find common errors for that particular part of the script.
comment on: http://stackoverflow.com/q/50866681
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88930365
comment on: http://stackoverflow.com/a/50966793
type: Comment
has text: This works quite nicely actually, and will be very useful for my usecase. I was hoping for something native to `docx` files which will **remove** the images (from the xml?), but your solution is creative and works for me, so i'll select it for now (if no other "native" solution pops up)
type: AnswerComment
score: 0

http://stackoverflow.com/comment/88804058
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50884859
score: 0
has text: That looks like an R graph. It would seem you have solution!

http://stackoverflow.com/q/50998859
has answer: http://stackoverflow.com/a/50999387
downvote count: 2
answer count: 3
type: UnansweredQuestion
has body: How can I store multiple keys and values in school dictionary? I was trying to store a list of keys and values in a dictionary with a for loop but I did t know how to go about it. Can any one help me out?
has title: Working with python dictionary
has comment: http://stackoverflow.com/comment/88991719
upvote count: 0
has answer: http://stackoverflow.com/a/50998892
favorite count: 0
type: Question
tagged with: python
score: -2
has answer: http://stackoverflow.com/a/50998955

http://stackoverflow.com/q/51009492
answer count: 3
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: io
tagged with: python
has body: I have a text file, which has the following, contents: joe satriani is god steve vai is god steve morse is god steve lukather is god I wanted to write a code in python, which will change the file lines like: joe satriani is god ,absolutely man .. steve vai is god,absolutely man .. steve morse is god,absolutely man .. steve lukather is god,absolutely man .. I had tried doing such earlier once and I had not gotten the desired outcome. So, first I tried writing a code, which would just append "absolutely man" at the end of only the first line. So, the following is my code: jj = open('readwrite.txt', 'r+') jj.seek(1) n = jj.read() print(" yiuiuiuoioio \n") #just for debugging print(n) f = n.split("\n" , n.count("\n")) #to see what I am getting print(f) #As it turns out read returns the whole content as a string print(len(f[0])) # just for debugging jj.seek(len(f[0])) #take it to the end of first line posy = jj.tell() # to see if it actually takes it print(posy) jj.write(" Absolutely ..man ") But on executing the code, my file changes to the following: joe satriani is god Absolutely ..man d steve morse is god steve lukather is god The second line is being overwritten. How to append to one string at the end of one line? I thought of opening the file in read and append mode but it would overwrite the existing file. I do not want to read strings from this file and write the into another file by appending. How to append or alter the lines of a file? Is there any way to do it without any packages?
score: 1
has answer: http://stackoverflow.com/a/51010488
tagged with: file
upvote count: 1
has title: Writing to a file which is open in read and write mode altering the structure
type: Question
has answer: http://stackoverflow.com/a/51009753
has answer: http://stackoverflow.com/a/51009773

http://stackoverflow.com/comment/88783458
score: 0
type: AnswerComment
has text: If you show the output in your question, I can tell you the command to run.
type: Comment
comment on: http://stackoverflow.com/a/50891141

http://stackoverflow.com/a/50902968
accepted answer of: http://stackoverflow.com/q/50902933
answers question: http://stackoverflow.com/q/50902933
downvote count: 0
upvote count: 8
type: AcceptedAnswer
has body: Whenever you want a default value that can't easily be specified statically, the idiom is to use a sentinel value. If None is not a valid value that anyone might ever pass, use that: def do_a_thing(self, my_arg=None): if my_arg is None: my_arg = self.bar do_something_else(my_arg) Or, if there's no falsey value that would ever be valid: def do_a_thing(self, my_arg=None): if not my_arg: my_arg = self.bar do_something_else(my_arg) Or, if even None could be a value, you need to create a private sentinel that nobody will ever pass: _sentinel = object() def do_a_thing(self, my_arg=_sentinel): if my_arg is _sentinel: my_arg = self.bar do_something_else(my_arg) By the way, calling this a "default keyword argument" implies a serious misunderstanding. The fact that the syntax for default values in function definitions looks similar to the syntax for keyword arguments in function calls is a coincidence. In particular, this is not a keyword parameter, and it can be called without using keyword arguments. For example: my_thing.do_a_thing(20) If you actually want a keyword-only parameter, it has to come after a * (or after *args, if you have one of those). And, because these are completely unrelated features, you can have keyword-only parameters without default values: def do_a_thing(self, *, my_arg): do_something_else(my_arg) And "kwargs" usually isn't used as shorthand for "keyword argument" or "keyword parameter", but rather for the **kwargs parameter that gathers all unknown keyword arguments.
type: Answer
score: 8

http://stackoverflow.com/comment/88842021
has text: Isn't it the other way round, that `int`converts from any base in [2..36] **to** 10? That would also answer part of your question.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50920126

http://stackoverflow.com/q/50982334
upvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/50982526
has comment: http://stackoverflow.com/comment/88959763
tagged with: python
score: -1
tagged with: django-templates
possible better answer: http://stackoverflow.com/a/50982526
has title: Django- url not displaying page despite changing
has answer: http://stackoverflow.com/a/50982646
tagged with: django
downvote count: 1
type: AnsweredQuestion
tagged with: django-views
accepted answer: http://stackoverflow.com/a/50982646
tagged with: django-models
has body: This is the index.html {% extends 'base.html' %} {% block content %} list of {{title}} {% if questions %} {% for question in questions %} {{question.title}} {% endfor %} {% else %} there is a no question available {% endif %} {% endblock %} details.html {% extends 'base.html' %} {% block content %} Details Page {{question.title}} {% for choice in question.choices %} {{choice.text}}({{choice.votes}}) {% empty %} There is no choice available for this Question {% endfor %} Poll is created by {{question.created_by.first_name}} {% endblock %} This is base.html {%load static%} WebPage Welcome to My Page {% block content %} {% endblock %} And poll.urls from django.conf.urls import url from poll.views import * urlpatterns = [ url('', index, name='polls_list'), url('<int:id>/details/', details, name='polls_details') ] So this is what happens I have 3 questions that display on the index.html, on clicking any of them it changes to the proper url but does not open the requested page. How do I solve this. Do keep in mind that i just started django two days ago so pardon my naivety.Thanks
type: Question
answer count: 2

http://stackoverflow.com/a/50940270
has comment: http://stackoverflow.com/comment/88878567
type: Answer
has body: Using dictionary comprehension your_dict = {key:value for key,value in my_dict.items() if None not in value} Output: {'b': [2, 2], 'c': [1, 0], 'd': [1, 1]}
answers question: http://stackoverflow.com/q/50940184
has comment: http://stackoverflow.com/comment/88878453
has comment: http://stackoverflow.com/comment/88878543
has comment: http://stackoverflow.com/comment/88878473
score: 0

http://stackoverflow.com/q/50999819
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50999904
score: 1
tagged with: group-by
has body: I have a huge CSV file of 100kb which contains records. Example like below city employee california jhon delhi kumar us raj california brakers us kroja ... So I want to group them and stored in a separate CSV file My output result for above example would be city employee california jhon california brakers delhi kumar us raj us kroja Will I have to like sort/group by the city in the data frame and then have a for loop and iterate through the entire data frame? And her is my code New_data=pd.read_csv("citynames.csv",encoding = "ISO-8859-1") Aftergrouping_data=New_data.groupby("city") #print(Aftergrouping_data.groups) for name,group in Aftergrouping_data: print(name) group.to_csv("aftergrouping.csv".format(name), index=False) The problem is its overriding the values in for loop and displays the last group data. but I want all the grouped data in the file. Thank you In advance
type: Question
has title: Group by Column in Dataframe and create seperate csv for all the group
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/50999904
tagged with: pandas-groupby
tagged with: pandas
tagged with: python
tagged with: python-3.x
upvote count: 1

http://stackoverflow.com/a/50940193
upvote count: 1
has comment: http://stackoverflow.com/comment/88918316
has comment: http://stackoverflow.com/comment/88921457
has body: Reduce value of rely to .8 or .75 or something like this in this line: lyric_label.place(relx = .1, rely = .85) Change to : lyric_label.place(relx = .1, rely = .8) or lyric_label.place(relx = .1, rely = .75)
has comment: http://stackoverflow.com/comment/88948020
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88948040
downvote count: 0
answers question: http://stackoverflow.com/q/50940128
accepted answer of: http://stackoverflow.com/q/50940128
type: Answer
score: 1

http://stackoverflow.com/comment/88815586
has text: @user6655984 what you suggest is not possible for what I am doing. I am using a test suite of over 70,000 integrals in it. All written this way, using ^ for exponents on many expressions. I can only change ^ to ** to make sympy happy. Other changes would requires advanced parser to convert the radicals to not use ** notation. Also, how would you write `2**(5/6)` without using `**` ?
comment on: http://stackoverflow.com/q/50904546
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88827535
type: Comment
comment on: http://stackoverflow.com/q/50913650
type: QuestionComment
has text: Given a particular value of `f(x,y)` and a given `c` there are infinitely many pairs `(x, y)` that give that particular value. How are we to choose the pair `(x, y)`? In other words, there is no inverse function. Things change a bit if `x` and `y` are required to be integers--is that the case?
score: 4

http://stackoverflow.com/comment/88769103
score: 1
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50883054
has text: https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples

http://stackoverflow.com/q/50995842
has answer: http://stackoverflow.com/a/50996172
accepted answer: http://stackoverflow.com/a/50996172
has title: Generating Clojure EDN from Python with :symbols
downvote count: 0
answer count: 1
score: 4
favorite count: 0
tagged with: python
has body: I'm trying to use EDN to communicate between a simple Python server and an in browser app written using ClojureScript. So the server needs to generate and return chunks of EDN format for the browser. I've installed https://github.com/swaroopch/edn_format which seems to be a recommended EDN library for Python. But I want to be able to generate a map that uses Clojure symbols for keys. Eg. {:a 1 :b 2} However, if I create a Python dictionary {"a":1, "b":2} and pass it to the dumps function, the final EDN keeps the keys as strings, not symbols. Obviously there are no :symbols in Python. But is there a way to convince edn_format.dumps to turn dictionary string-keys into them? Or is there a better edn library for Python that can do this?
tagged with: edn
tagged with: clojurescript
type: AnsweredQuestion
type: Question
upvote count: 4

http://stackoverflow.com/q/50944575
has title: How to set a pylint score threshold?
has answer: http://stackoverflow.com/a/55763311
score: 28
has answer: http://stackoverflow.com/a/50979498
upvote count: 28
has answer: http://stackoverflow.com/a/63624903
tagged with: threshold
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/63624903
tagged with: pylint
has body: I'd like to extract my pylint rating and set a threshold. Let me explain, for example, if the score is under 5, I want exit 1; And if my code is rated higher than 5, I want exit 0 and continue my Jenkins procedure.
tagged with: python
accepted answer: http://stackoverflow.com/a/50979498
has answer: http://stackoverflow.com/a/76414351
answer count: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/112576704
type: Question

http://stackoverflow.com/a/50968094
downvote count: 0
has comment: http://stackoverflow.com/comment/88943519
type: Answer
score: 1
has body: Not sure if I fully understand, but can you not do this? def get_variable(name): if name in os.environ: return os.environ[name] else: print("no default value") return 'empty' Or: parser = argparse.ArgumentParser(description=MODULE_NAME) parser.add_argument('--test_arg',dest='test',nargs='?', default="empty") args = parser.parse_args() if args.test == "empty": if name in os.environ: newGlobalVar = os.environ["name"] print("no default value") else: newGlobalVar = args.test
answers question: http://stackoverflow.com/q/50967625
upvote count: 1

http://stackoverflow.com/q/50919221
has answer: http://stackoverflow.com/a/50919566
tagged with: python
type: AnsweredQuestion
tagged with: tkinter
accepted answer: http://stackoverflow.com/a/50919566
has title: Make Python GUI call specific function
type: Question
has body: So I am having trouble with this code that I have made. What I want it to do is that the user inputs either "real" or "fake" and then they click the submit button and the program outputs this sentence "Your random animal is..." (It will have a random animal in the dots). What I can't get working is the get_animal function. So what this does is it outputs the response to the user. But I can't get it to work with my GUI. Here is my code: ###### IMPORTS ###### from tkinter import * from tkinter import ttk import random ###### FUNCTIONS AND SETUP ###### def get_animal(lit): rand_animal = random.choice(lit) print("Your random animal is {}".format(rand_animal)) def real_or_fake(user_input): user_input.strip() if user_input == "Real" or user_input == "Fake": return True else: return False def main(): answer = animal.get().capitalize() if real_or_fake(answer) == True: if answer == "Real": response_text.set(get_animal(real_animals)) play_again = input("Would you like to play again? (Y or N) ").capitalize() if play_again == "Y": main() else: exit() else: response_text.set(get_animal(fake_animals)) play_again = input("Would you like to play again? (Y or N) ").capitalize() if play_again == "Y": main() else: exit() else: main() # Set up lists real_animals = ["horse", "gyrfalcon", "bull", "lion", "meerkat", "cat", "mouse", "moose", "rat", "panda", "stone fish", "anaconda", "python", "owl", "pigeon", "cow", "rabbit", "dog", "narwhal", "killer whale", "shrimp", "plankton", "liger"] fake_animals = ["unicorn", "phoenix", "minotaur", "orge", "goblin", "hobgoblin", "dragon", "griffin", "centaur", "mermaid", "leviathan", "pegasus", "harpies", "gorgon", "hydra", "sphinx", "raiju", "godzilla", "kraken", "gremlins", "simba", "yogi bear", "bugs bunny", "bambi"] ##### GUI CODE ##### root = Tk() root.title("Real or Fake") # Create the top frame top_frame = ttk.LabelFrame(root, text="Random Animals") top_frame.grid(row=0, column=0, padx=10, pady=10, sticky="NSEW") # Create and set the message …
score: 0
answer count: 1

http://stackoverflow.com/q/50950013
has title: TypeError: Object of type 'Undefined' is not JSON serializable
answer count: 1
has body: I'm getting this error when I attempt to submit the form. I'm not exactly sure what doesn't have a value/isn't defined, and was looking for guidance as the traceback didn't offer much insight for me at least. I had this error before when I attempted to run the page for the first time, and it was resolved by putting form=form into render_template's parameter. I believe the issue is in views.py, but let me know if I'm missing code or anything else. Thanks views.py @blueprint.route("register/") def register_page(): """Renders register site landing page.""" form = RegisterForm() return render_template('main/register.html', page_title="Register", form=form, media_types=current_app.config["ACCEPTED_" "MEDIA_TYPE"]) @blueprint.route("register/", methods=['GET', 'POST']) def register(): """Renders register page.""" form = RegisterForm() if request.method == 'POST': if not form.validate_on_submit(): return render_template('main/register.html', page_title="Service Registration", form=form, form_success=False) # If company does not exist, create it if err: company, err = create_company(form.organization.data) if err: return render_template('main/register.html', page_title="Service Registration", form=form, form_success=False, message=err) if err: return render_template('main/register.html', page_title="Service Registration", form=form, form_success=False, message=err) if err: return render_template('main/register.html', page_title="Service Registration", form=form, form_success=False, message=err) else: success_msg = "Your ticket id is {}. You should receive an email with a link to your ticket." .format(ticket.get('id')) return render_template('main/register.html', page_title="Service Registration", form=form, form_success=True, message=success_msg) return render_template('main/register.html', page_title="Service Registration", form=form) javascript var validateContentType = function() { var contentType = $('#upload').prop('files')[0].type; console.log(contentType, contentType…
favorite count: 0
has comment: http://stackoverflow.com/comment/88900447
tagged with: flask-wtforms
tagged with: python
accepted answer: http://stackoverflow.com/a/50951846
score: 2
type: AnsweredQuestion
upvote count: 3
has comment: http://stackoverflow.com/comment/88899153
tagged with: jinja2
downvote count: 1
type: Question
tagged with: javascript
tagged with: flask
has answer: http://stackoverflow.com/a/50951846
has comment: http://stackoverflow.com/comment/88898327

http://stackoverflow.com/comment/89343967
type: Comment
comment on: http://stackoverflow.com/a/51017735
has text: This example needs the following imports in order for it to work: ```from selenium.webdriver.support.ui import Select, WebDriverWait``` ```from selenium.webdriver.support import expected_conditions as EC``` ```from selenium.webdriver.common.by import By```
type: AnswerComment
score: 0

http://stackoverflow.com/q/50925083
has answer: http://stackoverflow.com/a/56405982
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50928156
score: 9
type: Question
has answer: http://stackoverflow.com/a/60517247
has title: Parse multipart request string in Python
upvote count: 9
answer count: 6
tagged with: aws-api-gateway
tagged with: amazon-web-services
has answer: http://stackoverflow.com/a/76876593
linked to: http://stackoverflow.com/q/3380501
has body: I have a string like this "--5b34210d81fb44c5a0fdc1a1e5ce42c3\r\nContent-Disposition: form-data; name=\"author\"\r\n\r\nJohn Smith\r\n--5b34210d81fb44c5a0fdc1a1e5ce42c3\r\nContent-Disposition: form-data; name=\"file\"; filename=\"example2.txt\"\r\nContent-Type: text/plain\r\nExpires: 0\r\n\r\nHello World\r\n--5b34210d81fb44c5a0fdc1a1e5ce42c3--\r\n" I also have request headers available in other vairbles. How do I easily parse this with Python3? I am handling a file upload in AWS Lambda via API Gateway, request body and headers are available via Python dicts. There are other similar questions on stackoverflow, but most are assuming use of the requests module or other modules and expect the request details to be in a specific object or format. NOTE: I am aware its possible to have user upload to S3 and trigger Lambda, but I am intentionally choosing not to do that in this case.
has answer: http://stackoverflow.com/a/58771674
downvote count: 0
accepted answer: http://stackoverflow.com/a/50928156
linked to: http://stackoverflow.com/q/31486618
tagged with: aws-lambda
favorite count: 0
possible better answer: http://stackoverflow.com/a/58771674
has answer: http://stackoverflow.com/a/63485321

http://stackoverflow.com/comment/88832025
comment on: http://stackoverflow.com/a/50915957
score: 1
type: AnswerComment
has text: But I need all 10 RBs to be exclusive. Can you group GroupBoxes?
type: Comment

http://stackoverflow.com/q/51001582
has title: How to create a new DataFrame from a Dataframe excluding rows based on count of occurunces in a specific column?
tagged with: python
type: AnsweredQuestion
has body: I have the following data frame: foo bar 0 Alice 42 1 Alice 44 2 Bob 22 and I am trying to get a new data frame excluding the last row because Bob occurs only once in column foo foo bar 0 Alice 42 1 Alice 44 Here is the code that I use to create the data frame seen above: df = pd.DataFrame( { "foo": ["Alice", "Alice", "Bob"], "bar": [42, 44, 22] } ) and my approach on this requirement (which does not work..) col_foo_gt_1 = df["foo"].value_counts() &gt; 1 print(col_foo_gt_1["Alice"]) # Prints true print(col_foo_gt_1["Bob"]) # Prints false df_bob_removed = pd.DataFrame( df[col_foo_gt_1[df["foo"]]] ) The error I am getting is: ValueError: cannot reindex from a duplicate axis
downvote count: 0
score: 1
possible better answer: http://stackoverflow.com/a/51001620
accepted answer: http://stackoverflow.com/a/51001699
type: Question
has answer: http://stackoverflow.com/a/51001699
answer count: 2
tagged with: pandas
upvote count: 1
has answer: http://stackoverflow.com/a/51001620
favorite count: 0

http://stackoverflow.com/a/50904769
score: 1
answers question: http://stackoverflow.com/q/50904510
downvote count: 0
type: Answer
has body: another way is, use unstack format and your dataframe column name df= df.set_index(['ID','Segment']).unstack(fill_value='null') df.columns = ['_'.join(val ) for val in zip(df.columns.get_level_values(0),df.columns.get_level_values(1))] or in more elegant way to format column, df.columns = df.columns.map('{0[0]}_{0[1]}'.format) print df Output: Var1_AAA Var1_BBB Var1_CCC Var2_AAA Var2_BBB Var2_CCC Var3_AAA Var3_BBB \ ID 1 1 null null 1 null null 1 null 2 null 1 null null 0 null null 1 3 null 1 null null 1 null null 1 4 0 null null 1 null null 1 null 5 null null 0 null null 1 null null 6 0 null null 0 null null 1 null 7 0 null null 1 null null 1 null 8 1 null null 0 null null 1 null 9 null 1 null null 0 null null 1 10 null null 1 null null 0 null null Var3_CCC ID 1 null 2 null 3 null 4 null 5 1 6 null 7 null 8 null 9 null 10 1
upvote count: 1

http://stackoverflow.com/comment/88982845
has text: @enumaris see above :)
score: 0
comment on: http://stackoverflow.com/q/50993934
type: QuestionComment
type: Comment

http://stackoverflow.com/q/50950939
has comment: http://stackoverflow.com/comment/88904337
has comment: http://stackoverflow.com/comment/88902636
type: Question
has comment: http://stackoverflow.com/comment/88900285
has body: When defining a descriptor class, you can simply raise an AttributeError to signal that the attribute isn't available. For example: from typing import Any, TypeVar, MutableMapping V = TypeVar("V") class Desc: def __init__(self, key: str) -&gt; None: self.key = key def __get__(self, instance: Any, owner: type) -&gt; V: try: return instance._dict[self.key] except KeyError: raise AttributeError() class C: foo = Desc("d") def __init__(self, d: MutableMapping[str, V]) -&gt; None: self._dict = d Use like: &gt;&gt;&gt; d1 = dict(d=0, bar=0, baz=0) &gt;&gt;&gt; c = C(d1) &gt;&gt;&gt; c.foo 0 &gt;&gt;&gt; d1.update(d=1) &gt;&gt;&gt; c.foo 1 &gt;&gt;&gt; hasattr(C(dict()), "foo") False Note that the AttributeError causes the hasattr function to "fail silently". This is as expected and described by the descriptor protocol. However, in some cases you may want the AttributeError to "bubble up" to the top. For example: class NewDesc: def __get__(self, instance, owner): do_complex_task(instance) # &lt;-- AttributeError occurs here return instance._on_the_fly_private_attr I have found that this is easily handled by wrapping the offending line of code in a try-except block that raises some other error different than AttributeError: try: do_complex_task(instance) # &lt;-- AttributeError occurs here except AttributeError as e: raise MyError() from e Is this the canonical way of handling this problem? What pitfalls am I leaving myself open to by doing it this way?
has comment: http://stackoverflow.com/comment/88914893
score: 0
has title: Canonical way to handle an AttributeError raised inside of a descriptor
tagged with: descriptor
has comment: http://stackoverflow.com/comment/88907124
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88911251
linked to: http://stackoverflow.com/q/903130
tagged with: python
has comment: http://stackoverflow.com/comment/88912085
answer count: 0
has comment: http://stackoverflow.com/comment/88902751

http://stackoverflow.com/a/51299328
has comment: http://stackoverflow.com/comment/92093714
downvote count: 0
has comment: http://stackoverflow.com/comment/92233858
accepted answer of: http://stackoverflow.com/q/50893331
answers question: http://stackoverflow.com/q/50893331
type: AcceptedAnswer
score: 1
has comment: http://stackoverflow.com/comment/90144397
has comment: http://stackoverflow.com/comment/90031008
type: Answer
upvote count: 1
has body: There is a hackish way to do this that requires some tedious byte wrangling. Presumably you are OK with deploying a small OpenCL probing kernel? (PyOpenCL does this under the hood for some ops in any case) The basic idea is to: find out how the OpenCL device aligns all the elements of your structs by running a single instance kernel create a numpy byte array to match the size of the OpenCL struct byte-wise copy each element of your Python struct into this array when invoking your unchangeable OpenCL kernel, pass this array via a bag of bytes buffer The following kernel does the job: __kernel void get_struct_sizes( __global uint *struct_sizes ) { const uint global_id = get_global_id(0u)+get_global_id(1u)*get_global_size(0u); VglClStrEl vgclstrel; VglClShape vgclshape; uint offset; printf("In GPU (probing):\n Kernel instance = %d\n", global_id); if (global_id==0) { offset = (uint)&amp;(vgclstrel.data); struct_sizes[0] = (uint)sizeof(vgclstrel); struct_sizes[1] = (uint)&amp;(vgclstrel.ndim)-offset; struct_sizes[2] = (uint)&amp;(vgclstrel.shape)-offset; struct_sizes[3] = (uint)&amp;(vgclstrel.offset)-offset; struct_sizes[4] = (uint)&amp;(vgclstrel.size)-offset; offset = (uint)&amp;(vgclshape.ndim); struct_sizes[5] = (uint)sizeof(vgclshape); struct_sizes[6] = (uint)&amp;(vgclshape.shape)-offset; struct_sizes[7] = (uint)&amp;(vgclshape.offset)-offset; struct_sizes[8] = (uint)&amp;(vgclshape.size)-offset; } return; } Execute this kernel and return struct_sizes into vgclshape_sizes, create this array: img_shape = np.zeros((vgclshape_sizes[0]), dtype=np.uint8) and copy into it what you need: def copy_into_byte_array(value, byte_array, offset): for i,b in enumerate(np.ndarray.tobytes(value)): byte_array[i+offset] = b copy_into_byte_array(ndim, img_shape, 0) copy_into_byte_array(shape, img_shape, vgclshape_sizes[1]) copy_into_byte_array(offset, img_shape, vgclshape_sizes[2]) copy_into_byte_array(size, img_shape, vgclshape_sizes[3]) I've skipped some steps here; filling them in…

http://stackoverflow.com/q/50957340
score: 1
accepted answer: http://stackoverflow.com/a/50957630
answer count: 2
downvote count: 0
tagged with: scikit-learn
favorite count: 0
has body: Is there a way to implement sklearn isolation forest for a 1D array or list? All the examples I came across are for data of 2 Dimension or more. I have right now developed a model with three features and the example code snipped is mentioned below: # dataframe of three columns df_data = datafr'col_A', 'col_B', 'col_C' w_train = page_data[:700] w_test = page_data[700:-2] from sklearn.ensemble import IsolationForest # fit the model clf = IsolationForest(max_samples='auto') clf.fit(w_train) #testing it using test set y_pred_test = clf.predict(w_test) The reference I mainly relied upon: IsolationForest example | scikit-learn The df_data is a data frame with three columns. I am actually looking to find outlier in 1 Dimension or list data. The other question is how to tune an isolation forest model? One of the ways is to increase the contamination value to reduce the false positives. But how to use the other parameters like n_estimators, max_samples, max_features, versbose, etc.
tagged with: python
has title: Isolation Forest Sklearn for 1D array or list and how to tune hyper parameters
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50957630
has answer: http://stackoverflow.com/a/78970971
tagged with: anomaly-detection
tagged with: machine-learning
upvote count: 1
type: Question
possible better answer: http://stackoverflow.com/a/78970971
tagged with: algorithm

http://stackoverflow.com/a/50971744
upvote count: 1
type: AcceptedAnswer
has body: I think this matches what you want: while True: output = "" num = int(input("enter a integer: ")) if num == 0: exit() for i in range(1, num+1): output += "{}".format(i) if i != num: output += "+" output += " = {}".format(sum(range(num+1))) print (output) This prints out the sum of integers and then the answer, then waits for the next input. Example output: $ python test.py enter a integer: 5 1+2+3+4+5 = 15 enter a integer: 4 1+2+3+4 = 10 enter a integer: 3 1+2+3 = 6 enter a integer: 2 1+2 = 3 enter a integer: 1 1 = 1 enter a integer: 0 = 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50971279
answers question: http://stackoverflow.com/q/50971279
downvote count: 0
score: 1

http://stackoverflow.com/comment/88810307
comment on: http://stackoverflow.com/a/50901911
type: Comment
has text: @AChampion Ah yes forgot about `dict.get()`, I'll update my answer.
type: AnswerComment
score: 0

http://stackoverflow.com/q/50872490
has answer: http://stackoverflow.com/a/50872616
has comment: http://stackoverflow.com/comment/106485456
favorite count: 0
linked to: http://stackoverflow.com/q/1051254
has title: Checking if a package is installed specifically via pip
possible better answer: http://stackoverflow.com/a/50872616
tagged with: python
has comment: http://stackoverflow.com/comment/88746702
has answer: http://stackoverflow.com/a/60210931
upvote count: 2
has body: Checking if a particular package is available from within Python can be done via try: import requests except ImportError: available = False else: available = True Additionally, I would like to know if the respective package has been installed with pip (and can hence been updated with pip install -U package_name). Any hints?
tagged with: pip
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88747168
accepted answer: http://stackoverflow.com/a/60210931
has comment: http://stackoverflow.com/comment/88746675
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/106488148
downvote count: 0

http://stackoverflow.com/q/50884859
score: 1
tagged with: matplotlib
type: Question
has body: I want to plot a bar chart where I need to compare sales of two regions with respect to Region and Tier. I implemented below code: df.groupby(['Region','Tier'],sort=True).sum()'Sales2015','Sales2016'.unstack().plot(kind="bar",width = .8) But I want to implement sales of Tier 2015 and 2016 side by side, e.g., on the x-axis the xticks should look like High Sales of 2015 and 2016 etc.
has comment: http://stackoverflow.com/comment/88804058
has title: Bar plot by grouping values in python
tagged with: pandas
downvote count: 0
answer count: 1
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50901067

http://stackoverflow.com/a/50870809
answers question: http://stackoverflow.com/q/50869116
has body: Thank you so much for your kind answers. But It resolved by follow code: I created Model for output parameters like below in model.py file: class TalentScoring(models.Model): ID = models.IntegerField(blank=True, null=True) title = models.CharField(max_length = 100) Location = models.CharField(max_length = 100) Location_score = models.IntegerField(blank=True, null=True) No_of_matched_comp = models.IntegerField(blank=True, null=True) No_of_matched_industry = models.IntegerField(blank=True, null=True) over_all_score = models.IntegerField(blank=True, null=True) title_score = models.IntegerField(blank=True, null=True) I have done serializer for this model also like below so it will serialize my response and give output my serializer.py file is blow: class TalentScoringSerializer(serializers.ModelSerializer): class Meta: model = TalentScoring fields = ('ID','title','Location','Location_score','No_of_matched_comp','No_of_matched_industry','over_all_score','title_score') view.py file as below from rest_framework.pagination import PageNumberPagination paginator = PageNumberPagination() paginator.page_size = 10 result_page = paginator.paginate_queryset(final_Score, request) serializer = TalentScoringSerializer(result_page, many=True) return paginator.get_paginated_response(serializer.data) My list name is "final_Score" after done some python coding on input parameters Now I can show 10 data per page as per my desire.
upvote count: 6
type: Answer
downvote count: 0
score: 6

http://stackoverflow.com/q/50928841
score: 0
answer count: 1
has title: Unable to install py-audio due to installation error
has body: I am trying to install py-audio on ubuntu following the guide here: https://github.com/theintencity/py-audio/blob/master/README.md I have been able to build correctly, however whenever I try to use py-audio I get the following error: cannot load audiodev.so and audiospeex.so, please set the PYTHONPATH I have tried adding these to my PYTHONPATH so that it now looks like this: py-audio:audiospeex:audiodev But I am still getting the same error and don't know how else to resolve it
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50931843
type: Question
tagged with: ubuntu

http://stackoverflow.com/q/50938369
tagged with: django
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/88904062
has comment: http://stackoverflow.com/comment/88904712
has title: How to use AWS Simple Email Service (SES) in Django?
has comment: http://stackoverflow.com/comment/88904735
tagged with: amazon-simple-email-service
has comment: http://stackoverflow.com/comment/88881779
has comment: http://stackoverflow.com/comment/88904878
has answer: http://stackoverflow.com/a/50953681
answer count: 1
downvote count: 0
score: 1
tagged with: django-ses
type: Question
has comment: http://stackoverflow.com/comment/88904994
type: AnsweredQuestion
favorite count: 0
has body: I'm trying to use this library to integrate my Django project with AWS SES. settings.py EMAIL_BACKEND = 'django_ses.SESBackend' AWS_ACCESS_KEY_ID = 'my_aws_access_key' AWS_SECRET_ACCESS_KEY = 'my_aws_secret_access_key' AWS_SES_REGION_NAME = 'us-west-2' AWS_SES_REGION_ENDPOINT = 'email.us-west-2.amazonaws.com' It throws the following error SESAddressNotVerifiedError: 400 Email address is not verified. Sender <Code>MessageRejected Email address is not verified. The following identities failed the check in region US-WEST-2: jpark1320@gmail.com, webmaster@localhost 0220c0a0-741b-11e8-a153-475b5dfc6545 I can't even guess why is wrong on my codes. But, one thing might be a problem is send_mail(). I'm using trying to send an email to a user for sign-up confirmation. I put the codes for sending email below. SMTP settings EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'my_google_email@gmail.com' EMAIL_HOST_PASSWORD = 'my_google_email_password' EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = 'My Team Name <noreply@gmail.com>' Update views.py def signup(request): if request.method == 'POST': form = SignupForm(request.POST) if form.is_valid(): # Create a user object to set email to be username before passing it to db user = form.save(commit=False) user.is_active = False user.email = form.cleaned_data['username'] user.save() current_site = get_current_site(request) mail_subject = "[Modvisor] Please verify your email address." message = render_to_string('accounts/account_active_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) to_email = user.email email = EmailMessage( mail_subject, message, to=[to_email] ) email.send() return redirect('signup_confirm') else: form = SignupForm() return render(request, 'accounts/register.html', {'form': form})
accepted answer: http://stackoverflow.com/a/50953681

http://stackoverflow.com/comment/88729808
has text: I'm sorry but what do you mean by category sort?
comment on: http://stackoverflow.com/a/50863288
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/50972571
score: 2
type: AnsweredQuestion
tagged with: list
tagged with: syntax
tagged with: dataframe
type: Question
tagged with: nltk
has body: I have a list like list = ['about','above','account','address','after'] which i passed into the nltk pos tag function and the output looks like this in form of a list: [('about', 'IN'),('above', 'JJ'),('account', 'NN'),('address', 'NN'),('after', 'IN')] now i need to display these words and pos tags seperately in form of a DataFrame so the output looks something like this: Words Pos Tags about IN above JJ account NN address NN after IN
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/50972645
favorite count: 0
has title: NLTK POS tag: how to put the 'Word' and its corresponding 'POS Tag' in a DataFrame
upvote count: 2
accepted answer: http://stackoverflow.com/a/50972645
tagged with: python

http://stackoverflow.com/comment/88943316
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50973448
has text: what's `D` in your formulas?
score: 0

http://stackoverflow.com/q/50884127
tagged with: containers
tagged with: flask
favorite count: 0
answer count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: microservices
tagged with: web-applications
has title: How might one toggle between multiple separate Flask applications that share the same structure and are in the same repo?
tagged with: python
score: 2
type: Question
has comment: http://stackoverflow.com/comment/88770277
has body: Apologies for not having a pithier way to explain that...tl;dr the best real-world example of what I'm looking for is Slack's team-switching functionality, wrt going from one team to an entirely different one while remaining in the same window and saving session data. In case you'd like more context: essentially, I have been working on a organizational/note-taking tool for myself, comprised of template data structures (Entities, Categories, Collections, and Tags). For example, in my bookmark manager, I would use the Entities to represent my bookmarks, the Category to group by documentation/tutorial/etc., the Collections to group by my projects/skills involved/etc. And then I'd like to be able to interact with my bookmark manager through an interface, organize based on whatever query I feel like (e.g. 'search by tag:data-science' or 'search collection:projects by category'), and even take notes within the app. I'd like to repeat this same process with a separate app that I would use to take notes/structure course material, and another one for organizing my Spotify playlists, and so on. It may sound a bit silly, but it's how I'd like to organize my bookmarks and lists, because the hierarchical/nested structure just doesn't cut it for me. I'm thinking that I should deploy this in one package and just essentially create a bunch of factory apps, because it seems like I'll be reusing the same code over and over again since I plan to keep the same templates for the apps and data structures (e.g. I plan to extend a base Entity class with specific attributes depending on the app). And if I'm doing that, then I like the idea of having all of this in one repository, where I could switch between the separate apps via an entry point that behaves like Slack's does. But I'm not sure what the best way to do this is. I'm visualizing one central login that allows you to toggle between multiple apps depending on which one you're logging into, but maybe that's unrealistic/too grandiose…
downvote count: 0

http://stackoverflow.com/comment/88809875
has text: To clarify, I want setup function in ModbusBaseRequestHandler class to work as before and remain untouched, but add sth else to it, but this modification should be done in my code not in the library.
comment on: http://stackoverflow.com/q/50903448
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50990437
has comment: http://stackoverflow.com/comment/88975510
score: 0
answer count: 3
tagged with: pandas
tagged with: python
has body: Given a score column, e.g., scores = pd.DataFrame({"score":np.random.randn(10)}) and thresholds thresholds = pd.DataFrame({"threshold":[0.2,0.5,0.8]},index=[7,13,33]) I would like to find the applicable threshold for each score, e.g., score threshold 0 -1.613293 NaN 1 -1.357980 NaN 2 0.325720 7 3 0.116000 NaN 4 1.423171 33 5 0.282557 7 6 -1.195269 NaN 7 0.395739 7 8 1.072041 33 9 0.197853 NaN IOW, for each score s I want the threshold t such that t = min(t: thresholds.threshold[t] &lt; s) How do I do that? PS. based on the deleted answer: pd.cut(scores.score, bins=[-np.inf]+list(thresholds.threshold)+[np.inf], labels=["low"]+list(thresholds.index))
has title: pandas: which threshold applies to each row?
possible better answer: http://stackoverflow.com/a/50991153
has comment: http://stackoverflow.com/comment/88976146
accepted answer: http://stackoverflow.com/a/50990658
has answer: http://stackoverflow.com/a/50991153
has comment: http://stackoverflow.com/comment/88976209
has comment: http://stackoverflow.com/comment/88976320
has answer: http://stackoverflow.com/a/50990667
has comment: http://stackoverflow.com/comment/88976258
type: AnsweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/88976251
has answer: http://stackoverflow.com/a/50990658

http://stackoverflow.com/comment/88878255
comment on: http://stackoverflow.com/q/50939828
score: 0
type: Comment
has text: You may also want to play around with a [multi'index](http://pandas.pydata.org/pandas-docs/stable/advanced.html) , using mfg and rating for the levels, and see if it has any advantages.
type: QuestionComment

http://stackoverflow.com/comment/113368125
type: AnswerComment
comment on: http://stackoverflow.com/a/64109376
has text: That wouldn't work, since it would replace all instances of the word "and", regardless of whether they were originally an "&".
type: Comment
score: 1

http://stackoverflow.com/a/50868411
score: 0
answers question: http://stackoverflow.com/q/50866385
type: Answer
has body: Using a remapping tool from more_itertools in Python 3.6+: Given import copy as cp import collections as ct import more_itertools as mit data = [ ("Player1", "A", 1, 100), ("Player1", "B", 15, 100), ("Player2", "A", 7, 100), ("Player2", "B", 65, 100), ('Global Total', None, 88, 100) ] # Discard the last entry data = data[:-1] # Key functions kfunc = lambda tup: tup[0] vfunc = lambda tup: tup[1:] rfunc = lambda x: {item[0]: [item[1]] for item in x} Code # Step 1 remapped = mit.map_reduce(data, kfunc, vfunc, rfunc) # Step 2 intermediate = ct.defaultdict(list) for d in remapped.values(): for k, v in d.items(): intermediate[k].extend(v) # Step 3 remapped["Global Total"] = {k: [sum(v)] for k, v in intermediate.items()} final = cp.deepcopy(remapped) for name, d in remapped.items(): for lbl, v in d.items(): stat = (v[0]/remapped["Global Total"][lbl][0]) * 100 final[name][lbl].append(stat) Details Step 1 - build a new dict of remapped groups. This is done by defining key functions that dictate how to process the keys and values. The reducing function processes the values into sub-dictionaries. See also docs for more details on more_itertools.map_reduce. &gt;&gt;&gt; remapped defaultdict(None, {'Player1': {'A': [1], 'B': [15]}, 'Player2': {'A': [7], 'B': [65]}}) Step 2 - build an intermediate dict for lookups &gt;&gt;&gt; intermediate defaultdict(list, {'A': [1, 7], 'B': [15, 65]}) Step 3 - build a final dict from the latter dictionaries &gt;&gt;&gt; final defaultdict(None, {'Player1': {'A': [1, 12.5], 'B': [15, 18.75]}, 'Player2': {'A': [7, 87.5], 'B': [65, 81.25]}, 'Global Total': {'A': [8, 100.0], 'B': [80, 100.0]}})

http://stackoverflow.com/q/50920402
upvote count: 3
type: Question
score: 3
has body: I want to fill values between two number from two different column. I have a data frame that looks like this(df) I only want to fill the forward the Value column when I have a number in Start column and End column. Basically, the Start indicates that a process is getting started and end meaning that process is ending. So Value column only can have to be filled between these two. Here is a code to generate the data and DF is what I want to get. from datetime import datetime, timedelta import pandas as pd import numpy as np import random np.random.seed(11) date_today = datetime.now() ndays = 10 df = pd.DataFrame({'date': [date_today + timedelta(days=x) for x in range(ndays)], 'Start': pd.Series(np.random.randn(ndays)), 'End':pd.Series(np.random.randn(ndays))}) df = df.set_index('date') df = df.mask(np.random.random(df.shape) &lt; .6) df.End[{0,1,2,5,6,9}]=np.nan df.Start[5]=1 df.Start[{1,3,4,2,8, 9}]=np.nan df['Value']=np.nan df.Value[{0,5}]=[0.3,0.1] df I want to obtain a dataframe(DF) which look like this: End Start Value date 2018-06-18 22:34:35.964286 NaN 1.749455 0.3 2018-06-19 22:34:35.964286 NaN NaN 0.3 2018-06-20 22:34:35.964286 NaN NaN 0.3 2018-06-21 22:34:35.964286 0.561192 NaN 0.3 2018-06-22 22:34:35.964286 NaN NaN NaN 2018-06-23 22:34:35.964286 NaN 1.000000 0.1 2018-06-24 22:34:35.964286 NaN NaN 0.1 2018-06-25 22:34:35.964286 NaN NaN 0.1 2018-06-26 22:34:35.964286 -0.031075 NaN 0.1 2018-06-27 22:34:35.964286 NaN NaN NaN Thanks in advance
tagged with: dataframe
tagged with: pandas
has answer: http://stackoverflow.com/a/50920504
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
has title: Pandas: Fill forward between based on a condition
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50920504

http://stackoverflow.com/a/50978942
has comment: http://stackoverflow.com/comment/88953725
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50978660
downvote count: 0
has body: We are using strip to remove the trailing space. s1 = re.sub(r'[^a-zA-Z0-9\s]+|X','',s1).strip() s2 = re.sub(r'[^a-zA-Z0-9\s]+|X','',s2).strip() s3 = re.sub(r'[^a-zA-Z0-9\s]+|X','',s3).strip() 2 I LOVE FOOD FOOD
type: Answer

http://stackoverflow.com/comment/88834925
comment on: http://stackoverflow.com/a/50917368
type: Comment
score: 1
type: AnswerComment
has text: I would use a `left` join, since that's what OP literally needed. Besides that, this answer seems spot on.

http://stackoverflow.com/comment/88792089
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50894258
has text: Well, isn't then everything a wrapper around some C stuff? ;-)
score: 0

http://stackoverflow.com/q/50885943
has title: Trouble authenticating Airtable API while creating a field with python
type: AnsweredQuestion
tagged with: airtable
has answer: http://stackoverflow.com/a/50892595
downvote count: 0
score: 1
favorite count: 0
has body: [newbie question] I'm trying to create a new record in my Airtable base using python 3. The curl commands in the documentation are as follows: $ curl -v -XPOST https://api.airtable.com/v0/restoftheurl \ -H "Authorization: Bearer My_API_Key" \ -H "Content-type: application/json" \ -d '{ "fields": { "Item": "Headphone", "Quantity": "1", "Customer_ID": [ "My_API_Key" ] } }' The python code I tried to use is: import requests API_URL = "https://api.airtable.com/v0/restoftheurl" data = {"Authorization": "Bearer My_API_Key","Content-type": "application/json","fields": {"Item": "randomitem","Quantity": "5","Customer_ID": ["randomrecord"]}} r = requests.post(API_URL, data) print(r.json()) Where the response is the error: {'error': {'type': 'AUTHENTICATION_REQUIRED', 'message': 'Authentication required'}} How am I supposed to properly authenticate this, or am I way of?
tagged with: python-3.x
type: Question
tagged with: python
tagged with: curl
accepted answer: http://stackoverflow.com/a/50892595
upvote count: 1
answer count: 1

http://stackoverflow.com/a/50893615
downvote count: 0
has comment: http://stackoverflow.com/comment/88993160
has comment: http://stackoverflow.com/comment/88996343
has body: You can use constraints, then neo4j will check uniqueness for you. From documentation: To create a Node Key ensuring that all nodes with a particular label have a set of defined properties whose combined value is unique, and where all properties in the set are present CREATE CONSTRAINT ON (author:Author) ASSERT (author.first_name, author.last_name, author.affiliation) IS NODE KEY
has comment: http://stackoverflow.com/comment/88788156
has comment: http://stackoverflow.com/comment/88992744
type: Answer
has comment: http://stackoverflow.com/comment/88996644
answers question: http://stackoverflow.com/q/50893573
score: 1
upvote count: 1

http://stackoverflow.com/q/50965910
answer count: 0
score: 0
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/88928230
has title: Summatory with variables that have two indexes in PYTHON
has body: I am trying to write something like this (which is a part of a constraint): sum(a in ArcsOut[p.o]) F[a][p] for all p=(o,d) in pairs. My code is : I have a set of nodes: nodes = ["uno","dos","tres","cuatro","cinco","seis"] and its set of all possible pairs pairs = [(i,j) for i in nodes for j in nodes if i!=j] I have a set of ARCS. Also, I have defined the set ArcsOut[i], which has all arcs that are in ARCS and it first component is i. Binary var F[a][p]: F = [[mdl.binary_var_dict(ARCS, name= "F")] for p in pairs] That is, for each p in pairs there is a binary vector with length the number of arcs. In this situation I am trying to write the summatory of the beginning: mdl.sum([(F[a][p]) for a in ArcsOut[p[0]]] for p in pairs) but, naturally I get errors. Complete code: nodes = ["uno","dos","tres","cuatro","cinco","seis"] EDGES = [("uno", "dos"), ("uno", "tres"), ("dos", "tres"), ("dos", "cuatro"), ("tres", "cuatro"), ("tres", "cinco"), ("cuatro", "cinco"), ("cuatro", "seis"), ("cinco", "seis")] INVERSES =[(j,i) for (i,j) in EDGES] ARCS = EDGES + INVERSES ArcsOut = defaultdict(list) for k, v in ARCS: ArcsOut[k].append((k,v)) pairs = [(i,j) for i in nodes for j in nodes if i!=j] costY = [2, 3, 2.2, 3, 2.5, 1.3] costX = [1.7, 2.7, 2.1, 3, 2.6, 1.7, 2.8, 2.4, 1.9] max = 25 d = [9, 26, 19, 13, 12, 11, 14, 26, 7, 18, 30, 19, 30, 24, 8, 21, 9, 11, 22, 16, 14, 14, 8, 9, 20, 26, 1, 22, 24, 13] mdl = CpoModel() Y = mdl.binary_var_dict(nodes, name = "Y") X = mdl.binary_var_dict(EDGES, name = "X") Z = mdl.binary_var_dict(pairs, name = "Z") F = [[mdl.binary_var_dict(ARCS, name= "F")] for p in pairs] mdl.part1 = mdl.sum([(costX[i]*X[e]) for i, e in enumerate(EDGES)]) mdl.part2 = mdl.sum([(costY[i]*Y[e]) for i, e in enumerate(nodes)]) mdl.add(mdl.part1 + mdl.part2 &lt;= max) prod = [(d[i]*Z[p]) for i, p in enumerate(pairs)] obj = mdl.sum(prod) mdl.add(mdl.maximize(obj)) mdl.add(aX[e]&lt;=Y[e[0]] for e in EDGES) mdl.add(X[e]&lt;=Y[e[1]] for e in EDGES) I have problem with the next co…
tagged with: python-2.7
tagged with: docplex
has comment: http://stackoverflow.com/comment/88931178
tagged with: python
has comment: http://stackoverflow.com/comment/88929119
tagged with: python-3.x

http://stackoverflow.com/q/50991189
has comment: http://stackoverflow.com/comment/88988832
upvote count: 17
type: Question
has answer: http://stackoverflow.com/a/65471509
has comment: http://stackoverflow.com/comment/88991790
has title: Is there any pytorch function can combine the specific continuous dimensions of tensor into one?
accepted answer: http://stackoverflow.com/a/51002923
has answer: http://stackoverflow.com/a/67672417
has body: Let's call the function I'm looking for "magic_combine", which can combine the continuous dimensions of tensor I give to it. For more specific, I want it to do the following thing: a = torch.zeros(1, 2, 3, 4, 5, 6) b = a.magic_combine(2, 5) # combine dimension 2, 3, 4 print(b.size()) # should be (1, 2, 60, 6) I know that torch.view() can do the similar thing. But I'm just wondering if there is any more elegant way to achieve the goal?
tagged with: deep-learning
possible better answer: http://stackoverflow.com/a/70920384
downvote count: 0
has answer: http://stackoverflow.com/a/70920384
favorite count: 0
tagged with: tensor
has answer: http://stackoverflow.com/a/51002923
tagged with: python
answer count: 4
has comment: http://stackoverflow.com/comment/88977577
type: AnsweredQuestion
tagged with: pytorch
score: 17

http://stackoverflow.com/q/50937959
type: AnsweredQuestion
tagged with: zappa
has answer: http://stackoverflow.com/a/51340448
has answer: http://stackoverflow.com/a/54204032
has answer: http://stackoverflow.com/a/61994223
has answer: http://stackoverflow.com/a/68236387
tagged with: flask-ask
downvote count: 1
type: Question
linked to: http://stackoverflow.com/q/40785052
has answer: http://stackoverflow.com/a/55843615
has answer: http://stackoverflow.com/a/60014463
has comment: http://stackoverflow.com/comment/88892267
has answer: http://stackoverflow.com/a/50948763
score: 17
upvote count: 18
answer count: 11
has answer: http://stackoverflow.com/a/53420080
tagged with: amazon-web-services
tagged with: aws-lambda
has comment: http://stackoverflow.com/comment/121122455
has answer: http://stackoverflow.com/a/60081355
favorite count: 0
has answer: http://stackoverflow.com/a/52649862
has title: Zappa deployment error : GET request yields 502 response code
has answer: http://stackoverflow.com/a/61532078
accepted answer: http://stackoverflow.com/a/50948763
has body: I am trying to deploy the first zappa example app built with Flask-Ask, It looks like everything works good but after the Deploying API statement I get the following error : Error: Warning! Status check on the deployed lambda failed. A GET request to '/' yielded a 502 response code. Here is the code I am executing with minor changes to the sample app from flask import Flask from flask_ask import Ask, question, statement, session import pyodbc app = Flask(name) ask = Ask(app, '/') @ask.intent('HelloIntent') def hello(firstname): speech_text = "Hello %s" % firstname return statement(speech_text).simple_card('Hello', speech_text) @ask.intent('ByeIntent') def bye(): return statement("Ok, goodBye!") if name == 'main': app.run() Zappa version used: 0.46.1 Operating System and Python version: Windows 7, Python 3.6 Can someone please help me out here?
tagged with: python
possible better answer: http://stackoverflow.com/a/52649862

http://stackoverflow.com/a/50937731
has body: Assuming there is indeed a need to apply a function (say, foo()) to each submatrix, the following code does the job: result = np.stack( # Combine [foo(a[:,:,i].T) # Apply for i in range(a.shape[2])], # Split axis=2)
type: Answer
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50936802
upvote count: 2

http://stackoverflow.com/q/50979449
score: 0
has answer: http://stackoverflow.com/a/50980163
answer count: 1
has comment: http://stackoverflow.com/comment/88954973
linked to: http://stackoverflow.com/q/49598702
has title: Functionality of isalpha function
tagged with: isalpha
tagged with: python
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/3094498
has body: The Python program below checks if there exists an alphabet in the string and if there is no alphabet it translates it to english using a custom API and writes it to a file. Since isalpha() checks for - 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'. I'm not sure as to why the program enters the first loop for this string - '龙海德信机电有限公司'. When I ran the debugger it showed that the isalpha() function evaluates 龙 as an alphabet. I'm not sure as to why this happens. def translate_function(file): filea = open(file,encoding = "utf8") fileb = open("lmao.txt", 'r+') count = 0 for i in filea: state = 'false' count += 1 for j in i : if (j.isalpha()): state = 'true' print(i, "This is English") break if (state == 'false'): trans = translate(i) fileb.write(trans) fileb.write('\n') return count
type: Question
accepted answer: http://stackoverflow.com/a/50980163

http://stackoverflow.com/comment/89030481
has text: your_button.clicked.connect(your_dialog.close)
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50967870

http://stackoverflow.com/a/50986076
has comment: http://stackoverflow.com/comment/88981941
answers question: http://stackoverflow.com/q/50974836
type: Answer
has body: Instead of classifying according to entities, I would use Google default categories directly, changing entity = client.analyze_entities(document, encoding).entities to categories = client.classify_text(document).categories and consequently up-dating the code. I wrote the following sample code based on this tutorial, further developed in github. def run_quickstart(): # [START language_quickstart] # Imports the Google Cloud client library # [START migration_import] from google.cloud import language from google.cloud.language import enums from google.cloud.language import types # [END migration_import] # Instantiates a client # [START migration_client] client = language.LanguageServiceClient() # [END migration_client] # The text to analyze text = u'For its part, India has said it will raise taxes on 29 products imported from the US - including some agricultural goods, steel and iron products - in retaliation for the wide-ranging US tariffs.' document = types.Document( content=text, type=enums.Document.Type.PLAIN_TEXT) # Detects the sentiment of the text sentiment = client.analyze_sentiment(document=document).document_sentiment # Classify content categories categories = client.classify_text(document).categories # User category feedback for category in categories: print(u'=' * 20) print(u'{:&lt;16}: {}'.format('name', category.name)) print(u'{:&lt;16}: {}'.format('confidence', category.confidence)) # User sentiment feedback print('Text: {}'.format(text)) print('Sentiment: {}, {}'.format(sentiment.score, sentiment.magnitude)) # [END language_quickstart] if __name__ == '__main__': run_quickstart() Does this solution works for you? If not, why?
score: 0

http://stackoverflow.com/comment/88772528
comment on: http://stackoverflow.com/q/50885312
type: Comment
type: QuestionComment
score: 1
has text: Possible duplicate of [How to make IPython notebook matplotlib plot inline](https://stackoverflow.com/questions/19410042/how-to-make-ipython-notebook-matplotlib-plot-inline)

http://stackoverflow.com/comment/88894722
type: Comment
has text: @RoryDaulton Yes, any character position can mismatch. Sorry about the confusion.
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50948490

http://stackoverflow.com/comment/88982498
type: Comment
comment on: http://stackoverflow.com/a/50993849
score: 0
type: AnswerComment
has text: @serkanozel yeah, pandas devs think of everything. You're welcome.

arrays
tags question: http://stackoverflow.com/q/50971985
tags question: http://stackoverflow.com/q/50875983
tags question: http://stackoverflow.com/q/50895818
tags question: http://stackoverflow.com/q/50930832
tags question: http://stackoverflow.com/q/50859654
tags question: http://stackoverflow.com/q/51004753
tags question: http://stackoverflow.com/q/50887349
type: Tag
tags question: http://stackoverflow.com/q/50992584
tags question: http://stackoverflow.com/q/50896266
tags question: http://stackoverflow.com/q/50987691
tags question: http://stackoverflow.com/q/50865440
tags question: http://stackoverflow.com/q/50889582
tags question: http://stackoverflow.com/q/50959275
tags question: http://stackoverflow.com/q/50963992
tags question: http://stackoverflow.com/q/50928229
tags question: http://stackoverflow.com/q/50931421
tags question: http://stackoverflow.com/q/50980852
tags question: http://stackoverflow.com/q/50926411
tags question: http://stackoverflow.com/q/51002266
tags question: http://stackoverflow.com/q/50860869
tags question: http://stackoverflow.com/q/50889988
tags question: http://stackoverflow.com/q/50926951
tags question: http://stackoverflow.com/q/50899951
tags question: http://stackoverflow.com/q/50930655
tags question: http://stackoverflow.com/q/50866141
tags question: http://stackoverflow.com/q/50947681
tags question: http://stackoverflow.com/q/50900476
tags question: http://stackoverflow.com/q/50951033
tags question: http://stackoverflow.com/q/50892030
tags question: http://stackoverflow.com/q/50969050
tags question: http://stackoverflow.com/q/50897976
tags question: http://stackoverflow.com/q/50910357
tags question: http://stackoverflow.com/q/50949203
tags question: http://stackoverflow.com/q/50974234
tags question: http://stackoverflow.com/q/50860662
tags question: http://stackoverflow.com/q/50897756
tags question: http://stackoverflow.com/q/50957010
tags question: http://stackoverflow.com/q/50889925
tags question: http://stackoverflow.com/q/50931002
tags question: http://stackoverflow.com/q/50870524
tags question: http://stackoverflow.com/q/50880360
tags question: http://stackoverflow.com/q/50955782
tags question: http://stackoverflow.com/q/50959570
tags question: http://stackoverflow.com/q/50896980
tags question: http://stackoverflow.com/q/51002815
tags question: http://stackoverflow.com/q/50881505
tags question: http://stackoverflow.com/q/50865463
tags question: http://stackoverflow.com/q/50890791
tags question: http://stackoverflow.com/q/50974924
tags question: http://stackoverflow.com/q/50920346
tag name: arrays
tags question: http://stackoverflow.com/q/50895035
tags question: http://stackoverflow.com/q/50896193
tags question: http://stackoverflow.com/q/50988766
tags question: http://stackoverflow.com/q/50931068
tags question: http://stackoverflow.com/q/51006279
tags question: http://stackoverflow.com/q/50918497
tags question: http://stackoverflow.com/q/50875021
tags question: http://stackoverflow.com/q/50963189
tags question: http://stackoverflow.com/q/50954569
tags question: http://stackoverflow.com/q/50913499
tags question: http://stackoverflow.com/q/50949692
tags question: http://stackoverflow.com/q/50864169
tags question: http://stackoverflow.com/q/50907015
tags question: http://stackoverflow.com/q/50958668
tags question: http://stackoverflow.com/q/50976947
tags question: http://stackoverflow.com/q/50948684
tags question: http://stackoverflow.com/q/50915738
tags question: http://stackoverflow.com/q/51005699
tags question: http://stackoverflow.com/q/50862660
tags question: http://stackoverflow.com/q/50902087
tags question: http://stackoverflow.com/q/50927952
tags question: http://stackoverflow.com/q/50926626
tags question: http://stackoverflow.com/q/50955592
tags question: http://stackoverflow.com/q/50984418
tags question: http://stackoverflow.com/q/51006844
tags question: http://stackoverflow.com/q/50949437
tags question: http://stackoverflow.com/q/50919238
tags question: http://stackoverflow.com/q/50977944

http://stackoverflow.com/comment/88861054
type: Comment
type: QuestionComment
score: 2
has text: Does the order of the groups matter? Or just that duplicates all have the same group?
comment on: http://stackoverflow.com/q/50930849

http://stackoverflow.com/comment/88968199
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50986541
type: Comment
has text: Yes, it would have to be exactly as the question posted and not great for a dataframe with other columns

http://stackoverflow.com/comment/88867587
score: 0
type: Comment
type: QuestionComment
has text: Not having used factory boy, what happens if you make `model = Point.fromlist`? Semantically, they're both callables accepting arguments and return `Point` instances -- I feel like this might be one approach.
comment on: http://stackoverflow.com/q/50934517

http://stackoverflow.com/comment/88949279
comment on: http://stackoverflow.com/a/50958269
score: 1
has text: Thanks Dany, your flow was helpful in understanding on how to go about feature identification. Although, the python solution was more easy to apply.
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89066749
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50971180
type: Comment
has text: `link_list` and `his_sorted` are not defined, and you don't use the function `histogram()` you wrote. Moreover, I think you need to import the `datetime` module

http://stackoverflow.com/comment/88879575
comment on: http://stackoverflow.com/a/50936849
type: Comment
has text: Thank you for the suggestion.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/88801062
has text: @StephenRauch no, like I said, OP needs several things explained, particularly their misunderstanding of `message[0]`.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50900491

http://stackoverflow.com/q/50958442
possible better answer: http://stackoverflow.com/a/50959108
downvote count: 2
linked to: http://stackoverflow.com/q/1750757
type: Question
has body: I'm using the arcpy module of ArcGIS in Python (2.7) to process many polygon shapefiles, using many different tools. Every so often it will throw a random error, which I catch with an exception but all subsequent shapefiles are then affected by the same error. I really don't understand what is causing this error (ERROR 010088), and the only workaround I have is to restart the script from the last file that was processed successfully. My question is: how can I restart the script every time I hit this error, and then stop when all files have been processed successfully? I've looked at various different questions (e.g. Restarting a self-updating python script) but nothing quite does the job, or I can't understand how to apply it to my situation because I'm still very much a Python beginner. The closest I've come is the example below, based on this blog post: https://www.alexkras.com/how-to-restart-python-script-after-exception-and-run-it-forever/. Script called test.py: import arcpy import sys try: arcpy.Buffer_analysis(r"E:\temp\boundary.shp", r"E:\temp\boundary2.shp", "100 Feet") # Print arcpy execute error except arcpy.ExecuteError as e: # Print print(e) # Pass any other type of error except: pass Script called forever.py, in the same directory: from subprocess import Popen import sys filename = sys.argv[1] while True: print("\nStarting " + filename) p = Popen("python " + filename, shell=True) p.wait() (Note that boundary.shp is just a random boundary polygon - available here: https://drive.google.com/open?id=1LylBm7ABQoSdxKng59rsT4zAQn4cxv7a). I'm on a Windows machine, so I run all this in the command line with: python.exe forever.py test.py As expected, the first time this script runs without errors, and after that it hits an error because the output file already exists (ERROR 000725). The trouble is that ultimately I want the script to only restart when it hits ERROR 010088, and definitely not when the script has completed successfully. So in this example, it sho…
tagged with: arcpy
has title: Restart python script after arcpy error, until successful
accepted answer: http://stackoverflow.com/a/50958986
tagged with: python-2.7
answer count: 2
linked to: http://stackoverflow.com/q/4308182
favorite count: 0
tagged with: arcgis
upvote count: 2
tagged with: python
linked to: http://stackoverflow.com/q/2225564
has answer: http://stackoverflow.com/a/50959108
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50958986
score: 0

http://stackoverflow.com/comment/88756838
type: Comment
comment on: http://stackoverflow.com/a/50876688
score: 1
type: AnswerComment
has text: While this code snippet may be the solution, [including an explanation](https://meta.stackexchange.com/questions/114762/explaining-entirely-%E2%80%8C%E2%80%8Bcode-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.

http://stackoverflow.com/q/50956539
has title: Address already in use (Errno 98) django with vscode and docker
has answer: http://stackoverflow.com/a/57397843
tagged with: visual-studio-code
downvote count: 0
answer count: 1
favorite count: 0
tagged with: docker
tagged with: python
has comment: http://stackoverflow.com/comment/88910562
type: UnansweredQuestion
tagged with: django
upvote count: 1
has body: I have a python application with django and I'm running it inside a docker container. I need to debug this application and every time I do the docker-compose up it gives this error below. I looked at several sites on how to debug and none of the solutions helped me. Does anyone know what can it be? I think the most important files for you to evaluate are below, if there is need of any more I edit the post. I'm using django 2.0.1, ptvsd 3.2.1 and the Docker-Toolbox. File "manage.py", line 10, in &lt;module&gt; ptvsd.enable_attach(secret='my_secret', address = ('192.168.99.100', 3000)) File "/usr/local/lib/python3.6/site-packages/ptvsd/__init__.py", line 87, in enable_attach return _attach_server().enable_attach(secret, address, certfile, keyfile, redirect_output) File "/usr/local/lib/python3.6/site-packages/ptvsd/attach_server.py", line 109, in enable_attach server.bind(address) OSError: [Errno 99] Cannot assign requested addres s manage.py: #!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "chatire.settings") try: from django.core.management import execute_from_command_line import ptvsd ptvsd.enable_attach(secret='my_secret', address = ('192.168.99.100', 3000)) except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) docker-compose.yml: version: '3' services: db: image: postgres backend: build: . command: bash app.sh volumes: - .:/code ports: - "3000:3000" - "8000:8000" depends_on: - db frontend: build: ./chatire-frontend command: bash front.sh volumes: - ./chatire-frontend:/to-do-app ports: - "8080:8080" - "8081:8081" rabbit1: image: "rabbitmq:3-management" hostname: "rabbit1" environment: RABBITMQ_ERLANG_COOKIE: "SWQOKODSQALRPCLNMEQG" RABBITMQ_DEFAULT_USER: "guest" RABBITMQ_DEFAULT_PASS: "guest" RABB…
type: Question
score: 1

http://stackoverflow.com/comment/88806451
type: Comment
has text: I don't need the body, i want the headers. The body i can get.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50903304

http://stackoverflow.com/a/50987646
downvote count: 0
type: Answer
score: 1
has body: It would help if you provided an example of what exactly happens when you pass all the values. Otherwise, what according to me, could be causing the problem is that the 'Null' object in python is the singleton None. The best way to check things for "Noneness" is to use is not None or better still, something as simple as: {%if lat%} {{lat}} {% endif %} Also, can't you assign GeJ to the var GeJ within the div instead of putting a line of JS in an abrupt manner up there? P.S. I wanted to add this as a comment, but don't have enough reputation. Apologies.
upvote count: 1
answers question: http://stackoverflow.com/q/50864230

http://stackoverflow.com/a/50901392
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/50898857
has comment: http://stackoverflow.com/comment/88831783
has comment: http://stackoverflow.com/comment/88835693
upvote count: 1
type: AcceptedAnswer
has body: To change the screen, there are two ways to do it. The first method is all done in kv file. The second method is done in Python file. In the example demonstrates both methods. Method 1 - kv file You could put the code for changing screen in the kv file by replacing: root.change_screen(dashboard) with app.root.ids.screen.current = 'Dashboard' # 'Dashboard' name of screen Method 2 - Python &amp; kv files In kv file, pass the name of the screen to change_screen() function e.g. root.change_screen('Dashboard'). In Python file, replace self.ids.screens.ids.manager.current with self.parent.ids.screen.current in change_screen() method. Note AttributeError self.ids.screens.ids.manager.current = argument AttributeError: 'super' object has no attribute '__getattr__' Explanation self - The keyword self references the “current widget instance” i.e. class UpperMenu() ids - The keyword ids references the lookup object and it is a dictionary type property. In this case, all the Button widgets tagged with id’s under the class rule &lt;UpperMenu&gt;: in the kv file. screens - The keyword screens reference the id's for screens but it does not exist under self.ids. Due to this, Kivy threw AttributeError. Add print(self.ids) to display all the ids found in self.ids. Example test.kv #:kivy 1.10.0 &lt;Container&gt;: id: container UpperMenu: id: uppermenu pos: root.x, root.top - self.height Screens: id: screens &lt;UpperMenu&gt;: size_hint: 1,.15 Button: text: "" id: ButtonCeasuri on_release: root.change_screen('Dashboard') # Method 2 Image: source: 'dashboard.png' allow_stretch: False center_x: self.parent.center_x center_y: self.parent.center_y Button: text: "" id: ButtonCeasurii on_release: app.root.ids.screens.current = 'Player' # Method 1 Image: source: 'play-button.png' allow_stretch: False center_x: self.parent.center_x center_y: self.parent.center_y Button: text: "" id: ButtonCeasuriii Image: source: 'distance.png' allow_stretch: False center_x: self.parent.center_x center_y: self.…
type: Answer
has comment: http://stackoverflow.com/comment/88835013
accepted answer of: http://stackoverflow.com/q/50898857

http://stackoverflow.com/q/50936978
type: Question
has comment: http://stackoverflow.com/comment/88873043
has body: I am new to python GUI and have never used python GUI before. I just decided to gave a try. this is my function which convert local datetime to epoch, eg.py is the filename where both this functions are def epochConverter(a): return datetime(*a).timestamp() This functions takes two parameters of datetime and returns in timestamp (milliseconds) def DateExtraction(fromTime, toTime): convertedFromTime = int(epochConverter(fromTime)*1000) convertedtoTime = int(epochConverter(toTime)*1000) time = {'from':convertedFromTime,'to':convertedtoTime} return time this works as expected print(DateExtraction((2018,6,8,0,0,0), (2018,6,8,1,0,0))) Now, I wanted to implement this in python GUI and I am using appjar library. This simple GUI code looks like this from appJar import gui from eg import DateExtraction class MyApplication(): # Build the GUI def Prepare(self, app): # Form GUI app.setTitle("Simple Application") app.setFont(16) app.setStopFunction(self.BeforeExit) app.addLabel('oneTime',"From Time:", 0, 0) app.addEntry("fromTime", 0, 1) app.addLabel('twoTime',"To Time:", 1, 0) app.addEntry("toTime", 1, 1) app.addButtons(["Submit"], self.Submit, colspan=2) return app def Start(self): # Creates a UI app = gui() app = self.Prepare(app) self.app = app app.go() def BeforeExit(self): return self.app.yesNoBox("Confirm Exit", "Are you sure you want to exit?") def Submit(self, btnName): if btnName == "Submit": timefrom = self.app.getEntry("fromTime") timeto = self.app.getEntry("toTime") DateExtraction(timefrom, timeto) if __name__ == '__main__': App = MyApplication() App.Start() When the GUI runs, I fill both text fields as it is 2018,6,8,0,0,0 2018,6,8,1,0,0 and it throws error TypeError: function takes at most 9 arguments (14 given) I also tried, just in case (2018,6,8,0,0,0) (2018,6,8,1,0,0) and again throws the same error type error, functions takes bla bla arguments (bla bla given) I am new in python GUI and any kind of suggestions is welcome. Also any suggestions about tkinter to …
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/88873092
favorite count: 0
has answer: http://stackoverflow.com/a/50937256
tagged with: python
accepted answer: http://stackoverflow.com/a/50937256
score: 2
type: AnsweredQuestion
tagged with: tkinter
upvote count: 2
has title: Implementing python functions in python GUI

http://stackoverflow.com/a/50958977
has comment: http://stackoverflow.com/comment/88916557
score: 2
upvote count: 2
has body: I did some profiling to get a sense of what the actual difference between these is. You can find the REPL here from timeit import timeit import math from math import sin x = 10_000_000 def from_import(): for _ in range(x): sin(100) def import_module(): for _ in range(x): math.sin(100) def local_var(): s = math.sin for _ in range(x): s(100) def local_import(): from math import sin for _ in range(x): sin(100) funcs = (from_import, import_module, local_var, local_import) for func in funcs: print("{:&lt;15} {}".format( func.__name__, timeit( func.__name__ + '()', number=1, globals=globals()))) The results: from_import 4.354339323996101 import_module 5.608195230990532 local_var 3.982630196987884 local_import 3.9956486110022524 I was surprised that the local names were that much more performant over the global names. Both vastly outperform additional attribute lookups.
answers question: http://stackoverflow.com/q/50956798
downvote count: 0
type: Answer

http://stackoverflow.com/a/50965631
type: Answer
answers question: http://stackoverflow.com/q/50965335
has body: In addition to mehrdad-pedramfar answer: If using numpy is not a problem you can convert your list of tuples to a numpy array and then just use indexing. import numpy as np short_example = np.array([(1,2),(2,4),(4,6)]) short_example[:,0] gives a numpy array of all x values: array([1, 2, 4]) short_example[:,1] gives a numpy array of all y values: array([2, 4, 6])
score: 1
upvote count: 1
downvote count: 0

http://stackoverflow.com/comment/89000525
type: Comment
has text: Hi @user8212173, I could not find any method = post or . you can see there is no post method in the code which I posted above. Can you please suggest where I can find that.
comment on: http://stackoverflow.com/q/51002133
score: 0
type: QuestionComment

http://stackoverflow.com/q/50932221
has comment: http://stackoverflow.com/comment/88866436
tagged with: pandas
answer count: 1
has body: I have a master dataframe "master_df" that has as dates in one column and a list of dataframes in another column. In each dataframe within the master_df there is a column for dates, and a price associated with each date. I tried doing the following: prices = [] for index, row in master_df.iterrows(): pre_data = pd.read_csv(Path + row['Dataframe'] + '.csv') data = pre_data.set_index('Date') prices.append(data.loc[row['Date'], 'Price']) This produces the error: 'the label [12/22/2002] is not in the index' What's confusing is that when I do the same thing, but enter in the date manually, it works: for index, row in master_df.iterrows(): pre_data = pd.read_csv(Path + row['Dataframe'] + '.csv') data = pre_data.set_index('Date') prices.append(data.loc['12/22/2002', 'Price']) I checked the datatype of my index after I set it to date, and it is in a string. I'm stumped as to why it doesn't work when I grab with "row['Date']" when it's being read as a string, but it does work when entered manually. I realize there may be an easier way to grab these prices, keep in mind this is a part of a large complex function, so I am just trying to figure out this specific error. In other words, I have to grab it with row['Date']. Please advise as to how I can work around this error. Thank you!
has comment: http://stackoverflow.com/comment/88866504
has comment: http://stackoverflow.com/comment/88863617
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88865720
has answer: http://stackoverflow.com/a/50933927
type: Question
has comment: http://stackoverflow.com/comment/88863755
has comment: http://stackoverflow.com/comment/88865574
tagged with: dataframe
has title: index not being recognized in pandas
score: 0

http://stackoverflow.com/q/50987944
tagged with: pyspark
downvote count: 0
tagged with: apache-spark
has answer: http://stackoverflow.com/a/69491764
answer count: 7
has body: I'm trying to run this code: import pyspark from pyspark.sql import SparkSession spark = SparkSession.builder \ .master("local") \ .appName("Word Count") \ .getOrCreate() df = spark.createDataFrame([ (1, 144.5, 5.9, 33, 'M'), (2, 167.2, 5.4, 45, 'M'), (3, 124.1, 5.2, 23, 'F'), (4, 144.5, 5.9, 33, 'M'), (5, 133.2, 5.7, 54, 'F'), (3, 124.1, 5.2, 23, 'F'), (5, 129.2, 5.3, 42, 'M'), ], ['id', 'weight', 'height', 'age', 'gender']) df.show() print('Count of Rows: {0}'.format(df.count())) print('Count of distinct Rows: {0}'.format((df.distinct().count()))) spark.stop() And getting an error 18/06/22 11:58:39 ERROR SparkUncaughtExceptionHandler: Uncaught exception in thread Thread[main,5,main] java.util.NoSuchElementException: key not found: _PYSPARK_DRIVER_CALLBACK_HOST ... Exception: Java gateway process exited before sending its port number I'm using PyCharm and MacOS, Python 3.6, Spark 2.3.1 What is the possible reason of this error?
favorite count: 0
linked to: http://stackoverflow.com/q/56028402
has answer: http://stackoverflow.com/a/50988318
possible better answer: http://stackoverflow.com/a/51213220
score: 13
tagged with: python
has answer: http://stackoverflow.com/a/51213220
has answer: http://stackoverflow.com/a/63212437
upvote count: 13
has answer: http://stackoverflow.com/a/54199149
type: AnsweredQuestion
has title: key not found: _PYSPARK_DRIVER_CALLBACK_HOST
accepted answer: http://stackoverflow.com/a/50988318
type: Question
has answer: http://stackoverflow.com/a/59408093
has answer: http://stackoverflow.com/a/61088782

http://stackoverflow.com/q/50903244
has comment: http://stackoverflow.com/comment/88806734
has comment: http://stackoverflow.com/comment/88806750
score: 0
has answer: http://stackoverflow.com/a/50903304
linked to: http://stackoverflow.com/q/3889769
type: UnansweredQuestion
tagged with: django
tagged with: python
has title: How to print all recieved post request include headers in python
has comment: http://stackoverflow.com/comment/88806836
has body: I am a python newbie and i have a controler that get Post requests. I try to print to log file the request that it receive, i am able to print the body but how can i extract all the request include the headers? I am using request.POST.get() to get the body/data from the request. Thanks
has comment: http://stackoverflow.com/comment/88806401
type: Question
has answer: http://stackoverflow.com/a/50903353
answer count: 2

http://stackoverflow.com/a/51462672
type: Answer
has body: Because you are looking for a single bounding box, don't use regionprops or any per-object function. This also makes it so that you don't need to try to make a single object out of all the yellow dots. The simplest solution here is to walk over the image, and for each pixel, determine if it is "yellow enough" (whatever that means for your application). If so, add the pixel's coordinates to the running bounding box calculation. The bounding box calculation is quite simple: top_left = [1e9, 1e9] bottom_right = [0, 0] for ...: # within your loop over the pixels, [x, y] are the current coordinates top_left = [min(top_left[0], x), min(top_left[1], y)]; bottom_right = [max(bottom_right[0], x), max(bottom_right[1], y)]; There might be a way with skimage to do this without loops, but I don't know that package at all.
score: 0
answers question: http://stackoverflow.com/q/50902373

http://stackoverflow.com/q/50957742
has body: I have ran into some trouble. I'm quite new to OOP and working with tkinter and GUI's in general. I have managed to find some code on the Internet and meshed it all together to create something and I'm nearly where I want to be. So what I want is some help figuring this out. How can I assign results of askdirectory to a variable I can use elsewhere? # coding=utf-8 import tkinter as tk from tkinter import font as tkfont from tkinter import filedialog class MainApp(tk.Tk): .... class SelectFunction(tk.Frame): .... class FunctionChangeName(tk.Frame): .... a = Gui(self) # this gets me the askdirectory but how to add it to a variable? Above is the call to run askdirectory code, and it works, just need to find out how to save it to a variable so I can use it, I have tried to print it in several ways, but all I get is something along the lines .!frame.!functionchangename.!gui. class SelectDir: def __init__(self, container, title, initial): self.master = container self.initial = initial self.selected = initial self.options = {'parent': container,'title': title,'initialdir':initial,} def show(self): result = filedialog.askdirectory() if result: self.selected = result def get(self): return self.selected class Gui(tk.Frame): def __init__(self, container): tk.Frame.__init__(self, container) frame = tk.Frame(container) frame.pack() self.seldir = SelectDir(self, "Select directory", "D:\\MyPgm\\Python\\Tiles_8") button = tk.Button(frame, text="Select directory", command=self.select_dir) button.grid(column=0, row=0) self.act_dir = tk.StringVar() self.act_dir.set("D:\\MyPgm\\Python\\Tiles_8") entry = tk.Entry(frame, textvariable=self.act_dir, width=30) entry.grid(column=0, row=1) def select_dir(self): self.seldir.show() self.act_dir.set(self.seldir.get()) # or # result = seldir.show() # self.act_dir.set(result) if __name__ == "__main__": app = MainApp() app.mainloop()
answer count: 1
has comment: http://stackoverflow.com/comment/88937013
score: 0
tagged with: python
tagged with: tkinter
linked to: http://stackoverflow.com/q/50964709
has title: How to save askdirectory result in a variable I can use using tkinter with OOP?
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/36105688
has comment: http://stackoverflow.com/comment/88913584
has comment: http://stackoverflow.com/comment/88936881
tagged with: oop
has answer: http://stackoverflow.com/a/60574263
has comment: http://stackoverflow.com/comment/88917928
type: Question
has comment: http://stackoverflow.com/comment/88918239

http://stackoverflow.com/comment/88940646
type: Comment
type: QuestionComment
has text: the `item` is scoped inside `any()` - thats why.
comment on: http://stackoverflow.com/q/50972054
score: 0

http://stackoverflow.com/q/50867053
tagged with: windows
has title: How can I sniff packets using Scapy without any CMD opened?
has answer: http://stackoverflow.com/a/50889287
tagged with: python
tagged with: cmd
type: UnansweredQuestion
tagged with: scapy
type: Question
answer count: 1
tagged with: powershell
score: 0
has body: I'm trying to write a script to sniff some packets and send others according to the sniff. I also want that script to be completely invisible to the user (so it could only be seen from Task Manager). I tried changing the script extension to .pyw so it would run with pythonw.exe, and it kind of works. However a PowerShell window opens up and when closed, shuts off the pythonw process as well. I read some on the web and understood Scapy creates it in order to get access to low level networking requests. I also found code to change it into a regular CMD. However I don't want it to change to another shell type, I want this shell to disappear completely so there's no indication om the desktop that the script is running. How do I achieve this? Is there a way to request scapy to create this shell as a background process? Or is there a way to move an already running CMD to the background? Thanks in advance! PS: The code to change the PowerShell to CMD is: POWERSHELL_PROCESS.close() conf.prog.powershell = None POWERSHELL_PROCESS.__init__() After the import, and was found here.

http://stackoverflow.com/comment/89011944
type: QuestionComment
has text: I’m sorry, I don’t have a Windows system at the moment to test on. I don’t know.
comment on: http://stackoverflow.com/q/51008838
score: 0
type: Comment

http://stackoverflow.com/a/50983889
has body: have a look at pandas.DataFrame.shift. This is a column-wise operation that shifts all rows in a given column to another row of another column: # original df x1 0 0 1 1 2 2 3 3 4 4 # shift down df.x2 = df.x1.shift(1) x1 x2 0 0 NaN # Beware 1 1 0 2 2 1 3 3 2 4 4 3 # Shift up df.x2 = df.x1.shift(-1) x1 x2 0 0 1 1 1 2 2 2 3 3 3 4 4 4 NaN # Beware You can use this to move spo2 of timestamp n+1 next to spo2 in the timestamp n row. Then, filter based on conditions applied to that one row. df['spo2_Next'] = df['spo2'].shift(-1) # replace NaN to allow float comparison df.spo2_Next.fillna(1, inplace = True) # Apply your row-wise condition to create filter column df.loc[((df.spo2_Next - df.spo2) &gt; 1) or ((df.spo2_Next - df.spo2) &lt; 1), 'Outlier'] = True # filter df_clean = df[df.Outlier != True] # remove filter column del df_clean['Outlier']
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50983782
answers question: http://stackoverflow.com/q/50983782
score: 3
upvote count: 3
type: AcceptedAnswer

http://stackoverflow.com/q/50920091
has comment: http://stackoverflow.com/comment/88839916
upvote count: 0
answer count: 1
linked to: http://stackoverflow.com/q/4706499
has title: How to append content with existing file?
favorite count: 0
duplicate of: http://stackoverflow.com/q/4706499
type: UnansweredQuestion
score: -3
tagged with: python
downvote count: 3
type: Question
has answer: http://stackoverflow.com/a/50920111
has comment: http://stackoverflow.com/comment/88839932
has body: How to append the content with the existing content in a same file? But It show now and existing content also..

http://stackoverflow.com/comment/88949709
type: QuestionComment
score: 1
has text: You can. I'd recommend using PyMYSQL (https://github.com/PyMySQL/PyMySQL).
comment on: http://stackoverflow.com/q/50976837
type: Comment

http://stackoverflow.com/a/56501199
score: 20
downvote count: 0
type: Answer
upvote count: 20
answers question: http://stackoverflow.com/q/50960539
has body: A little late to answer this, but I had the same question just now. I found the solution buried in this issue on their Github repository. To change the target of the log you can use import os from selenium import webdriver # to create a driver with no log driver = webdriver.Firefox(service_log_path=os.devnull) # or to just rename the log file driver = webdriver.Firefox(service_log_path='my-app.log') Initially I got a deprecation warning when I used the keyword argument log_path (as suggested in the issue) but that will vary on the version you're using. I'm using selenium==3.141.0.

http://stackoverflow.com/a/50914545
has comment: http://stackoverflow.com/comment/102087163
has comment: http://stackoverflow.com/comment/88862692
downvote count: 0
has comment: http://stackoverflow.com/comment/88831803
score: 1
has comment: http://stackoverflow.com/comment/88868611
has comment: http://stackoverflow.com/comment/88868964
has comment: http://stackoverflow.com/comment/88832307
has comment: http://stackoverflow.com/comment/88904353
upvote count: 1
has body: If I have understood your question correctly then you want to changes the parameters of the decision trees inside the random forest ? I am not exactly sure why you would want to do that. I will break the solution into two parts First we will try to change the parameters of a decision tree from sklearn.tree import DecisionTreeClassifier from sklearn.datasets import load_iris clf = DecisionTreeClassifier(random_state=0) iris = load_iris() clf.fit(iris.data,iris.target) #DecisionTreeClassifier(class_weight=None, criterion='gini', max_depth=None, # max_features=None, max_leaf_nodes=None, # min_impurity_decrease=0.0, min_impurity_split=None, # min_samples_leaf=1, min_samples_split=2, # min_weight_fraction_leaf=0.0, presort=False, random_state=0, # splitter='best') #Now extract the parameters parameters_dt = clf.get_params() #Now change the parameter you want parameters_dt['max_depth'] = 3 #Now create a new classifier new_clf = DecisionTreeClassifier(**parameters_dt) #DecisionTreeClassifier(class_weight=None, criterion='gini', max_depth=2, # max_features=None, max_leaf_nodes=None, # min_impurity_decrease=0.0, min_impurity_split=None, # min_samples_leaf=1, min_samples_split=2, # min_weight_fraction_leaf=0.0, presort=False, random_state=0, # splitter='best') Now lets get back to Random Forest from sklearn.ensemble import RandomForestClassifier from sklearn.tree import DecisionTreeClassifier from sklearn.datasets import make_classification X, y = make_classification(n_samples=1000, n_features=4, n_informative=2, n_redundant=0, random_state=0, shuffle=False) clf = RandomForestClassifier(max_depth=2, random_state=0) clf.fit(X, y) clf_list = clf.estimators_ for idx in range(0,len(clf_list)): #Get the current Decision Tree in Random Forest estimator = clf_list[idx] #Get the params temp_params = estimator.get_params() #Change the params you want temp_params['max_depth'] = 3 #Create a new decision tree temp_decision_tree = DecisionTreeClassifier(**temp_params) #Remove the old deci…
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50913468
has comment: http://stackoverflow.com/comment/88864983
answers question: http://stackoverflow.com/q/50913468
type: Answer

http://stackoverflow.com/comment/88912082
comment on: http://stackoverflow.com/a/50957008
has text: @bipll what exactly is an iterator object??? I mean it's not a list or tuple.... what is its form?? I mean lists are like this [1,2,3] while tuples are like (1,2,3) and also these have some functions and operations to work with them.... what is the case with an iterator object
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50999881
has answer: http://stackoverflow.com/a/50999995
type: Question
tagged with: jit
tagged with: raspberry-pi
has body: I want to run a python program with numba. I have try install numba using: sudo apt install libblas-dev llvm python3-pip python3-scipy sudo pip install llvmlite==0.15.0 sudo pip install numba==0.30.1 and also searching on other references to install numba. Numba can be imported, but when I run the program with @jit decorator, it tells: Traceback (most recent call last): File "Ambil_Data.py", line 12, in &lt;module&gt; @njit#(fastmath=True) File "/usr/local/lib/python2.7/dist-packages/numba/decorators.py", line 209, in njit return jit(*args, **kws) File "/usr/local/lib/python2.7/dist-packages/numba/decorators.py", line 151, in jit return wrapper(pyfunc) File "/usr/local/lib/python2.7/dist-packages/numba/decorators.py", line 167, in wrapper **dispatcher_args) File "/usr/local/lib/python2.7/dist-packages/numba/dispatcher.py", line 423, in __init__ self.targetctx = self.targetdescr.target_context File "/usr/local/lib/python2.7/dist-packages/numba/targets/registry.py", line 54, in target_context return self._toplevel_target_context File "/usr/local/lib/python2.7/dist-packages/numba/utils.py", line 278, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python2.7/dist-packages/numba/targets/registry.py", line 38, in _toplevel_target_context return cpu.CPUContext(self.typing_context) File "/usr/local/lib/python2.7/dist-packages/numba/targets/base.py", line 232, in __init__ self.init() File "/usr/local/lib/python2.7/dist-packages/numba/targets/cpu.py", line 42, in init self._internal_codegen = codegen.JITCPUCodegen("numba.exec") File "/usr/local/lib/python2.7/dist-packages/numba/targets/codegen.py", line 479, in __init__ self._init(self._llvm_module) File "/usr/local/lib/python2.7/dist-packages/numba/targets/codegen.py", line 495, in _init self._mpm = self._module_pass_manager() File "/usr/local/lib/python2.7/dist-packages/numba/targets/codegen.py", line 535, in _module_pass_manager dl.add_pass(pm) AttributeError: 'TargetData' object ha…
score: 0
tagged with: llvm
accepted answer: http://stackoverflow.com/a/50999995
answer count: 1
tagged with: numba
tagged with: python
has title: Running Numba Jit on Raspberry Pi 3
type: AnsweredQuestion

http://stackoverflow.com/comment/88802163
has text: Possible duplicate of [PyYAML interprets string as timestamp](https://stackoverflow.com/questions/28835322/pyyaml-interprets-string-as-timestamp)
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50900727

http://stackoverflow.com/q/50880303
has title: Python - Pickle Spacy for PySpark
accepted answer: http://stackoverflow.com/a/51542562
type: Question
tagged with: user-defined-functions
answer count: 2
has body: The documentation for Spacy 2.0 mentions that the developers have added functionality to allow for Spacy to be pickled so that it can be used by a Spark Cluster interfaced by PySpark, however, they don't give instructions on how to do this. Can someone explain how I can pickle Spacy's English-language NE parser to be used inside of my udf functions? This doesn't work: from pyspark import cloudpickle nlp = English() pickled_nlp = cloudpickle.dumps(nlp)
tagged with: pyspark
downvote count: 0
has comment: http://stackoverflow.com/comment/90052540
has comment: http://stackoverflow.com/comment/90051075
tagged with: apache-spark
has comment: http://stackoverflow.com/comment/90048371
has answer: http://stackoverflow.com/a/51559077
score: 8
has answer: http://stackoverflow.com/a/51542562
favorite count: 0
upvote count: 8
possible better answer: http://stackoverflow.com/a/51559077
tagged with: python
has comment: http://stackoverflow.com/comment/90049679
type: AnsweredQuestion

http://stackoverflow.com/a/50941976
has comment: http://stackoverflow.com/comment/88955846
downvote count: 0
has comment: http://stackoverflow.com/comment/88956366
type: Answer
upvote count: 3
has body: You can try it the following way with a little help from numpy import pandas as pd import numpy as np import os path 'F:/Work/' files_in_dir = [f for f in os.listdir(path) if f.endswith('csv')] temp_data = [] for filenames in files_in_dir: temp_data.append(np.loadtxt(filenames,dtype='str')) temp_data = np.array(temp_data) np.savetxt('out.csv',temp_data.transpose(),fmt='%s',delimiter=',')
score: 3
answers question: http://stackoverflow.com/q/50941165

http://stackoverflow.com/comment/89000703
comment on: http://stackoverflow.com/a/50995920
type: AnswerComment
has text: @Dan I checked and it works. Please try again and be careful to do it right. Start from your second version. Remove the body of the except block, i.e. the line starting with `stringToCheck =` and copy it to a string variable --- `ctr`, say --- outside the function. Copy and paste the three lines I've posted to the except block and make sure to get indentation right. Now test with parameters that worked before, for example `'!', '11!/10!', ctr`
type: Comment
score: 0

http://stackoverflow.com/comment/88929862
has text: @Aran-Fey it's a JSON. let x={'firstName': {'value': 'xyz'}} and y=x['firstName'] I am calling a function with input parameter as fun(y) which assigns 'xyz' .thus I was only able to use y['value']='xyz'.
score: 0
comment on: http://stackoverflow.com/q/50966390
type: Comment
type: QuestionComment

variables
tag name: variables
tags question: http://stackoverflow.com/q/50969736
tags question: http://stackoverflow.com/q/50990679
tags question: http://stackoverflow.com/q/50933100
tags question: http://stackoverflow.com/q/50888544
tags question: http://stackoverflow.com/q/50970511
tags question: http://stackoverflow.com/q/50882356
tags question: http://stackoverflow.com/q/50869910
type: Tag
tags question: http://stackoverflow.com/q/50942784
tags question: http://stackoverflow.com/q/50974075
tags question: http://stackoverflow.com/q/51003119
tags question: http://stackoverflow.com/q/50987777
tags question: http://stackoverflow.com/q/50962731
tags question: http://stackoverflow.com/q/50922474
tags question: http://stackoverflow.com/q/50901241
tags question: http://stackoverflow.com/q/50865854

http://stackoverflow.com/a/50931435
downvote count: 0
has body: OK, the only solution I came up with is making the arity of the function explicit, i.e. from typing import Any, Callable, TypeVar A = TypeVar('A') B = TypeVar('B') C = TypeVar('C') def say_hi_and_call_ternary(func: Callable[[A, B, C], Any], a: A, b: B, c: C): print('Hi.') func(a, b, c) def foo(a: str, b: float, c: int): print(a, b, c + 1) say_hi_and_call_ternary(foo, 'ok', 2.2, 'bad') Of course one would need a similar say_hi_and_call_unary and say_hi_and_call_binary etc. too. But since I value my application not exploding in PROD over saving some LOC, I'm happy when mypy is able to report the error, which now certainly is the case: error: Argument 1 to "say_hi_and_call_ternary" has incompatible type "Callable[[str, float, int], Any]"; expected "Callable[[str, float, str], Any]"
score: 1
answers question: http://stackoverflow.com/q/50895191
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50895191
type: Answer

http://stackoverflow.com/q/50869177
score: 0
has answer: http://stackoverflow.com/a/50869445
has answer: http://stackoverflow.com/a/50869404
has comment: http://stackoverflow.com/comment/88740086
favorite count: 0
has answer: http://stackoverflow.com/a/50869264
has title: Searching for list in list python
upvote count: 2
type: UnansweredQuestion
downvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/88740074
answer count: 4
tagged with: computer-science
type: Question
has answer: http://stackoverflow.com/a/50869214
has body: Let's say I have the following main_list that contains other small_lists: main_list = [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]] I want to find the small_list knowing the index 0 and 1 of the small_lists. So for instance, how can I create a getlist() function such that: getlist(4,5) = [4, 5, 6, 7] getlist(0,1) = [0, 1, 2, 3] getlist(5,5) = None getlist(9,10) = None
tagged with: arraylist

http://stackoverflow.com/a/51010436
answers question: http://stackoverflow.com/q/51010361
upvote count: 1
has body: conda create -n myEnv python=3.6 That should include all the default packages in your environment. Having said that, I do think it's good practice to only have packages installed that you actually need. Do you really require everything conda includes as default? EDIT: Ok I just double checked and conda really doesn't include as much as I thought. Here is the list of default packages for a python 3.6 env: ca-certificates: 2018.4.16-0 conda-forge certifi: 2018.4.16-py36_0 conda-forge libgcc-ng: 7.2.0-hdf63c60_3 ncurses: 5.9-10 conda-forge openssl: 1.0.2o-0 conda-forge pip: 9.0.3-py36_0 conda-forge python: 3.6.5-1 conda-forge readline: 7.0-0 conda-forge setuptools: 39.2.0-py36_0 conda-forge sqlite: 3.20.1-2 conda-forge tk: 8.6.7-0 conda-forge wheel: 0.31.0-py36_0 conda-forge xz: 5.2.3-0 conda-forge zlib: 1.2.11-h470a237_3 conda-forge
score: 0
downvote count: 1
type: Answer

http://stackoverflow.com/comment/88730501
type: QuestionComment
comment on: http://stackoverflow.com/q/50863652
has text: ...Does your function do *wildly* different things depending on whether it gets an `int`, `float`, or `Decimal`? If so, it should probably be multiple functions instead.
score: 0
type: Comment

http://stackoverflow.com/a/51009919
type: Answer
answers question: http://stackoverflow.com/q/50992875
has body: If you want to know the current joint properties (position and rate), you can just request the Gazebo service /gazebo/get_joint_properties. You just have to write a python service client as explained here, or you can also first try to get the information via rqt_service_caller.
score: 0

http://stackoverflow.com/comment/88838311
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50919167
has text: Once you exit a `while` loop, you've exited it; changing the predicate back won't change anything. To make that work, you'd need another `while` loop, maybe a `while True:`, around the whole thing (including the `e.wait()`).

http://stackoverflow.com/comment/88739710
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50869011
has text: May be they should be hashing the type too
type: AnswerComment

http://stackoverflow.com/q/50960719
tagged with: python
tagged with: recursion
type: AnsweredQuestion
tagged with: oop
accepted answer: http://stackoverflow.com/a/50960965
type: Question
has answer: http://stackoverflow.com/a/50960965
tagged with: python-2.7
score: 0
answer count: 1
tagged with: python-3.x
has title: Tree structure with values for internal nodes, arguments to __init__ method
has body: Below class represents a tree structure with internal node values. A fibonacci recursive function is used to make a fib_tree. I haven't come across the return call to class below in fib_tree. The notation Tree (left.entry + right.entry, left, right) has left me confused. In OOP, I am familiar with obj_inst.att, obj_inst.method(), properties, self, __init__ etc. Here left.entry + right.entry - left, right and entry are attributes of the object instance itself, then what does attribute.attribute mean?. What exactly is being passed here to __init__? Is this a popular technique, does it have a name that I can research on? class Tree (object): def __init__(self, entry , left = None, right = None): self.entry = entry self.right = right self.left = left def __repr__(self): args = repr(self.entry) if self.left or self.right: args += ' , {0}, {1}'.format (repr(self.left), repr(self.right)) return 'Tree ({0})'. format (args) def fib_tree (n): if n == 1: return Tree (0) if n == 2: return Tree (1) left = fib_tree (n-2) right = fib_tree (n-1) return Tree (left.entry + right.entry, left, right) fib_tree (4) #Tree (2 , Tree (1), Tree (1 , Tree (0), Tree (1)))

http://stackoverflow.com/comment/88917949
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50960308
has text: @phihag "Remove comments" - seriously? How does the presence of comments affect the performance?

http://stackoverflow.com/q/50892066
downvote count: 0
has answer: http://stackoverflow.com/a/50892548
favorite count: 0
answer count: 3
has title: ModuleNotFoundError while package already installed
type: UnansweredQuestion
has body: My distribution is WinPython and I use Spyder as an IDLE, my python version is 3.6.5. Although I have so many modules (from the WinPython download) like pip, pandas, and numpy that work perfectly, I want now to download another package called Swampy. So, I wrote to my IPython console: !pip install Swampy and it worked perfectly but when I wrote import Swampy the result was a ModuleNotFoundError! Lastly, I have to mention that all the packages seem to be here C:\Users\MY_USERNAME\Downloads\WinPython\python-3.6.5.amd64\Lib\site-packages
upvote count: 1
tagged with: python
score: 1
has answer: http://stackoverflow.com/a/50895161
type: Question
has answer: http://stackoverflow.com/a/50892139
tagged with: python-import

http://stackoverflow.com/comment/88775058
score: 0
type: Comment
type: QuestionComment
has text: It's unclear if you have a dictionary or a list that contains all your words. In the example you show us a dictionary but you refer to it as "main list". Please make this clear.
comment on: http://stackoverflow.com/q/50886718

http://stackoverflow.com/q/50902933
has answer: http://stackoverflow.com/a/50902971
favorite count: 0
downvote count: 0
has title: Class methods in python: default kwargs from attributes of self
score: 6
tagged with: python
type: AnsweredQuestion
type: Question
possible better answer: http://stackoverflow.com/a/50902971
answer count: 2
has body: Is it possible to define a class method which takes an attribute of self as a default keyword argument? i.e. I'd like to do something equivalent to the following: class Foo: def __init__(self, bar): self.bar = bar def do_a_thing(self, my_arg=self.bar): do_something_else(my_arg) Of course this throws an error: x = Foo(y) x.do_a_thing() NameError: name 'self' is not defined Hopefully it is clear what kind of behavior I am hoping to get. Calling x.do_a_thing() should be equivalent to x.do_a_thing(my_arg=x.bar). Is there a way to do this?
upvote count: 6
tagged with: keyword-argument
has answer: http://stackoverflow.com/a/50902968
accepted answer: http://stackoverflow.com/a/50902968

http://stackoverflow.com/a/50907222
accepted answer of: http://stackoverflow.com/q/50907049
type: Answer
upvote count: 1
has body: UPDATE1: here is a snippet for an upper triangular distance matrix (it shouldn't really matter as the distance matrix is always symmetric): from itertools import combinations res = {tup[0]:tup[1] for tup in zip(pdist(points), list(combinations(range(len(points)), 2)))} result: In [111]: res Out[111]: {1.4142135623730951: (0, 1), 4.69041575982343: (0, 2), 4.898979485566356: (1, 2)} UPDATE2: this version will support duplicates in distances: In [164]: import pandas as pd first we construct a Pandas.Series: In [165]: s = pd.Series(list(combinations(range(len(points)), 2)), index=pdist(points)) In [166]: s Out[166]: 2.0 (0, 1) 6.0 (0, 2) 12.0 (0, 3) 4.0 (1, 2) 10.0 (1, 3) 6.0 (2, 3) dtype: object now we can group by index and produce lists of coordinates: In [167]: s.groupby(s.index).apply(list) Out[167]: 2.0 [(0, 1)] 4.0 [(1, 2)] 6.0 [(0, 2), (2, 3)] 10.0 [(1, 3)] 12.0 [(0, 3)] dtype: object PS the main idea here is that you shouldn't build square distance matrix if you are going to flatten it afterwards and to get rid of duplicates.
score: 1
has comment: http://stackoverflow.com/comment/88817186
has comment: http://stackoverflow.com/comment/88818590
has comment: http://stackoverflow.com/comment/88819914
answers question: http://stackoverflow.com/q/50907049
has comment: http://stackoverflow.com/comment/88819451
has comment: http://stackoverflow.com/comment/88820045
has comment: http://stackoverflow.com/comment/88819663
has comment: http://stackoverflow.com/comment/88820452
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/50958377
has comment: http://stackoverflow.com/comment/88914612
answer count: 2
has comment: http://stackoverflow.com/comment/88914188
has body: I want to import a csv dataset. My problem is when I import the base, pandas kinds of try to convert it into something. Let me explain with numbers. This is more or less how my csv file is. &gt; Data, Id, Text &gt;2018-06-11, 17980873.3391, bla bla bla &gt;2018-06-11, 17980874.4560, bla bla bla &gt;2018-06-11, 17980876.8560, bla bla bla The trouble is when I import it with pd.read_csv. The Id column should be exactly the way it is in csv file (I want to use it as a filter to do searches) . But pandas is returning something like: When I import with no changes in the structure (pandas transform the column into float automatically) &gt; Data, Id, Text &gt;2018-06-11, 17980873.33910, bla bla bla &gt;2018-06-11, 17980874.45600, bla bla bla &gt;2018-06-11, 17980876.85600, bla bla bla when I import the dataset and transform the id column as type(str): &gt; Data, Id, Text &gt;2018-06-11, 17980873.3391, bla bla bla &gt;2018-06-11, 17980874.456, bla bla bla &gt;2018-06-11, 17980876.856, bla bla bla It is deleting and adding 0. I really don't know how to make pandas import the real number &gt;17980876.8560 Hope I've made myself understood. I'm still learning how to ask questions here. Thanks!
downvote count: 0
has comment: http://stackoverflow.com/comment/88918237
has comment: http://stackoverflow.com/comment/88914115
tagged with: series
accepted answer: http://stackoverflow.com/a/50958544
has title: Pandas - Importing CSV issue - adding and deleting 0 at the end
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has comment: http://stackoverflow.com/comment/88914455
has comment: http://stackoverflow.com/comment/88914379
has comment: http://stackoverflow.com/comment/88914266
favorite count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/88914674
tagged with: floating-point
has comment: http://stackoverflow.com/comment/88914390
type: Question
has comment: http://stackoverflow.com/comment/88914632
score: 2
has comment: http://stackoverflow.com/comment/88914385
has comment: http://stackoverflow.com/comment/88914432
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50958479
has comment: http://stackoverflow.com/comment/88914331
has answer: http://stackoverflow.com/a/50958479
has answer: http://stackoverflow.com/a/50958544

http://stackoverflow.com/q/50922725
has comment: http://stackoverflow.com/comment/88846349
tagged with: django
tagged with: python
has title: Loading static files referenced by other static files in django
has body: In my Python Django project I have a static html file (map.html). Inside this html file other static files are referenced. Like this: ... The static html file is referenced from a template file (index.html) using django template language as so: {% load static %} The problem is django can't find the static files (mfiles/leaflet_002.js etc.) referenced in the static html file (map.html), because in this html file (map.html), django template language cannot be used so django doesn't find path to these files. To make my architecture clean I present this simple diagram: django_template_file ----references----> map.html (static, loads fine) ----references----> mfiles/*.js etc. (PROBLEM django doesn't see those files) How can I tell django to look also in m_app/static/mfiles/* and not just to m_app/static/? Even though the static files in m_app/static/mfiles/ are referenced only from other static files located in m_app/static/ (and loaded correctly)? Relevant part of the file structure: m_project |______> m_app |______> __pychache__ |______> migrations |______> static |______> m_files ("this folder is referenced in map.html and django doens't see it") |______> leaflet_002.js |______> ... |______> map.html ("this is the static html file referenced from template index.html") |______> templates |______> m_app |______> index.html ("this is the template file I am talking about above") |______> __init__.py |______> admin.py |______> apps.py |______> models.py |______> tests.py |______> urls.py |______> views.py |______> m_project |______> __pychache__ |______> __init__.py |______> settings.py |______> urls.py |______> wsgi.py |______> db.sqlite3 |______> manage.py
type: Question
has answer: http://stackoverflow.com/a/50922787
score: 0
has comment: http://stackoverflow.com/comment/88844809
answer count: 1
type: UnansweredQuestion

http://stackoverflow.com/comment/88849185
score: 0
type: QuestionComment
type: Comment
has text: All are the same with exactly the same setup. Setup b with pgpool II is almost 20 seconds faster.
comment on: http://stackoverflow.com/q/50924843

http://stackoverflow.com/comment/88834394
type: QuestionComment
has text: Second, have you actually put the literal string `/path/to/python3` or `/path/to/python3/python` somewhere? If so, you were supposed to substitute that with the actual path to python3, like `/Library/Frameworks/Python.framework/Versions/3.6/bin/` or `/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6`.
type: Comment
score: 2
comment on: http://stackoverflow.com/q/50917156

http://stackoverflow.com/comment/88796140
type: QuestionComment
comment on: http://stackoverflow.com/q/50897987
has text: https://stackoverflow.com/a/6947758/2836621
score: 0
type: Comment

http://stackoverflow.com/q/50955128
answer count: 2
downvote count: 0
tagged with: database
tagged with: oracle-database
tagged with: sql
favorite count: 0
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50955387
tagged with: django
tagged with: python
score: 2
has title: How to get the last date from similar records? | Django
has answer: http://stackoverflow.com/a/50955365
type: Question
has body: I have next model. Also below you can see table with data. As you can for example A has 2 close records. The difference only in change_date column. I need to take only last date. How to make that with Django ORM? models.py: class Securities(models.Model): name= models.CharField() bool_value = models.BooleanField() code = models.CharField() change_date = models.DateField() bool_value = models.BooleanField() Lets say I have such Table: NAME | CODE | CHANGE_DATE | BOOL_VALUE A | 8328 | 15.02.2018 | 1 A | 8328 | 02.09.2018 | 0 B | 8328 | 02.09.2018 | 1 C | 8328 | 02.09.2018 | 1 C | 8328 | 20.09.2018 | 0 I want to filter next result: NAME | CODE | CHANGE_DATE | BOOL_VALUE A | 8328 | 02.09.2018 | 0 B | 8328 | 02.09.2018 | 1 C | 8328 | 20.09.2018 | 0

http://stackoverflow.com/comment/88961555
type: Comment
has text: i want to show only available car only after booked . in list view i had show if car is avaiable show it. after car booked is_available_car have to be false .
comment on: http://stackoverflow.com/q/50982757
score: 0
type: QuestionComment

http://stackoverflow.com/comment/88912014
type: QuestionComment
has text: Awesome. What does the fixed code look like?
comment on: http://stackoverflow.com/q/50953377
score: 0
type: Comment

http://stackoverflow.com/a/50912149
answers question: http://stackoverflow.com/q/50911501
score: 2
has body: Let's try using a dictionary instead of new variables: import pandas as pd import networkx as nx df=pd.read_csv('my_dataframe') sub_list=df.nodes_y.unique() sg_dict = {} for item in sub_list: sub_df=df[df['nodes_y']==item] sG_dict[item]=nx.Graph() #here I'd like to assign a name to the network #recursively based on the subset of the dataframe sG_dict[item].add_nodes_from(sub_df['nodes_x']) sG_dict[item].add_nodes_from(sub_df['nodes_y']) ##rest of the code
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50911501
has comment: http://stackoverflow.com/comment/88825636
has comment: http://stackoverflow.com/comment/88824813
upvote count: 2
has comment: http://stackoverflow.com/comment/88824728
has comment: http://stackoverflow.com/comment/88824983
has comment: http://stackoverflow.com/comment/88826275
has comment: http://stackoverflow.com/comment/88825883
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88828228
type: Answer

http://stackoverflow.com/comment/88936455
has text: `pcolor` does not add single pixels on a map. Instead it expects an array (together with positions) to plot. Try to separate data creation from plotting. Create one single array with what you want to show, then supply that single array (together with the respective coordinate arrays) to `pcolor`.
type: Comment
comment on: http://stackoverflow.com/q/50969238
score: 0
type: QuestionComment

http://stackoverflow.com/a/50990876
type: AcceptedAnswer
upvote count: 6
downvote count: 1
type: Answer
has body: According to userAccountControl flags: 512 - Normal account (512), 514 - Disable account (2 + 512), 66048 - Normal account + dont expire password (65536 + 512).
has comment: http://stackoverflow.com/comment/106246032
accepted answer of: http://stackoverflow.com/q/50988232
answers question: http://stackoverflow.com/q/50988232
score: 5

http://stackoverflow.com/a/50986949
answers question: http://stackoverflow.com/q/50986441
upvote count: 5
score: 5
downvote count: 0
has comment: http://stackoverflow.com/comment/88968821
has body: This has to do with what Python "variables" really are: name pointings to objects. Think of it as a dictionary with names as keys and objects as values. In your for loop, i initially points to the current iteration item in the list, ie i points to L[0], then to L[1] etc. But when you do i += 1 - which actually translates to i = i+1 - you rebind i so that it points to another object. This only affects the name i (what value the key holds), not the object it was pointing to before, so your list is indeed not changed. For a more in-depth explanation, you want to read Ned Batchelder's excellent article. This will save you a lot of time and frustrations ;) NB : for your example snippet, the proper way to update your list in place is to use enumerate: for index, value in enumerate(L): L[index] = value + 1 or to update the whole list inplace with a list comprehension: L[:] = [value+1 for value in L]
type: Answer
has comment: http://stackoverflow.com/comment/88969293
has comment: http://stackoverflow.com/comment/88969252

http://stackoverflow.com/comment/88949811
has text: *psst*: "zipwith" is just [`map`](https://docs.python.org/3/library/functions.html#map). (Yes, it supports multiple iterables)
comment on: http://stackoverflow.com/a/50976893
type: Comment
score: 2
type: AnswerComment

http://stackoverflow.com/q/51004029
favorite count: 0
upvote count: 8
possible better answer: http://stackoverflow.com/a/51004204
tagged with: python
has answer: http://stackoverflow.com/a/51004204
score: 8
has comment: http://stackoverflow.com/comment/89001597
has title: Create a new dataframe based on rows with a certain value
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51004086
type: Question
accepted answer: http://stackoverflow.com/a/51004086
has answer: http://stackoverflow.com/a/51004188
tagged with: dataframe
has body: I have a large dataframe of transactions which I want to break into two smaller dataframes based on a certain column ("Type"). If "Type" is "S" then add that entire row to the "cust_sell" dataframe, and if "Type" is "P" to the "cust_buy" dataframe. I am using a for loop, but this is only adding the index value to the dataframe. Any help is appreciated! from win32com.shell import shell, shellcon import pandas as pd filename = (shell.SHGetFolderPath(0, shellcon.CSIDL_PERSONAL, None, 0)) + '\MSRB T-1_test.xlsx' wb = pd.read_excel(filename, sheet_name='T1-20062017', index_col=0, header=0) cust_buy = [] cust_sell = [] # Create a list of customer buys and sells separately for i in wb.index: if wb['Type'][i] == 'S': cust_sell.append([i]) elif wb['Type'][i] == 'P': cust_buy.append([i])
answer count: 3
tagged with: pandas
downvote count: 0

http://stackoverflow.com/comment/88965445
type: Comment
score: 0
type: QuestionComment
has text: @Dark The strip() did the trick. Thanks.
comment on: http://stackoverflow.com/q/50982008

http://stackoverflow.com/a/62088100
answers question: http://stackoverflow.com/q/50966453
score: 0
type: Answer
has body: You can open a file by using open() and save it in a variable and keep using the variable wherever u wish to refer to the file. with open('Test.txt','r') as f: or f=open('Test.txt','r') and use f to refer to the file. If you want the file to be both readable &amp; writable, you can use r+ in place of r.

http://stackoverflow.com/a/50939813
answers question: http://stackoverflow.com/q/50939773
has comment: http://stackoverflow.com/comment/88885181
score: 0
has body: Your animate(self) method must return a tuple. You also need to show the plot. import matplotlib.animation as animation import matplotlib.pyplot as plt class Example: def __init__(self): self.fig = plt.figure() def update(self, num): print(f"This is getting called {num}") return num, def animate(self): ani = animation.FuncAnimation(self.fig, self.update, interval=100) plt.show() def main(): obj = Example() obj.animate() if __name__ == "__main__": main()
type: Answer
has comment: http://stackoverflow.com/comment/88887798
has comment: http://stackoverflow.com/comment/88887074

http://stackoverflow.com/q/50905222
possible better answer: http://stackoverflow.com/a/51096643
tagged with: interpolation
upvote count: 2
has comment: http://stackoverflow.com/comment/88811625
answer count: 2
accepted answer: http://stackoverflow.com/a/50988216
has comment: http://stackoverflow.com/comment/88814148
has comment: http://stackoverflow.com/comment/88814228
tagged with: dataframe
has body: I am having an issue where I have AIS data of several trips from Rotterdam to Hamburg. The route is split into 6 sectors, with the sector borders pre-defined for the route, and I need to know where and when a ship entered the next sector. I tried just using the last record within a sector, but the data's resolution isn't high enough for that. So I would like to interpolate the time and longitude based on the latitude of the sector border. You can see the borders I decided on for this trip in the following image. The longitude of crossing the border is always exactly on the border line. What I need to determine is the latitude at which this line is crossed by a ship. My DataFrame looks like this: TripID time Latitude Longitude SectorID 0 42 7 52.9 4.4 1 1 42 8 53.0 4.6 1 2 42 9 53.0 4.7 1 3 42 10 53.1 4.9 2 4 5 9 53.0 4.5 1 5 5 10 53.0 4.7 1 6 5 11 53.2 5.0 2 7 5 12 53.3 5.2 2 where the border between sectors 1 and 2 is pre-defined at longitude 4.8, so I would like to interpolate both the latitude and time at longitude 4.8 for each trip and sector border. I'm guessing a good solution will involve something like df.groupby(['TripID', 'SectorID']). I tried adding an entry for each trip and sector that only has the Latitude of the sector's border in it and then using interpolate, but adding the entries takes about an hour for me and interpolating the missing values crashes right away. The result I'm looking for should look like this: TripID time Latitude Longitude SectorID 0 42 7 52.9 4.4 1 1 42 8 53.0 4.6 1 2 42 9 53.0 4.7 1 8 42 9.5 53.05 4.8 1 3 42 10 53.1 4.9 2 4 5 9 53.0 4.5 1 5 5 10 53.0 4.7 1 9 5 10.3 53.06 4.8 1 6 5 11 53.2 5.0 2 7 5 12 53.3 5.2 2 I would also be happy about and able to work with a result that looks like this: TripID SectorID leave_lat leave_lon leave_time 42 1 53.05 4.8 9.5 5 1 53.06 4.8 10.3 Please ask, if my description of the problem isn't quite clear.
has comment: http://stackoverflow.com/comment/88813072
has comment: http://stackoverflow.com/comment/88813845
score: 2
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/50988216
favorite count: 0
has comment: http://stackoverflow.com/comment/88814295
has title: Interpolate specific entries in DataFrame depending on groups
has answer: http://stackoverflow.com/a/51096643
has comment: http://stackoverflow.com/comment/88814586
type: Question
tagged with: pandas
tagged with: python

http://stackoverflow.com/comment/136020731
has text: I downvote, because lone type variable (not bound in signature arguments) makes zero sense as a return type and shouldn't be used this way. `mypy` will even emit an error for such type variable. Only using `-> A` is a correct solution, and it is fully correct (since `A` and `B` are equivalent from typing perspective).
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50902210
type: Comment

http://stackoverflow.com/a/50985420
answers question: http://stackoverflow.com/q/50984718
score: 0
has body: Not tested, and there's probably a much better way with Mock but anyway: def mygetattr(self, name): if name == "tmp": self._tmp_was_accessed = True return super(A, self).__getattribute__(name) real_getattr = A.__getattribute__ A.__getattribute__ = mygetattr try: a = A() a._tmp_was_accessed = False b(a) finally: A.__getattribute__ real_getattr print(a._tmp_was_accessed)
type: Answer

plot
tags question: http://stackoverflow.com/q/50977764
tags question: http://stackoverflow.com/q/50869690
tags question: http://stackoverflow.com/q/50932614
tag name: plot
tags question: http://stackoverflow.com/q/50930770
tags question: http://stackoverflow.com/q/50928868
tags question: http://stackoverflow.com/q/50947776
tags question: http://stackoverflow.com/q/50892710
tags question: http://stackoverflow.com/q/50996810
tags question: http://stackoverflow.com/q/50911214
tags question: http://stackoverflow.com/q/51009887
tags question: http://stackoverflow.com/q/50883202
tags question: http://stackoverflow.com/q/50938167
tags question: http://stackoverflow.com/q/50912451
tags question: http://stackoverflow.com/q/50930889
tags question: http://stackoverflow.com/q/50898521
tags question: http://stackoverflow.com/q/50936819
type: Tag
tags question: http://stackoverflow.com/q/51008008
tags question: http://stackoverflow.com/q/50875637
tags question: http://stackoverflow.com/q/50936658
tags question: http://stackoverflow.com/q/50866141
tags question: http://stackoverflow.com/q/50871461
tags question: http://stackoverflow.com/q/50882880
tags question: http://stackoverflow.com/q/50899355
tags question: http://stackoverflow.com/q/50971871
tags question: http://stackoverflow.com/q/50951790
tags question: http://stackoverflow.com/q/50856625
tags question: http://stackoverflow.com/q/50981193
tags question: http://stackoverflow.com/q/50859183

http://stackoverflow.com/comment/88875457
type: Comment
comment on: http://stackoverflow.com/a/50900488
type: AnswerComment
has text: Quick question...there is one annoying column titled 'HR/FB' that uses a % sign after each value. Can `df.columns.str.contains` search for the '%' sign and the column 'HR/FB'? I've tried using the | operand but I keep getting an error. Thanks again for the help!
score: 0

http://stackoverflow.com/q/50977801
has body: Please I need help with this code.I want mylist to retain values appended to it next time the function 'no_repeat_rule' is called. I'm pretty new to python. My code is below: def no_repeat_rule(play_board): mylist = list() if seeds_left(play_board) == 2 and sum(play_board[:6])== 1: mylist.append(play_board) return mylist Output of this code (in part) is: ... [[1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0]] Player 1 chose cup 0 [[0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0]] Player 2 chose cup 6 [[0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0]] ... what I want the function 'no_repeat_rule' to do is to grow mylist each time a player plays. I don't know if this is clear enough to get help?
type: UnansweredQuestion
has title: How to retain values appended to a python list
has answer: http://stackoverflow.com/a/50977879
upvote count: 1
tagged with: python
downvote count: 1
tagged with: list
type: Question
has answer: http://stackoverflow.com/a/50978078
answer count: 2
has comment: http://stackoverflow.com/comment/88951620
score: 0
favorite count: 0

http://stackoverflow.com/a/50870263
type: Answer
score: 1
upvote count: 1
has body: See the discussion here about how the logger names work: https://docs.python.org/2/library/logging.html#logger-objects Your logging.getLogger('myapp') only sees the library's logs if the library's logger inherits from your 'myapp' logger. Since it's named __name__ I think that will only be true if the library is a submodule of your app (i.e. it's in a subfolder under your app). My understanding of imports could be wrong though; I haven't actually tested what __name__ resolves to in a core module. In general, you would need to know the string name of the library's logger (whatever __name__ resolves to, in this case.), then call getLogger to grab that. But in your specific case, you can just import the logger object from any module in the library. Then add your handler to it.
downvote count: 0
answers question: http://stackoverflow.com/q/50869663

http://stackoverflow.com/q/50974761
has answer: http://stackoverflow.com/a/50974880
linked to: http://stackoverflow.com/q/311627
type: Question
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50974810
has comment: http://stackoverflow.com/comment/88945709
has answer: http://stackoverflow.com/a/50974810
has answer: http://stackoverflow.com/a/50974923
has comment: http://stackoverflow.com/comment/88945899
score: 0
answer count: 3
accepted answer: http://stackoverflow.com/a/50974880
has title: Trouble with inputing current date into a list in a specific format
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88945893
tagged with: python
has body: How do I put the current date into a list in the format I want? import datetime today = datetime.date.today() lst=[] lst.append(today) lst[0] &gt;&gt;&gt; datetime.date(2018, 6, 22) print(lst[0]) #found this code on another post (I have no idea how it works) &gt;&gt;&gt; 2018-06-22 I am trying to get "2018-06-22", which is the output of print(lst[0]), into my list but I can only get "datetime.date(2018, 6, 22)". Thanks in advance! Update: lst.append(str(today)) Using this code gets me the same results and I have no idea how it works.

http://stackoverflow.com/comment/88935786
type: Comment
comment on: http://stackoverflow.com/q/50969674
score: 0
has text: link for the dataset: https://www.kaggle.com/c/3136/download/train.csv
type: QuestionComment

http://stackoverflow.com/a/50896054
type: Answer
upvote count: 5
has body: I can't say for sure if that's the problem since you forgot to show what you really have in your DB but here: (Q(destination=modelEmployerDestinationInstance) | Q(destination=modelEmployerDestinationInstance)) I assume you want: (Q(source=modelEmployerDestinationInstance) | Q(destination=modelEmployerDestinationInstance)) instead... Note that the logical would be much more obvious with shorter names, ie source and destination instead of modelEmployerSourceInstance modelEmployerDestinationInstance: q = ( (Q(source=source) | Q(destination=source)) &amp; (Q(source=destination | Q(destination=destination)) &amp; Q(job_id=job_id) ) querySet = modelChat.objects.filter(q) Meaningful names are a good thing, but they have to be short and distinct enough. With "modelEmployerXXXInstance", you have four words to parse, and with the only distinctive (hence relevant) part of the name being in third position, your brain tends to skip over this part. The "model", "Employer" and "Instance" parts are actually just noise.
score: 5
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50895730
accepted answer of: http://stackoverflow.com/q/50895730
has comment: http://stackoverflow.com/comment/138607616

http://stackoverflow.com/comment/88897463
score: 0
comment on: http://stackoverflow.com/q/50949254
has text: Here's the link Charles: https://www.virustotal.com/en/file/ed3610bf1e2f5199c5462498a794719b3347ef6b4779668d146165e5bda624cf/analysis/1529502718/ Now I will try @oliver Melancon suggestions.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50978954
has body: when I run $pip in windows10, it shows: -bash: /usr/local/bin/pip: /usr/bin/python: bad interpreter: No such file or directory but when I run $pip3, it shows the detail successful. Usage: pip &lt;command&gt; [options] ... I downloaded the python in custom directory C:\any_program_related\python\Scripts I already clicked the "add path" during in installation on python. How come the $pip does not run properly? How can I solve this problem?
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88953827
answer count: 0
tagged with: pip
type: Question
score: 0
has comment: http://stackoverflow.com/comment/88957118
has title: cannot run pip in win10

http://stackoverflow.com/comment/88737204
comment on: http://stackoverflow.com/a/50867378
has text: Isn't it easier to use something like `soup.select('span.column-even')`
type: Comment
score: 1
type: AnswerComment

http://stackoverflow.com/comment/88747233
type: Comment
has text: If it is web application, you need to be clear about where your csv file is? Server or local? You want to upload the csv from local to your web application through http? Or are you asking how the backend (using JS/PY) read the csv file already on server?
comment on: http://stackoverflow.com/q/50868543
score: 0
type: QuestionComment

http://stackoverflow.com/comment/89011907
comment on: http://stackoverflow.com/q/51008838
has text: Do you speak about this subject : https://stackoverflow.com/questions/31172719/pip-install-access-denied-on-windows ? Because I tried also to write "python -m pip install --upgrade pip" in cmd, but it doesn't work either
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88840241
type: QuestionComment
comment on: http://stackoverflow.com/q/50919800
score: 0
has text: I think you have fundamental issue with the architecture of your solution—so don't see a simple solution. Instead I suggest that you study Tkinter more. For your code it looks to me like what you may need/want are what are called dialog windows or boxes. Here's some (dated) [documentation on them](http://effbot.org/tkinterbook/tkinter-dialog-windows.htm) to get you started. I'm sure there are many other Tkinter tutorial web sites that have (more likely up-to-date) discussions regarding the topic.
type: Comment

http://stackoverflow.com/comment/133402019
has text: Does this answer your question? [How to make python portable?](https://stackoverflow.com/questions/44488174/how-to-make-python-portable)
comment on: http://stackoverflow.com/q/50950943
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/50981193
has comment: http://stackoverflow.com/comment/88958357
tagged with: numpy
answer count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88958904
tagged with: python
tagged with: large-data
has comment: http://stackoverflow.com/comment/88958070
has answer: http://stackoverflow.com/a/50981429
has title: Efficient way to plot a set of large data and calculate slopes in python
has comment: http://stackoverflow.com/comment/88958652
score: 0
has body: I have a text file with 32 columns. Ev col 2, col 3, col 4, col 5, col 6, col 7 col 8 col 9 col 10 etc...(total 32 columns) -0.08, 8.300, 8.300, 8.300, 8.301, 8.300, 8.300, 8.300, 8.301, 3.405...(total 32 columns) -0.04, 8.300, 8.300, 8.300, 8.301, 8.300, 8.300, 8.300, 8.301, 3.405... (total 32 columns) 0.00, 8.300, 8.300, 8.300, 8.301, 8.300, 8.300, 8.300, 8.301, 3.405... (total 32 columns) 0.04, 8.300, 8.300, 8.300, 8.301, 8.300, 8.300, 8.300, 8.301, 3.405... (total 32 columns) 0.08, 8.300, 8.300, 8.300, 8.301, 8.300, 8.300, 8.300, 8.301, 3.405... (total 32 columns) I would like to plot all the 32 columns on the right versus the left one. (i.e. Ev vs col2, Ev vs col3..... Ev vs col 32) and calculate their slopes. So I tried the bruteforce method- import matplotlib.pyplot as plt import numpy as np x1, y1, y2, y3, y4, y5, y6, y7, y8, y9, y10, y11, y12, y13, y14, y15, y16, y17, y18, y19, y20, y21, y22, y23, y24, y25, y26, y27, y28, y29, y30, y31, y32 = np.loadtxt('mydata.txt', delimiter=',', unpack=True) slope1, intercept1 = np.polyfit(x1, y1, 1) slope1, intercept1 = np.polyfit(x1, y2, 1) slope1, intercept1 = np.polyfit(x1, y3, 1) slope1, intercept1 = np.polyfit(x1, y4, 1) #..... All the way upto 32nd column print('slope 1 =',slope1) plt.plot(x1,y1, label='With ',marker='o') plt.plot(x1,y2, label='With ',marker='o') plt.plot(x1,y3, label='With ',marker='o') plt.plot(x1,y4, label='With ',marker='o') plt.plot(x1,y5, label='With ',marker='o') #. #. #. #....All the way upto 32nd columns # ...plt.plot(x1,y32, label='mydata ',marker='o') plt.show() Even though this code works, I know this is not the efficient way. Is there a better way of plotting these data and get the slopes?
tagged with: plot
type: Question
tagged with: matplotlib

http://stackoverflow.com/a/50919844
answers question: http://stackoverflow.com/q/50919761
has body: From python documentation: An object is hashable if it has a hash value which never changes during its lifetime (it needs a hash() method), and can be compared to other objects (it needs an eq() method). Hashable objects which compare equal must have the same hash value. Hashability makes an object usable as a dictionary key and a set member, because these data structures use the hash value internally. All of Python’s immutable built-in objects are hashable, while no mutable containers (such as lists or dictionaries) are. Objects which are instances of user-defined classes are hashable by default; they all compare unequal, and their hash value is their id(). (https://docs.python.org/3.1/glossary.html) You are trying to create a dict from ndarray, which is not hashable. You can try to use tuple(np.ndarray) P.S. Please, make your question easier to understand. Posting your entire code is not a good way to get an answer. You should debug and find the exact line where the problem is, print the input, the output and say what you expected instead of what you got.
has comment: http://stackoverflow.com/comment/88840012
upvote count: 3
type: Answer
downvote count: 0
score: 3
has comment: http://stackoverflow.com/comment/91327798

http://stackoverflow.com/a/50941371
answers question: http://stackoverflow.com/q/50941178
score: 0
type: Answer
has body: You may want this one Section One:.*[a-z0-9].*$ re.MULTILINE and re.IGNORECASE are used. .*[a-z0-9].*: Match something contains at least one alphanumeric character, ie. [a-z0-9]. $: make sure matching against the whole line. See https://regex101.com/r/H64ZCV/3 for example.

http://stackoverflow.com/a/78076086
has body: I had the same (or similar) problem. You can see in initial description posted by "Neeraj" that "pyyaml" was already installed. In my case the problem was in the fact that I had two python versions. So, "python" command was related to one and "py" to another one version. I find out this by C:\Program Files\Python310>py --version Python 3.12.1 C:\Program Files\Python310>python --version Python 3.10.1 So, my installation of "pyyaml" module was executed in wrong environment. To clarify: the previous command python -m pip install pyyaml dindn't have any effect, meanwhile the solution was in: py -m pip install pyyaml
type: Answer
upvote count: 5
score: 5
downvote count: 0
answers question: http://stackoverflow.com/q/50868322

http://stackoverflow.com/q/50897395
tagged with: anaconda
tagged with: rpy2
has comment: http://stackoverflow.com/comment/88795110
upvote count: 2
answer count: 1
favorite count: 0
tagged with: http://stackoverflow.com/tag/r
has title: Is it possible to set up the rpy2 with system R
tagged with: python
has answer: http://stackoverflow.com/a/50897778
score: 2
has body: Briefly speaking, I want to install rpy2 to connect python seamlessly with R. I have already installed the python 3 in anaconda and installed the system R with Rstudio and both of them work properly in general. Now I want to setup the rpy2 to connect them together, however, when I type conda install rpy2 in terminal (I'm a Mac OSX user), it will install the r-base within the anaconda which is not what I intend to do. I wonder whether it's feasible that it wouldn't install this r-base, but integrates the anaconda python with the system R instead as I've already had all the needed packages installed in this version of R(studio).
downvote count: 0
type: UnansweredQuestion
tagged with: rstudio
has comment: http://stackoverflow.com/comment/88795437
type: Question

http://stackoverflow.com/q/50871530
upvote count: 1
has answer: http://stackoverflow.com/a/50873834
has comment: http://stackoverflow.com/comment/88749931
has body: This program causes an overflow in the nonlinear function. And finally, the output gets nan in all elements. import numpy as np def nonlin(x,deriv=False): if(deriv==True): return x*(1-x) return 1/(1+np.exp(-x)) X = np.array([[0,0],[0,1],[1,0],[1,1]]) Y = np.array([[0],[1],[1],[0]]) w1 = np.random.random((2,2)) w2 = np.random.random((2,1)) for i in range(1000): a0 = X z1 = np.dot(a0,w1) a1 = nonlin(z1) z2 = np.dot(a1,w2) a2 = nonlin(z2) C = Y-a2 #if(i%10==0): # print(np.mean(np.abs(C))) Cdz2 = C*nonlin(z2,True) Cdz1 = Cdz2.dot(w2.T)*nonlin(z1,True) w2 += a1.T.dot(Cdz2) w1 += a0.T.dot(Cdz1) print(a2) The backpropagation method gives runtime warning in the nonlinear function.
type: Question
has comment: http://stackoverflow.com/comment/88749061
has comment: http://stackoverflow.com/comment/88745530
has comment: http://stackoverflow.com/comment/88744988
has title: Why does this neural network gives runtime warning?
tagged with: numpy
downvote count: 0
answer count: 1
score: 1
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88750361
tagged with: python
has comment: http://stackoverflow.com/comment/88750148

http://stackoverflow.com/comment/89000260
comment on: http://stackoverflow.com/q/50963544
score: 1
has text: Option 3 - avoid class hierarchies. Don't use OOP for classification/taxonomies.
type: Comment
type: QuestionComment

awk
tag name: awk
type: Tag
tags question: http://stackoverflow.com/q/50870719
tags question: http://stackoverflow.com/q/50983763

http://stackoverflow.com/a/50943610
type: Answer
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/88885234
has body: import pandas as pd df1 = pd.DataFrame({'C1':['A','B','A'],'C2':[1,1,3],'C3':[2,3,2],'C4':['AA','A','B']}) df2 = pd.DataFrame({'C1':['A','B','Q'],'C2':[1,1,4],'C3':[3,2,1],'C4':['E','C','Z']}) common = pd.merge(df1, df2,on=['C1','C2']) R1 = df1[~((df1.C1.isin(common.C1))&amp;(df1.C2.isin(common.C2)))] R2 = df2[~((df2.C1.isin(common.C1))&amp;(df2.C2.isin(common.C2)))] df1: C1 C2 C3 C4 0 A 1 2 AA 1 B 1 3 A 2 A 3 2 B df2: C1 C2 C3 C4 0 A 1 3 E 1 B 1 2 C 2 Q 4 1 Z common: C1 C2 C3_x C4_x C3_y C4_y 0 A 1 2 AA 3 E 1 B 1 3 A 2 C R1: C1 C2 C3 C4 2 A 3 2 B R2: C1 C2 C3 C4 2 Q 4 1 Z
downvote count: 0
answers question: http://stackoverflow.com/q/50942619

http://stackoverflow.com/a/50906097
answers question: http://stackoverflow.com/q/50905462
type: Answer
score: 0
has body: If your list would have bigger numbers, you should change range(2,int(i/2)+1) for range(2,math.floor(math.sqrt(n)+1)) For instance, 400 will try numbers until 20 instead of 200.

http://stackoverflow.com/comment/89036232
score: 0
comment on: http://stackoverflow.com/a/50969872
type: Comment
type: AnswerComment
has text: Just released PyDev 6.4.1. Can you check if it's fixed for you?

http://stackoverflow.com/q/50965671
has answer: http://stackoverflow.com/a/50966021
answer count: 1
downvote count: 0
tagged with: text-mining
favorite count: 0
has body: I have written following code to extract the words of a ebook and add them to a corpus for text-mining purposes. # loading the german corpus from ebooklib import epub import ebooklib import os import nltk input_path = r"C:\Users\jzeh\Desktop\Directory" german_corpus = [] book = epub.read_epub(os.path.join(input_path,'grimms-maerchen.epub')) for doc in book.get_items(): german_corpus += str(doc.content) german_corpus = [w.lower() for w in nltk.word_tokenize(german_corpus)] Unfortunately running the code gives me the error: TypeError ---&gt; 12 german_corpus = [w.lower() for w in nltk.word_tokenize(german_corpus)] TypeError: expected string or bytes-like object Could anyone tell me, what I am missing?
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50966021
has title: Extract text from epub in Python
upvote count: 3
type: Question
score: 3
tagged with: nltk
tagged with: epub
has comment: http://stackoverflow.com/comment/94707399

http://stackoverflow.com/comment/88748721
comment on: http://stackoverflow.com/q/50872816
type: QuestionComment
type: Comment
has text: Without `kernel='linear'`, I am able to run it easily. Even with `kernel='linear'` and standardizing your data, I am able to run it. Just not ending with the original data.
score: 0

http://stackoverflow.com/q/50856577
type: Question
tagged with: functional-testing
has answer: http://stackoverflow.com/a/50859855
downvote count: 0
has body: I am writing functional tests for my Python application. I use Python standard logging package in the code I am testing. In my Unit Tests I have mocked the logging package but for the functional tests I would like to test 2 things: The logs are in the correct format - This one I can check ok - The logs are sent to stdout - Here is where I am a bit lost - I am able to capture logs and check that the messages are correct. Here is the code I am using: with assertLogs('', level='INFO') as captured_logs: do_something() assertEqual(captured_logs.records[0].msg, "expected message") This works fine but I am only testing my point 1, logs are produced and the messages are as expected. My question is how can I test that those logs are actually being sent to stdout and not to a file or stderr, etc.? Edit: An example of the code to test could be import logging def do_something(): logging.warning("expected message") The result from testing that code will be that the test passes because the message logged is the expected one. But it will pass no matter if the log goes to a file, or to sys.stdout or sys.stderr... My question would be what do I need to add to the test code to make sure the test only passes when the log message goes to stdout Thanks!!
answer count: 1
favorite count: 0
has title: How to check handler used for a log record?
accepted answer: http://stackoverflow.com/a/50859855
tagged with: python
type: AnsweredQuestion
score: 3
upvote count: 3
tagged with: python-unittest
has comment: http://stackoverflow.com/comment/88716400

http://stackoverflow.com/comment/89071853
score: 0
type: Comment
has text: I just found that the last column is always empty. How can we avoid that it attaches `' '` also to the longest sequence? I feel the answer must be in `for k in sequences:`
comment on: http://stackoverflow.com/a/50935316
type: AnswerComment

http://stackoverflow.com/comment/88873265
comment on: http://stackoverflow.com/q/50936686
has text: @abamert, I named it dict just for the sample code I posted. I replaced it with my actual code. The final structure I want is a dictionary with values of quantities from a list with lines of multiple zips and quantities.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50953969
answer count: 1
has comment: http://stackoverflow.com/comment/88905732
has title: How can I update same label with different values?
upvote count: 1
has answer: http://stackoverflow.com/a/50954086
accepted answer: http://stackoverflow.com/a/50954086
has comment: http://stackoverflow.com/comment/88905894
has comment: http://stackoverflow.com/comment/88905869
favorite count: 0
tagged with: tkinter
tagged with: python
has comment: http://stackoverflow.com/comment/88905877
type: AnsweredQuestion
has body: from tkinter import * import fnd from fnd import fake_news import infer def find_news(): global e string = e.get() ans=infer.fake_fake(string) if(ans==0): w = Label(window, text="FAKE",bg="red",fg="white",font="none 19 bold") w.pack() else: w= Label(window,text="REAL",bg="green",fg="white",font="none 19 bold") w.pack() window = Tk() window.title('AVIS') window.geometry("500x500") window.configure(background='black') l1=Label(window,text="",bg="black",fg="white",font="none 19 bold") l1.pack() l1.focus_set() l=Label(window,text="Enter headline of news:",bg="black",fg="white",font="none 12 bold") l.pack() l.focus_set() e = Entry(window,width=200) e.pack() e.focus_set() b = Button(window,text='submit',command=find_news) b.pack(side='bottom') window.mainloop() I am getting a answer from a function and according to it i have to set whether it is fake or not in the label. How can I different values to the same label. If is fake it comes FAKE one below another
has comment: http://stackoverflow.com/comment/88905727
has comment: http://stackoverflow.com/comment/88905903
score: -1
type: Question
downvote count: 2

http://stackoverflow.com/q/50967071
answer count: 0
downvote count: 0
type: UnansweredQuestion
tagged with: tensorflow
type: Question
tagged with: crop
upvote count: 2
has comment: http://stackoverflow.com/comment/88938707
tagged with: keras
favorite count: 0
has title: Random cropping images from data generators
tagged with: python
tagged with: computer-vision
has body: I have found this code for doing random cropping on images for tensorflow backend. def random_crop(img, random_crop_size) # Note: image_data_format is 'channel_last' assert img.shape[2] == 3 height, width = img.shape[0], img.shape[2] dy, dx = random_crop_size x = np.random.randint(0, width - dx + 1) y = np.random.randint(0, height - dy + 1) return img[y:(y+dy), x:(x+dx), :] def crop_generator(batches, crop_length): while True: batch_x, batch_y = next(batches) batch_crops = np.zeros((batch_x.shape[0], crop_length, crop_length, 3)) for i in range(batch_x.shape[0]): batch_crops[i] = random_crop(batch_x[i], (crop_length, crop_length)) yield (batch_crops, batch_y) In my case, I want to crop images with shape (256,256,3) into (224,224,3). In imagenes_trigo every item is a string that contains the path of an image. I have generated my data with the class PantasTrigoDataset. How can I use the above image code for cropping every image of data_train and data_valid? It would be great if someone helps me. Thanks. x_train,x_test,y_train,y_test = train_test_split(imagenes_trigo,labels,test_size=0.25) class PlantasTrigoDataset(Sequence): def __init__(self,imagenes_trigo,labels): self.x=[imread(i) for i in tqdm(imagenes_trigo)] self.y=labels self.batch_size=8 def __len__(self): return int(np.ceil(len(self.x)/float(self.batch_size))) def __getitem__(self, idx): batch_x = self.x[idx * self.batch_size:(idx + 1) * self.batch_size] batch_y = self.y[idx * self.batch_size:(idx + 1) * self.batch_size] return np.array([file_name for file_name in batch_x]), np.array(batch_y) def get_steps(self): return len(self.x)//self.batch_size data_train = PlantasTrigoDataset(x_train,y_train) data_val = PlantasTrigoDataset(x_test,y_test) I have tried this: train_crops = crop_generator(data_train, crop_length) valid_crops = crop_generator(data_val, crop_length) but when I fit a model like this: model.fit_generator( train_crops, steps_per_epoch= 2245, epochs=500, validation_data=valid_crops, validation_ste…
score: 2

http://stackoverflow.com/comment/88945818
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50974639
has text: This text area must be inside a div, could you add that?
score: 0

http://stackoverflow.com/q/50909208
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50909299
downvote count: 2
tagged with: python
has body: I am trying to find a reason to this Error. The Code Is def x(): if b == 1: a = a + 4 print(a) a = 5 b = 1 x() The second time my variable a is used : a = a + 4, an error occur. I am developing a program which mainly uses this type of assignments.
has comment: http://stackoverflow.com/comment/88818440
has comment: http://stackoverflow.com/comment/88818418
type: AnsweredQuestion
score: 3
upvote count: 5
type: Question
accepted answer: http://stackoverflow.com/a/50909299
answer count: 1
has comment: http://stackoverflow.com/comment/88818313
has comment: http://stackoverflow.com/comment/88818427
has title: Unresolved Reference In Python Method

http://stackoverflow.com/a/50896506
upvote count: 1
downvote count: 0
has body: I would try to use the function called argpartition(). To get the indices of the two largest elements, do: import numpy as np a = np.array([9, 4, 4, 3, 3, 9, 0, 4, 6, 0]) ind = np.argpartition(a, -2)[-2:] ind Out[13]: array([5, 0], dtype=int64) a[ind] Out[14]: array([9, 9])
type: Answer
score: 1
answers question: http://stackoverflow.com/q/50895818

http://stackoverflow.com/q/50885585
has answer: http://stackoverflow.com/a/53118187
possible better answer: http://stackoverflow.com/a/50891219
tagged with: python-3.x
has title: Find the corner of a projected rectangle of a single color in numpy
tagged with: python
type: AnsweredQuestion
has body: I have an image of a rectangle, which is projected. The entire rectangle is colored with a single plain color. Similar to this image: I'm trying to find the 4 corners of it an efficiently, probably using numpy and cv2
accepted answer: http://stackoverflow.com/a/53118187
tagged with: image-processing
type: Question
tagged with: numpy
tagged with: opencv
has answer: http://stackoverflow.com/a/50891219
score: 0
has comment: http://stackoverflow.com/comment/88773345
answer count: 2
has comment: http://stackoverflow.com/comment/88776175

http://stackoverflow.com/comment/88888538
type: Comment
type: QuestionComment
has text: It is a real problem, but you should have posted a [mcve] to help others to reproduce.
score: 0
comment on: http://stackoverflow.com/q/50942773

http://stackoverflow.com/comment/120708721
comment on: http://stackoverflow.com/a/50861623
type: AnswerComment
score: 0
has text: `x[x.notnull()]` can be replaced with `x.dropna()`.
type: Comment

http://stackoverflow.com/comment/88886381
has text: @jpp true but I'd assume that the `pandas` version would be recent enough
score: 0
comment on: http://stackoverflow.com/a/50944440
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/88913913
type: Comment
comment on: http://stackoverflow.com/a/50958206
score: 0
type: AnswerComment
has text: Fair enough, thanks for the help, np.where will definitely be helpful

http://stackoverflow.com/a/50990230
answers question: http://stackoverflow.com/q/50990045
has body: What you want to achieve is spawn a new process in which you execute something from either a Node app or a Python app: NodeJS approach: Child process const { spawn } = require('child_process'); const pythonApp = spawn('python', ['my_python_app.py']); Python approach: Subprocess import subprocess node_app = subprocess.Popen(["node","my_node_app.js"], stdin=subprocess.PIPE, stderr=subprocess.PIPE, stdout=subprocess.PIPE) EDIT Regarding catching the INTERRUPT (CTRL+C) signal, this can also be done in both languages; and leveraged to kill the process you spawned: With NodeJS: process.on('SIGINT', () =&gt; { console.log("Caught interrupt signal"); if(pythonApp) pythonApp.exit(); }); With Python: import sys try: # Your app here... except KeyboardInterrupt: print("Caught interrupt signal") if node_app: node_app.kill() sys.exit()
type: AcceptedAnswer
score: 0
has comment: http://stackoverflow.com/comment/89052213
has comment: http://stackoverflow.com/comment/89045940
type: Answer
accepted answer of: http://stackoverflow.com/q/50990045

http://stackoverflow.com/comment/88864537
type: AnswerComment
has text: But that will return each list element as string, if you need to convert the numbers to int or floats you will need additional handling.
score: 0
comment on: http://stackoverflow.com/a/50932874
type: Comment

http://stackoverflow.com/q/50918093
answer count: 2
has comment: http://stackoverflow.com/comment/88836621
possible better answer: http://stackoverflow.com/a/50920700
accepted answer: http://stackoverflow.com/a/50918304
favorite count: 0
has answer: http://stackoverflow.com/a/50920700
has comment: http://stackoverflow.com/comment/88836559
has body: I am trying to make a basic form filler using Selenium on nike.com. I have completed most of it but I am having trouble clicking on the button to select the gender. I have attempted to use many examples of find_element_by_xxxxx code bit none of it has worked. Finding elements by id and xpath haven't come to much either. A typical error i get is Message: no such element: Unable to locate element. I am very new to coding so I could very easily have made an error, but any idea on how you guys would solve it would be much appreciated
tagged with: python
has title: Trouble clicking button using Selenium with Python
has comment: http://stackoverflow.com/comment/88836356
tagged with: selenium-chromedriver
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88836462
downvote count: 2
tagged with: selenium
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/50918304
score: -1

http://stackoverflow.com/q/50969238
score: 0
has comment: http://stackoverflow.com/comment/88936455
has body: i try to develope a self organisation map but i have a basical problem, i don't find a solution to write the color in pcolor my script : import pandas as pd import numpy as np import matplotlib.pyplot as plt dataset = pd.read_csv("/Users/alainmeo/Desktop/deep learning auto adaptating map/data.csv", header=None, sep=';') x = dataset.iloc[:].values from sklearn.preprocessing import MinMaxScaler sc = MinMaxScaler() x = sc.fit_transform(x) from minisom import MiniSom som = MiniSom(x=10, y=10, input_len=5) som.train_random(x, num_iteration=100) from pylab import bone, pcolor, colorbar, plot, show bone() for i, x in enumerate(x): liste = list(x) liste[0]=liste[0]*255 liste[1]=liste[1]*255 liste[2]=liste[2]*255 liste[3]=liste[3]*255 print(liste) w = som.winner(x) if liste[0]&gt;liste[1] and liste[0]&gt;liste[2] and liste[0]&gt;liste[3]: pcolor(w[0]+0.5 ,w[1]+0.5, cmap="RdBu") if liste[1]&gt;liste[0] and liste[1]&gt;liste[2] and liste[1]&gt;liste[3]: pcolor(w[0]+0.5 ,w[1]+0.5, cmap="RdBu") if liste[2]&gt;liste[1] and liste[2]&gt;liste[0] and liste[2]&gt;liste[3]: pcolor(w[0]+0.5 ,w[1]+0.5, cmap="RdBu") if liste[3]&gt;liste[1] and liste[3]&gt;liste[2] and liste[3]&gt;liste[0]: pcolor(w[0]+0.5 ,w[1]+0.5, cmap="RdBu") show() my error line 5553, in _pcolorargs 'Illegal arguments to %s; see help(%s)' % (funcname, funcname)) TypeError: Illegal arguments to pcolor; see help(pcolor) i want to have for each value of an output neuron a one color intensity on the map, but i don't find the solution. Can you help me? thank you in advance
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88963270
has title: self organisation map : visualisation with color
answer count: 0
type: Question
tagged with: matplotlib

range
tags question: http://stackoverflow.com/q/50887562
tags question: http://stackoverflow.com/q/51002971
tags question: http://stackoverflow.com/q/50907540
type: Tag
tags question: http://stackoverflow.com/q/50955719
tag name: range
tags question: http://stackoverflow.com/q/50974157

http://stackoverflow.com/a/50872616
downvote count: 1
has comment: http://stackoverflow.com/comment/88748854
score: 0
answers question: http://stackoverflow.com/q/50872490
has comment: http://stackoverflow.com/comment/88747145
type: Answer
has body: You said subprocess.call() is allowed, so available = not(subprocess.call(["pip", "show", "requests"]))
upvote count: 1

http://stackoverflow.com/comment/131481682
type: Comment
comment on: http://stackoverflow.com/a/74444728
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).
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88934162
comment on: http://stackoverflow.com/q/50968896
score: 0
type: QuestionComment
has text: can you show the expected output table?
type: Comment

http://stackoverflow.com/comment/89048892
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50996755
has text: idk, I did exactly the above (apt, pip, and the python line) and it works, both with python 2.7 and 3.5

http://stackoverflow.com/a/50970624
type: Answer
downvote count: 0
score: 1
has body: It doesn't stop, max throws an error. You can handle this in a couple of ways: ... for file in files: if file.endswith(".xlsx"): list_of_files.append(file) if list_of_files: # if it's not blank... print(max(list_of_files)) or ... for file in files: if file.endswith(".xlsx"): list_of_files.append(file) try: print(max(list_of_files)) except ValueError: # something goes wrong with `max` (or `print` I guess) # what do we do? Probably... pass
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50970550
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50970550

http://stackoverflow.com/a/50900374
has body: We can add the selected attribute to the value that is already selected, like: --------- {% for event in event_dropdown %} {{ event.name }} {% endfor %} Where selected_id is the id of the element. In case there can be multiple selected ids, we can make a list or set of the selected_ids, and then work with: --------- {% for event in event_dropdown %} {{ event.name }} {% endfor %}
score: 5
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88833033
type: Answer
has comment: http://stackoverflow.com/comment/88833062
has comment: http://stackoverflow.com/comment/88833288
accepted answer of: http://stackoverflow.com/q/50900353
upvote count: 5
has comment: http://stackoverflow.com/comment/88833427
answers question: http://stackoverflow.com/q/50900353

http://stackoverflow.com/comment/88989724
comment on: http://stackoverflow.com/a/50992684
type: Comment
has text: @rachana_sharma003 It is working perfectly for me. Please make sure you are on reasonably up-to-date python and numpy versions and that you provide proper inputs. The function takes a numpy array, an int and optinally another int. If after making a reasonable effort you still cannnot get it to work you may come back with a proper description of your setup, the inputs you tried and the error you received.
score: 1
type: AnswerComment

http://stackoverflow.com/a/50995511
has body: If you want output of your command running by subprocess then only when command run successfully without any error then do this command = subprocess.Popen ('command', shell=True, stdout=subprocess.PIPE,stderr=subprocess.STDOUT) ans,err = command.communicate() subprocess.Popen('kill '+str(command.pid),shell=True) If you want to get output of your command by complete execution without error or when your timeout expired then do this command = subprocess.Popen ("command", shell=True, stdout=subprocess.PIPE,stderr=subprocess.STDOUT, stdin=subprocess.PIPE) command.stdin.write ("input for your command") // optional command.stdin.close () timeout = 4 // some timeout ans,time_out = getO(command,timeout) def getO(command,timeout): poll_obj = select.poll() poll_obj.register(command.stdout, select.POLLIN) buflimit = 512000 // set as Ideal buffer limit idealbuffer = 1 buf = 0 ans ='' start = time.time() while buf &lt;= buflimit and start + timeout &gt; time.time() : poll_result = poll_obj.poll(0) if poll_result: ans+= command.stdout.read(idealbuffer) buf+=idealbuffer return ans
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50994346

http://stackoverflow.com/q/50901159
type: Question
type: AnsweredQuestion
has body: The following code that uses the TF-Slim library to load a model and finetune it achieves a performance of 90% in a classification task (I omitted loading the data and preprocessing): with slim.arg_scope(resnet_v1.resnet_arg_scope(weight_decay=0.0001)): logits, _ = resnet_v1.resnet_v1_50(images, num_classes=dataset.num_classes, is_training=True) one_hot_labels = slim.one_hot_encoding(labels, NUM_CLASSES) tf.losses.softmax_cross_entropy(one_hot_labels, logits) total_loss = tf.losses.get_total_loss() global_step = variables.get_or_create_global_step() lr = tf.train.exponential_decay(LEARNING_RATE, global_step, DECAY_STEPS, GAMMA) optimizer = tf.train.MomentumOptimizer(learning_rate=lr, momentum=MOMENTUM) train_op = slim.learning.create_train_op(total_loss, optimizer, global_step=global_step) init_fn = slim.assign_from_checkpoint_fn("resnet_v1_50.ckpt", VARIABLES_TO_RESTORE) final_loss = slim.learning.train( train_op, logdir=train_dir, log_every_n_steps=500, save_summaries_secs=25, init_fn=init_fn, number_of_steps = NUM_STEPS) I tried rewriting the same code using vanilla tensorflow to have more control over the training process and for some reason I cannot achieve the same performance (10% performance drop) when using all the same hyperparameters (in uppercase) and same preprocessing. The differences are in the graph definition: lr = tf.train.exponential_decay(LEARNING_RATE, global_step, DECAY_STEPS, GAMMA) optimizer = tf.train.MomentumOptimizer(learning_rate=lr, momentum=MOMENTUM) full_train_op = optimizer.minimize(total_loss, global_step=global_step) and training: for s in range(NUM_STEPS): sess.run(train_init_op) #Initializes dataset iterator while True: try: sess.run([full_train_op], feed_dict={is_training: True}) except tf.errors.OutOfRangeError: break Is the slim train function doing some other operations? I thought it might be using batch normalization or something else that I did not implement on my version of the code. Is it possible to load the slim resnet m…
tagged with: resnet
tagged with: python
answer count: 1
has answer: http://stackoverflow.com/a/50902491
score: 0
tagged with: tensorflow
accepted answer: http://stackoverflow.com/a/50902491
tagged with: tf-slim
has title: Unable to achieve same performance training with vanilla Tensorflow code compared to training using TF-slim

http://stackoverflow.com/q/50920607
has title: How to run some piece of code in background, after a function returns in python
answer count: 0
type: UnansweredQuestion
has body: I am trying to make a background process which will compress a combination of files. I have a python project which have flask API. I want that when a flask API receives request, compression should start and API return should not wait for end of compression thread. I have this bunch of code but it waits for the time for completion @server.route("/api/dummy/zip", methods=['GET']) def compress_file(): print("zipping starts at", time.time()) file_path = "" file_name = "" comObj = compression_handler.CompressionThread() comObj.__int__(file_name, file_path) logging.info("compression starts") print("zipping end at", time.time()) return "zipping has took " and compression_handler python file : import zipfile import os from os.path import basename import threading import threading from Main import logging class CompressionThread: def __int__(self, file_name, file_path): thread = threading.Thread(target=self.compress, args=(['/Users/nirmalsarswat/Desktop/jdk-8u171-macosx-x64.dmg', '/Users/nirmalsarswat/Desktop/resume-nirmal-sarswat.pdf'],)) thread.daemon = True thread.start() logging.info('thread has started, in progress') def compress(self, file_list): print("running thread in list") try: zip_path = '/Users/nirmalsarswat/Documents/newone.zip' print(zip_path) zip_file = zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) for files in file_list: zip_file.write(files, basename(files)) zip_file.close() logging.info("compression of files is done !!!") except Exception as e: print("exception occured during compression %s" % e) Following code output is like this (in console debugging) &gt; Zipping starts at xxxxx &gt; running thread in list \n &gt; compression of files is done !!! \n &gt; thread has started, in progress &gt; compression starts &gt; zipping end at xxxxxx
has comment: http://stackoverflow.com/comment/88841614
has comment: http://stackoverflow.com/comment/88840935
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/88841031
favorite count: 0
type: Question
tagged with: multithreading
has comment: http://stackoverflow.com/comment/88841699
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/88841126
has comment: http://stackoverflow.com/comment/88840979
has comment: http://stackoverflow.com/comment/88841564
has comment: http://stackoverflow.com/comment/88841062
has comment: http://stackoverflow.com/comment/88849862
has comment: http://stackoverflow.com/comment/88841027

http://stackoverflow.com/a/53177770
has comment: http://stackoverflow.com/comment/139366885
has body: Use: pip install tld --ignore-installed six
type: Answer
answers question: http://stackoverflow.com/q/50954182
upvote count: 48
downvote count: 1
score: 47

http://stackoverflow.com/comment/88972963
comment on: http://stackoverflow.com/q/50989052
type: QuestionComment
has text: use: *#!/usr/bin/env python3* in your script
score: 0
type: Comment

http://stackoverflow.com/q/51007631
tagged with: python
type: AnsweredQuestion
upvote count: 0
has body: In my dataset there is an independent column called "Cycle". It has date values written in text format. I am not understanding how to convert it into numbers. I am working with Multiple Linear Regression and Python. The Column looks like this. Any idea regarding this. Cycle 10th June to 11th July 20th June to 21st July 17th June to 18th July
has answer: http://stackoverflow.com/a/51007832
accepted answer: http://stackoverflow.com/a/51007832
score: -3
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/89008636
type: Question
has title: Machine Learning - Independent Column with Text data type
has comment: http://stackoverflow.com/comment/89008304
answer count: 1
favorite count: 0
downvote count: 3

http://stackoverflow.com/a/50974871
score: 1
answers question: http://stackoverflow.com/q/50974695
accepted answer of: http://stackoverflow.com/q/50974695
upvote count: 1
has body: If you just need post_id try using regex. Ex: import re s = """&lt;script type='text/javascript' data-cfasync='false'&gt; //&lt;![CDATA[ _SHR_SETTINGS = {"endpoints":{"local_recs_url":"https:\/\/klaudynahebda.pl\/wp-admin\/admin-ajax.php?action=shareaholic_permalink_related"},"url_components":{"year":"2018","monthnum":"06","day":"19","post_id":"21132","postname":"letnie-warsztaty-ziolowo-kosmetyczne-7-9lipiec","author":"admin"}}; //]]&gt; &lt;/script&gt;""" m = re.search(r'(?&lt;="post_id":\")(?P&lt;post_id&gt;.*?)(?=\",\")', s) if m: print(m.group('post_id')) Output: 21132
type: AcceptedAnswer
type: Answer
downvote count: 0

http://stackoverflow.com/q/50996368
accepted answer: http://stackoverflow.com/a/50996678
has answer: http://stackoverflow.com/a/50996554
tagged with: python
upvote count: 6
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52229463
tagged with: matplotlib
downvote count: 1
type: Question
possible better answer: http://stackoverflow.com/a/52229463
score: 5
has title: How to change the length of the cap of a whisker in matplotlib boxplot
has answer: http://stackoverflow.com/a/50996678
answer count: 3
tagged with: boxplot
has body: I am trying to change the length of the caps (the min and max point) of the boxplot whisker which are marked red in the following picture Is it possible to change the length of the min marker and max marker of the whisker without changing the size of the box? Edit: I meant the increase of the length of the line marker that indicates the min and max end of the whisker, not increasing the length of the whole whisker itself by increasing the confidence interval. In the latest updated pic I show that I want the black min and max marker to be increased so that it matches the size I indicated with red line.
favorite count: 0

http://stackoverflow.com/q/50971175
has body: I am trying to run my robot scripts on docker remotely with selenium grid. The script to call the docker is Open Browser Remotely [Arguments] ${URL} ${DOCKER_IP} ${REMOTE_URL} Catenate ${DOCKER_IP}/wd/hub Open Browser ${URL} ... ${BROWSER} ... None ... remote_url=${REMOTE_URL} when i run the docker test case i get the following error in the docker log. hub_1 | 2018-06-21 14:15:27.069:WARN:osjs.HttpChannel:qtp615634843-17: /wd/hub/session java.io.IOException: org.openqa.grid.common.exception.GridException: Cannot extract a capabilities from the request: {"capabilities": {"alwaysMatch": {"platform": "ANY", "browserName": "chrome", "version": ""}, "firstMatch": []}, "desiredCapabilities": {"platform": "ANY", "browserName": "chrome", "version": ""}} In the robot Message log no errors, just a vague message 20180621 19:45:27.060 : INFO : Cannot capture screenshot because no browser is open. 20180621 19:45:27.066 : FAIL : WebDriverException: Message: The other part is that my colleague is able to run his test in the docker. please let me know how to solve this issue. Do let me know if more info to added.
has title: how to solve /wd/hub/session java.io.IOException: when running Robot framework testcases on selenium grid in docker?
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/88966532
tagged with: selenium-webdriver
score: 0
tagged with: selenium
tagged with: robotframework
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88962178
tagged with: docker

k-means
tags question: http://stackoverflow.com/q/50927351
tags question: http://stackoverflow.com/q/50898910
type: Tag
tags question: http://stackoverflow.com/q/50938205
tags question: http://stackoverflow.com/q/50942006
tags question: http://stackoverflow.com/q/50914764
tag name: k-means
tags question: http://stackoverflow.com/q/50890518
tags question: http://stackoverflow.com/q/50891737

http://stackoverflow.com/q/50889988
possible better answer: http://stackoverflow.com/a/50890126
favorite count: 0
has answer: http://stackoverflow.com/a/50890160
tagged with: python
has answer: http://stackoverflow.com/a/72189491
type: AnsweredQuestion
type: Question
upvote count: 4
accepted answer: http://stackoverflow.com/a/50890160
has comment: http://stackoverflow.com/comment/88781399
tagged with: arrays
downvote count: 0
tagged with: pyobject
has body: I am trying to creating a python array and have problems with the following code def __init__(self, size): assert size&gt;0, "Array size must be &gt; 0" self._size = size # Create the array structure using the ctypes module. arraytype = ctypes.py_object * size self._elements = arraytype() In the initialization, it uses ctypes to create an array and I don't really understand the last two lines. I tried to change them into one line self._elements = ctypes.py_object() * size But it doesn't work and gives me the error TypeError: unsupported operand type(s) for *: 'py_object' and 'int' Could anyone explain it for me?
score: 4
has answer: http://stackoverflow.com/a/50890126
answer count: 3
has title: the attribute of ctypes.py_object
has comment: http://stackoverflow.com/comment/88781462

http://stackoverflow.com/q/50985836
favorite count: 0
tagged with: python
tagged with: text
tagged with: list
downvote count: 2
has answer: http://stackoverflow.com/a/50985860
upvote count: 1
type: Question
type: AnsweredQuestion
tagged with: split
has body: I am trying to create a script that will look at a text file and store every word as a separate element in a list. When trying to use .split() it doesn't seem to split the string into individual elements. RanTxtString = open("randomText.txt", "r") for word in RanTxtString: word.split() print(word) Output: c:\Scripts&gt;python TxtToList.py Lorem ipsum dolor sit amet, Word1 consectetur adipiscing elit. Nunc fringilla arcu congue metus aliquam mollis. Mauris nec maximus purus. Maecenas sit amet pretium tellus. Praesent Word3 sed rhoncus eo. Duis id commodo orci. Quisque at dignissim lacus.
score: -1
accepted answer: http://stackoverflow.com/a/50985860
answer count: 1
has title: Python Text File To List

http://stackoverflow.com/q/50918196
type: Question
duplicate of: http://stackoverflow.com/q/51756672
has answer: http://stackoverflow.com/a/50918274
linked to: http://stackoverflow.com/q/44666592
answer count: 1
downvote count: 0
score: 1
favorite count: 0
has title: Navigate max date directory in FTP using Python
tagged with: ftplib
type: UnansweredQuestion
tagged with: python
tagged with: ftp
has body: I'm trying to navigate to the latest directory on an FTP site to download a CSV file in it. For this example, I'm trying to select the OG_EWA_2018-06-02 link. How can I access using the max date? Thanks OG_EWA_2018-03-02 . . . Mar 02 10:52 OG_EWA_2018-04-03 . . . Apr 03 09:20 OG_EWA_2018-05-02 . . . May 02 09:17 OG_EWA_2018-06-02 . . . Jun 02 10:52 from ftplib import FTP ftp = FTP('ftp') ftp.cwd('OG_EWA') ftp.retrlines('LIST') print(ftp)
linked to: http://stackoverflow.com/q/51756672
upvote count: 1

http://stackoverflow.com/comment/88768436
has text: +1 for explaining how to look for XHR. I've seen some others mentioning it in other posts but without explaining how to actually use devtools to find it.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50883100

http://stackoverflow.com/q/50962666
has answer: http://stackoverflow.com/a/50962694
tagged with: count
tagged with: python
answer count: 4
score: 2
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/50962693
accepted answer: http://stackoverflow.com/a/50962693
downvote count: 0
has title: How to return a count of values in a list of lists
has answer: http://stackoverflow.com/a/50962720
type: Question
has answer: http://stackoverflow.com/a/50973541
possible better answer: http://stackoverflow.com/a/50962720
has comment: http://stackoverflow.com/comment/88922387
upvote count: 2
favorite count: 0
has comment: http://stackoverflow.com/comment/88921999
has body: I'm trying to return the number of values that are in each list, which are housed in a bigger list. l = [(32, -59), (33, -58)], [(33, -58), (28, 17), (27, 81)], [(33, 28), (95, 49)], [(76, 9), (33, 4)] I have tried to use (sum(x.count('value') for x in l)) but this just returns the count of a single value. I'm hoping to return: 2,3,2,2 I'm not too fussed what format it's in. Although, I'll eventually convert it to a df: 1 2 3 4 0 2 3 2 2

http://stackoverflow.com/comment/88784816
has text: I think this may be somehow related what I'm looking for. Because if I run my script it will run out of memory. But can we still use ImageDataGenerator? Because I want to use that to do the image data augmentation. But I hope to add a functionality to sample random data from a list of filepath for each batch.
comment on: http://stackoverflow.com/a/50889604
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/88884084
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50942840
score: 0
has text: @Aaron, sorry, there was an error

http://stackoverflow.com/q/50884623
has comment: http://stackoverflow.com/comment/88771196
has comment: http://stackoverflow.com/comment/88771522
tagged with: python
has comment: http://stackoverflow.com/comment/88771524
accepted answer: http://stackoverflow.com/a/50884653
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88771427
has title: Randomly select values from list but with character length restriction
linked to: http://stackoverflow.com/q/10048069
has comment: http://stackoverflow.com/comment/88771229
has body: I have a two lists of strings like the following: test1 = ["abc", "abcdef", "abcedfhi"] test2 = ["The", "silver", "proposes", "the", "blushing", "number", "burst", "explores", "the", "fast", "iron", "impossible"] The second list is longer, so I want to downsample it to the length of the first list by randomly sampling. def downsample(data): min_len = min(len(x) for x in data) return [random.sample(x, min_len) for x in data] downsample([list1, list2]) However, I want to add a restriction that the words chosen from the second list must match the length distribution of the first list. So for the first word that is randomly chosen, it must be of the same length as the first word of the shorter list. The issue here is that replacement is not allowed either. How can I randomly select n (length of shorter list) elements from test2 which matches the character length distribution of test1? Thanks, Jack
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/50884729
downvote count: 0
has answer: http://stackoverflow.com/a/50884729
upvote count: 8
has answer: http://stackoverflow.com/a/50884653
score: 8
favorite count: 0

http://stackoverflow.com/comment/88890839
type: Comment
has text: looks like a copy/pasta accident
comment on: http://stackoverflow.com/a/50946556
type: AnswerComment
score: 0

http://stackoverflow.com/comment/88994544
type: Comment
comment on: http://stackoverflow.com/a/51000182
score: 0
type: AnswerComment
has text: That's one approach to do so but it has multiple `if` statements. The question involves only a single `if` statement.

game-loop
tag name: game-loop
tags question: http://stackoverflow.com/q/50880120
type: Tag

http://stackoverflow.com/q/50954513
upvote count: 0
has comment: http://stackoverflow.com/comment/88908240
has title: Model Equation of logistic regression in sklearn or statsmodel.api
has body: After running the logistic regression, I want to see the model equation. Is there a way of finding that?
tagged with: logistic-regression
type: Question
tagged with: statsmodels
has answer: http://stackoverflow.com/a/50954666
score: -1
answer count: 1
downvote count: 1
tagged with: scikit-learn
favorite count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/88950847
comment on: http://stackoverflow.com/q/50977031
type: QuestionComment
has text: Fair play if you're new to both, you've avoided some really common traps in your code. I'm taking another look.
score: 0
type: Comment

http://stackoverflow.com/comment/88866204
type: QuestionComment
type: Comment
has text: Hmm. I think it is not the field itself that results in problems, but probably the fact that these permissions are later *translated* into `Permission` fields.
comment on: http://stackoverflow.com/q/50933633
score: 0

http://stackoverflow.com/q/50950043
tagged with: python
tagged with: qweb
favorite count: 0
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
has title: TypeError: 'NoneType' object is not subscriptable Odoo 11 custom report
tagged with: odoo-11
tagged with: odoo
score: 1
has comment: http://stackoverflow.com/comment/88898974
type: Question
upvote count: 1
downvote count: 0
has body: I'm trying to create a custom report, i've followed some code i've found on Odoo github but it doesn't work. First, i'm creating a transiant model with a function that get my data and put it in a python dict : from odoo import api, fields, models import logging _logger = logging.getLogger(__name__) class SockValuationReport(models.TransientModel): _name = 'report.stock_valuation_flora' _description = 'Sotck valuation report for floravert' @api.multi def render_report(self): products = self.env['product.template'].search([]) data = {} categ_dict = {} for product in products: valuation = 0 if(product.categ_id.name in categ_dict): valuation = product.standard_price * product.qty_available categ_dict[product.categ_id.name]['valuation'] = categ_dict[product.categ_id.name]['valuation'] + valuation else: categ_dict[product.categ_id.name] = {'categ_name':product.categ_id.name, 'valuation':product.standard_price * product.qty_available} data['products'] = products data['categ_value']= categ_dict _logger.info(data) return self.env.ref('stock_printer.report_stock_product_valuation').report_action(self,data=data) next i'm creating a report object in my view.xml file : <report id="report_stock_product_valuation" model="report.stock_valuation_flora" string="Stock Report" report_type="qweb-pdf" name="stock_printer.report_stock_valuation" file="stock_printer.report_stock_valuation"/> then i'm adding my view template : <t t-call="web.html_container"> <t t-call="web.internal_layout"> MY REPORT <t t-foreach="data['products']" t-as="product"> </t> </t> </t> but when i'm trying to print this report i got this error : Traceback (most recent call last): File "C:\Program Files (x86)\Odoo 11.0\server\odoo\addons\base\ir\ir_qweb\qweb.py", line 341, in _compiled_fn return compiled(self, append, new, options, log) File " ", line 1, in template_489_36 File " ", line 2, in body_call_content_35 File " ", line 3, in body_call_content_34 TypeError: 'NoneType' object is not subscriptable During hand…

http://stackoverflow.com/q/50866634
downvote count: 0
answer count: 7
accepted answer: http://stackoverflow.com/a/51154583
favorite count: 0
has comment: http://stackoverflow.com/comment/134448713
linked to: http://stackoverflow.com/q/62864082
tagged with: python-pptx
tagged with: python
has answer: http://stackoverflow.com/a/61177344
has answer: http://stackoverflow.com/a/56448435
has title: How to copy a slide with python-pptx?
upvote count: 19
possible better answer: http://stackoverflow.com/a/57578849
has answer: http://stackoverflow.com/a/57578849
score: 19
type: Question
has answer: http://stackoverflow.com/a/51154583
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/56074651
has answer: http://stackoverflow.com/a/78819892
has body: How can I copy a slide? I created a template slide and I need to copy it and edit shapes of each copy separately. Or how I can add my template slide to presentation.slide_layouts?
has answer: http://stackoverflow.com/a/73954830

http://stackoverflow.com/q/50951572
tagged with: python
has title: How do I sum values from one column dependent on items in other columns?
type: UnansweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/88902604
has body: I have the following dataframe: Course Orders Ingredient 1 Ingredient 2 Ingredient 3 starter 3 Fish Bread Mayonnaise starter 1 Olives Bread starter 5 Hummus Pita main 1 Pizza main 6 Beef Potato Peas main 9 Fish Peas main 11 Bread Mayonnaise Beef main 4 Pasta Bolognese Peas desert 10 Cheese Olives Crackers desert 7 Cookies Cream desert 8 Cheesecake Cream I would like to sum the number of orders for each ingredient per course. It is not important which column the ingredient is in. The following dataframe is what I would like my output to be: Course Ord Ing1 IngOrd1 Ing2 IngOrd2 Ing3 IngOrd3 starter 3 Fish 3 Bread 4 Mayo 3 starter 1 Olives 1 Bread 4 starter 5 Hummus 5 Pita 5 main 1 Pizza 1 main 6 Beef 17 Potato 6 Peas 21 main 9 Fish 9 Peas 21 main 11 Bread 11 Mayo 11 Beef 17 main 4 Pasta 4 Bolognese 4 Peas 21 desert 10 Cheese 10 Olives 10 Crackers 10 desert 7 Cookies 7 Cream 15 desert 8 Cheesecake 8 Cream 15 I have tried using groupby().sum() but this does not work with the ingredients in 3 columns. I also cannot use lookup because there are instances in the full dataframe where I do not know what ingredient I am looking for.
has comment: http://stackoverflow.com/comment/88901079
type: Question
has comment: http://stackoverflow.com/comment/88935675
has comment: http://stackoverflow.com/comment/88906095
has comment: http://stackoverflow.com/comment/88902014
has answer: http://stackoverflow.com/a/50957377
tagged with: pandas
answer count: 1

http://stackoverflow.com/comment/88997682
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51001928
score: 0
has text: `len(set(data)) != len(data)` will tell you if dupes, leaving you still some work to find out what are the dupes. (You're only checking one item at a time so len is always going to be one for set and non-set.)

http://stackoverflow.com/a/50936612
has body: The only way you can see this error is to post a list of dicts under countries_id key of request body. You need to pass a list of countries ids (int) instead. Traceback and request data would be helpful to answer your question exactly.
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50936240
score: 1
upvote count: 1

http://stackoverflow.com/comment/88855466
type: Comment
type: QuestionComment
score: 0
has text: The javascript part will return an array of objects with a `str` property, something like `[{str: "what"}, {str: "ever"}]`, therefore i guess you just want to return the `value` property of your object to make it work, sth like `r.json().value`
comment on: http://stackoverflow.com/q/50924824

http://stackoverflow.com/comment/88853685
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50919821
type: AnswerComment
has text: Flask automatically looks for a folder called `static` in the root of the project you're currently working on.

http://stackoverflow.com/a/51009000
has comment: http://stackoverflow.com/comment/89011259
has comment: http://stackoverflow.com/comment/89011951
score: -1
answers question: http://stackoverflow.com/q/51008162
has comment: http://stackoverflow.com/comment/89026815
downvote count: 1
has comment: http://stackoverflow.com/comment/89026946
has comment: http://stackoverflow.com/comment/89026979
type: Answer
has body: You don't need to separate train and test data for cross_val_score. The function itself just takes care of it. When passing the features set, you need to pass the complete feature set, not X_train and X-test First seperate the target variable target = df['result'] Then run the selectKbest and get the column names like you did, but this time instead of splitting the X into train and test, just pass them as single data set like this X = clean_df[colnames_selected] Then pass the X and target to cross_val_score scores = cross_val_score(forest, X, target, cv=10) print("Reduced features: mean of the scores: {:.2f}".format(scores.mean())) The whole point of the function is to perform cross validation on the dataset and return the scores using the estimators provided. You can also use pipelines to make this whole process more easier in go like this example.
has comment: http://stackoverflow.com/comment/89027867
upvote count: 0
has comment: http://stackoverflow.com/comment/89026286
has comment: http://stackoverflow.com/comment/89027841

http://stackoverflow.com/a/50877993
answers question: http://stackoverflow.com/q/50877791
upvote count: 1
has comment: http://stackoverflow.com/comment/88758183
has comment: http://stackoverflow.com/comment/88758231
downvote count: 0
type: Answer
has body: There is no theoretical problem with this approach. From a statistical standpoint, all you've done is to exclude those seven features from the PCA reduction. This implies that you know, a priori, that those seven features are principal components -- that they're significant to the results, without having to analyze them for independence from the other features, and for relevance. As loeschet already mentioned, you should try it both ways: once the way you're proposing, and once with all 103 features included in your PCA phase. See which gives you better results. Much of data set analysis consists of trying different approaches to see which gives you the best empirical results.
score: 1

http://stackoverflow.com/comment/88976258
comment on: http://stackoverflow.com/q/50990437
score: 0
has text: @user3483203: I would accept an answer mentioning `pd.cut`
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88881331
comment on: http://stackoverflow.com/a/50940663
type: AnswerComment
score: 0
has text: Sorry, I've test it without"email from", it's same...is there any other setting for the email sending function , for example to write the sending function customized。？？
type: Comment

http://stackoverflow.com/comment/88833303
comment on: http://stackoverflow.com/a/50916413
score: 0
type: AnswerComment
has text: Yes. What I what to be able to do is craft a update_or_create() statement that will work no matter how many times in a given day the CVS report file gets read and processed.
type: Comment

http://stackoverflow.com/comment/89022861
has text: Interesting, it works. Just curious (or greedy), is there any method in your package to know the earliest available date for each ticker or does it have to be try-error?
comment on: http://stackoverflow.com/a/50991375
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89067538
type: Comment
comment on: http://stackoverflow.com/a/50981351
score: 0
type: AnswerComment
has text: Or shorter - ws.cell(cell.Row, 2).Value = 6

http://stackoverflow.com/comment/88943720
score: 0
has text: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html - http://idownvotedbecau.se/noresearch/
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50973529

http://stackoverflow.com/q/50889874
has answer: http://stackoverflow.com/a/50889922
has title: How do I know if a variable in Django contains anything in it?
tagged with: django
has body: My views.py : class PostView(TemplateView): template_name = 'airapp/post_list.html' def get(self, request): form = PostForm() posts = Post.objects.order_by('-date') users = User.objects.exclude(id=request.user.id) friend, created = Friend.objects.get_or_create(current_user=request.user) friends = friend.users.all() args = {'form' : form, 'posts' : posts, 'users': users, 'friends' : friends} return render(request, self.template_name, args) My post_list.html Friends {% if **not friends.exists()** %} You don't have any friends :( Add one!! {% else %} {% for friend in friends %} {{ friend.username }} Remove Friend {% endfor %} {% endif %} Is there any way in which I can check whether friends actually contains anything? Because if it doesn't, I want to display something else ( which is pretty evident)
possible better answer: http://stackoverflow.com/a/50890207
type: Question
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/88780917
has answer: http://stackoverflow.com/a/50890207
answer count: 2
upvote count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/50889922
tagged with: python
has comment: http://stackoverflow.com/comment/88780932

http://stackoverflow.com/a/50959413
type: Answer
has comment: http://stackoverflow.com/comment/89403669
downvote count: 1
upvote count: 4
has body: Let's try and do this step by step, writing our own function to solve the WBM problem as specified in the question. Using pulp it is not too difficult to formulate and solve a weighted bipartite matching (WBM), when we are given two sets of nodes (u and v, edge weights and vertex capacities.) In Step 2 below, you'll find a (hopefully easy to follow) function to formulate WBM as an ILP and solve using pulp. Go through it to see if it helps. (You need to pip install pulp) Step 1: Set up the bipartite graph capacities and edge weights import networkx as nx from pulp import * import matplotlib.pyplot as plt from_nodes = [1, 2, 3] to_nodes = [1, 2, 3, 4] ucap = {1: 1, 2: 2, 3: 2} #u node capacities vcap = {1: 1, 2: 1, 3: 1, 4: 1} #v node capacities wts = {(1, 1): 0.5, (1, 3): 0.3, (2, 1): 0.4, (2, 4): 0.1, (3, 2): 0.7, (3, 4): 0.2} #just a convenience function to generate a dict of dicts def create_wt_doubledict(from_nodes, to_nodes): wt = {} for u in from_nodes: wt[u] = {} for v in to_nodes: wt[u][v] = 0 for k,val in wts.items(): u,v = k[0], k[1] wt[u][v] = val return(wt) Step 2: Solve the WBM (formulated as an integer program) Here's some description to make the code that follows easier to understand: The WBM is a variation of the Assignment problem. We 'match' nodes from the RHS to the LHS. The edges have weights The objective is to maximize the sum of the weights of the selected edges. Additional set of constraints: For each node, the number of selected edges has to be less than its 'capacity' which is specified. PuLP Documentation if you are not familiar with puLP . def solve_wbm(from_nodes, to_nodes, wt): ''' A wrapper function that uses pulp to formulate and solve a WBM''' prob = LpProblem("WBM Problem", LpMaximize) # Create The Decision variables choices = LpVariable.dicts("e",(from_nodes, to_nodes), 0, 1, LpInteger) # Add the objective function prob += lpSum([wt[u][v] * choices[u][v] for u in from_nodes for v in to_nodes]), "Total weights of selected edges" # Co…
score: 3
has comment: http://stackoverflow.com/comment/89165136
answers question: http://stackoverflow.com/q/50908267
has comment: http://stackoverflow.com/comment/89119010

http://stackoverflow.com/comment/88743951
type: QuestionComment
has text: Yes i have tried it but it didnt help.
comment on: http://stackoverflow.com/q/50861080
score: 0
type: Comment

http://stackoverflow.com/q/50941740
accepted answer: http://stackoverflow.com/a/51129770
downvote count: 0
has answer: http://stackoverflow.com/a/51129770
has body: I'm trying to convert tensorflow lite quantised .pb file to .lite using toco. The command for creating .pb file is : retrain.py is here and here. python retrain.py \ --bottleneck_dir=/mobilenet_q/bottlenecks \ --how_many_training_steps=4000 \ --output_graph=/mobilenet_q/retrained_graph_mobilenet_q_1_224.pb \ --output_labels=/mobilenet_q/retrained_labels_mobilenet_q_1_224.txt \ --image_dir=/data \ --architecture=mobilenet_1.0_224_quantized When I'm trying to convert the .pb file to .tflite using toco command: bazel run --config=opt //tensorflow/contrib/lite/toco:toco \ -- --input_file= retrained_graph_mobilenet_q_1_224.pb \ --output_file= retrained_graph_mobilenet_q_1_224.lite \ --input_format=TENSORFLOW_GRAPHDEF \ --output_format=TFLITE \ --input_shape=1,224,224,3 \ --input_array=input \ --output_array=final_result \ --inference_type=FLOAT \ --input_data_type=FLOAT I'm getting the error: Some of the operators in the model are not supported by the standard TensorFlow Lite runtime. If you have a custom implementation for them you can disable this error with --allow_custom_ops, or by setting allow_custom_ops=True when calling tf.contrib.lite.toco_convert(). Here is a list of operators for which you will need custom implementations: Dequantize. I've searched in github and stackoverflow but I've not come across a satisfactory answer.
answer count: 1
has title: Custom implementation for Dequantize when converting .pb to .tflite
favorite count: 0
upvote count: 2
tagged with: android
tagged with: python
score: 2
type: AnsweredQuestion
tagged with: conv-neural-network
tagged with: tensorflow
type: Question

http://stackoverflow.com/q/50912166
favorite count: 0
has comment: http://stackoverflow.com/comment/88905941
tagged with: astronomy
has body: I have 4000 fits-files images from SPITZER, each containing the same star over a time period. Each image is a photmetry cube of 32 pixel * 32 pixel * 64 consequent time frames. I need to look through all the single frames and order the pixel by brightness. Not hard to do with Python, but sometimes I have in the frames short-lived events/artefacts which are brighter than the brightest pixel of the star (see below). These artefacts last only over one or two consequent time frames How can I easily correct for the artefacts? Is there an astropy/pyfits package that does this? Or some kind of bad pixel flagging in SPITZER (I know that Kepler-images have flagging of bad pixel)? Optional: It would be convenient to have the code in vectorized form, avoiding loops, so that I save computtional time Comparison of two frames, in the left one everything is fine, in the right one you see in the top right corner one of this artefacts, being brighter than any of the star pixel. Note: the artefact doesn't reach the level of saturation.
tagged with: python
type: AnsweredQuestion
has title: Python: Order fits-file pixel by brightness, ignore artefacts
tagged with: fits
score: 1
has comment: http://stackoverflow.com/comment/88855660
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51061682
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/51061682

http://stackoverflow.com/comment/88988405
type: Comment
comment on: http://stackoverflow.com/a/50996851
type: AnswerComment
has text: @Atihska It's a recipe in the docs. You can't import code from recipes in the docs; you have to type it, or copy and paste it, into your code. They do this because (a) it's only two lines, and (b) it's useful sample code they want you to read. If you really want to, though, there are equivalent functions in third-party libraries like `more_itertools` and `toolz`. (Also, why would you expect `from itertools import groupby` to give you a function called `grouper`?)
score: 0

http://stackoverflow.com/q/50938370
has title: Docker with Jupyter Notebook and Spark
tagged with: docker
has body: I am trying to use docker to run Jupyter Notebook with spark , on PowerShell I am using the following command: docker run --rm -h 0.0.0.0 -p 8888:8888 -e PYTHONHASHSEED=0 jupyter/all-spark-notebook When I run that I get the following error: Container must be run with group "root" to update passwd file Any Ideas about how to fix it/ update group root password?
downvote count: 0
tagged with: jupyter-notebook
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 2
answer count: 0
type: Question

http://stackoverflow.com/comment/88955859
type: QuestionComment
comment on: http://stackoverflow.com/q/50979821
has text: Tastes differ. Which is why this question is probably off topic on SO.
score: 0
type: Comment

http://stackoverflow.com/comment/88845872
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50923192
has text: chromedriver = "C:/Users/iza/desktop/chromedriver/chromedriver.exe" os.environ["webdriver.chrome.driver"] = chromedriver browser = webdriver.Chrome(chromedriver)

http://stackoverflow.com/q/50859808
has answer: http://stackoverflow.com/a/50860010
favorite count: 0
has comment: http://stackoverflow.com/comment/88723264
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88722363
has comment: http://stackoverflow.com/comment/88722447
tagged with: python
has comment: http://stackoverflow.com/comment/88722501
has comment: http://stackoverflow.com/comment/88722255
has title: Add values when there is a gap between elements
tagged with: list
type: UnansweredQuestion
upvote count: 1
has answer: http://stackoverflow.com/a/50860001
has comment: http://stackoverflow.com/comment/88722836
score: 1
has body: I have a list defined as A = [1.0, 3.0, 6.0, 7.0, 8.0] I am trying to fill the gap between the elements of the list with zero values. A gap is an increment between elements that is more than one. So for instance between 1.0 and 3.0 there is one gap: 2.0 and between 3.0 and 6.0 there are two gaps:4.0 and 5.0 I am working with this code but it is not complete and I am missing adding multiple values when the gap is bigger than one increment B = [] cnt = 0 for i in range(len(A)-1): if A[i] == A[i+1] - 1: B.append(A[cnt]) cnt += 1 if A[i] != A[i+1] - 1: B.append(A[cnt]) B.append(0.0) cnt += 1 The output of this code is: B = [1.0, 0.0, 3.0, 0.0, 6.0, 7.0] But since there are two gaps between 3.0 and 6.0 I need B to look like this: B = [1.0, 0.0, 3.0, 0.0, 0.0, 6.0, 7.0] I am a bit stuck on how to do this and I already have a feeling that my code is not very optimized. Any help is appreciated!
type: Question
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/88722768

http://stackoverflow.com/comment/88878109
has text: Are you only using Pandas to read the csv and convert to JSON? Are you using the Dataframe for anything else?
comment on: http://stackoverflow.com/q/50939977
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88839958
has text: Hi, it doesn't work. What I'm looking for is something of the sort : '[ { "time": "14/06/2018 - 07:41:47", "name": "Rajkiran", "accuracy": "91.08506", "direction": "default" }, { "time": "14/06/2018 - 07:41:52", "name": "Rajkiran", "accuracy": "100.0", "direction": "default" } ]' However, if I use mode = 'a' I get: '[][ { "time": "19/06/2018 - 08:48:52", "name": "Rajkiran", "accuracy": "100.0", "direction": "default" } ]'
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50920133
type: Comment

http://stackoverflow.com/a/50867314
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/88737000
downvote count: 0
answers question: http://stackoverflow.com/q/50867244
has comment: http://stackoverflow.com/comment/88736786
type: Answer
has body: Try the below code: with open('f.txt') as f: print('\n'.join([i for i in f.read().split(',')[0:3]]))

sql
tags question: http://stackoverflow.com/q/50977031
tags question: http://stackoverflow.com/q/50975052
tags question: http://stackoverflow.com/q/50970937
tags question: http://stackoverflow.com/q/50973254
tags question: http://stackoverflow.com/q/50882613
tags question: http://stackoverflow.com/q/51010048
tags question: http://stackoverflow.com/q/50926769
tags question: http://stackoverflow.com/q/50978136
tags question: http://stackoverflow.com/q/50955128
tag name: sql
type: Tag
tags question: http://stackoverflow.com/q/50863413
tags question: http://stackoverflow.com/q/50958010
tags question: http://stackoverflow.com/q/50868607
tags question: http://stackoverflow.com/q/50976041
tags question: http://stackoverflow.com/q/50940145
tags question: http://stackoverflow.com/q/50927740
tags question: http://stackoverflow.com/q/50887479
tags question: http://stackoverflow.com/q/50865907
tags question: http://stackoverflow.com/q/50996820
tags question: http://stackoverflow.com/q/50986627
tags question: http://stackoverflow.com/q/50858082
tags question: http://stackoverflow.com/q/50918386
tags question: http://stackoverflow.com/q/50930012
tags question: http://stackoverflow.com/q/51008386
tags question: http://stackoverflow.com/q/50955856
tags question: http://stackoverflow.com/q/50918185
tags question: http://stackoverflow.com/q/50855155
tags question: http://stackoverflow.com/q/50976837

http://stackoverflow.com/q/50923061
accepted answer: http://stackoverflow.com/a/50933709
has title: Python `logging` module + YAML config file
score: 0
has answer: http://stackoverflow.com/a/50923421
has body: I have found a lot of documentation and tutorials such as the official logging config docs, the official logging cookbook, and this nice tutorial by Fang. Each of them have gotten me near to an answer, but not quite. My question is this: When using Config Files, how can I use a logger with 2 separate handlers at 2 separate levels? To clarify, here is an example of my YAML file: --- version: 1 handlers: debug_console: class: logging.StreamHandler level: DEBUG . . . info_file_handler: class: logging.handlers.RotatingFileHandler level: INFO . . . loggers: dev: handlers: [debug_console, info_file_handler] test: handlers: [info_file_handler] root: handlers: [info_file_handler] I want to have two ways to run the logger, where one way (dev) is more verbose than the other. Moreover, when running the dev logger, I want it to have two different levels for the two different handlers. This is a snippet of the code to try to launch the logger: with open('logging.yaml', 'r') as f: log_cfg = yaml.safe_load(f.read()) logging.config.dictConfig(log_cfg) my_logger = logging.getLogger('dev') The dictConfig line above works correctly. I say this because when I get to the code which asks to log to the console, I will see dev as the name when the log prints out. (I have edited the yaml, but it contains %(name)s in the format.) But there is something wrong with my_logger. Even though it is tied to the name of dev, none of the rest of the attributes seem to have been set. Specifically, I see: &gt;&gt;&gt; my_logger &lt;Logger dev_model (WARNING)&gt; I don't know the logging module well enough to understand where the problem is. What I want is: When I activate the 'dev' logger, I want to launch 2 handlers, one which is at the DEBUG level and writes to console, the other which is at the INFO level and writes to a file. How can this be done?
tagged with: python
tagged with: config
tagged with: logging
type: Question
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50923421
answer count: 2
has answer: http://stackoverflow.com/a/50933709

http://stackoverflow.com/comment/89135792
score: 0
type: Comment
type: QuestionComment
has text: @ParagS.Chandakkar It seems like it is working. Thank you!
comment on: http://stackoverflow.com/q/50995005

http://stackoverflow.com/q/51005416
upvote count: 2
tagged with: google-api
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51005519
tagged with: python
score: 2
type: Question
tagged with: google-tag-manager
has body: I am attempting to automate GTM setup using the API and Python. However, I want to set overrideGaSettings to false when I create the UA tag and I can't seem to get it to work. I searched the api doc site for overrideGaSettings and got zero hits which I find strange. This code works but sets overrideGaSettings = true def CreateGATag(service, workspace): GA_tag = { 'name': 'Google Analytics', 'type': 'ua', 'parameter': [ { 'type': 'template', 'key': 'trackingId', 'value': '{{Google Analytics Settings}}' } ] } return service.accounts().containers().workspaces().tags().create(parent=workspace['path'],body=GA_tag).execute() This codes gives me an invalid argument error. def CreateGATag(service, workspace): GA_tag = { 'name': 'Google Analytics', 'type': 'ua', 'parameter': [ { "type": "boolean", "key": "overrideGaSettings", "value": "false" }, { 'type': 'template', 'key': 'trackingId', 'value': '{{Google Analytics Settings}}' } ] } return service.accounts().containers().workspaces().tags().create(parent=workspace['path'],body=GA_tag).execute() This code does set overrideGaSettings = false at tag creation without any problem. def CreateGAformSubmitTag(service, workspace): GAformSubmittag = { "name": "Universal Analytics - formSubmit", "type": "ua", "parameter": [ { "type": "boolean", "key": "nonInteraction", "value": "true" }, { "type": "boolean", "key": "overrideGaSettings", "value": "false" }, { "type": "template", "key": "eventCategory", "value": "click" }, { "type": "template", "key": "trackType", "value": "TRACK_EVENT" }, { "type": "template", "key": "gaSettings", "value": "{{Google Analytics Settings}}" }, { "type": "template", "key": "eventAction", "value": "formSubmit" } ], "tagFiringOption": "oncePerEvent" } return service.accounts().containers().workspaces().tags().create( parent=workspace['path'], body=GAformSubmittag).execute()
downvote count: 0
answer count: 1
tagged with: google-api-python-client
favorite count: 0
has title: Google Tag Manager API Python Set overrideGaSettings = false at Tag creation

http://stackoverflow.com/a/50898345
has comment: http://stackoverflow.com/comment/88811437
has body: You are probably better off using root.after than threads: In any events, as other pointed out, using time.sleep is a bad idea in a GUI. You should also not name your buttons the same as your functions. calling root.update, is also not necessary here. from tkinter import * from tkinter import ttk def start_process(n=0, times=10): n += 1 if not stop_button_state and n &lt; times: print('Iteration started') print(f'Iteration number: {n}') print('Iteration completed \n') root.after(1000, start_process, n) else: print('stopping everything') def stop_fun(): global stop_button_state stop_button_state = True if __name__ == '__main__': root = Tk() start = ttk.Button(root, text="Start", command=start_process) start.grid(row=0, column=0, padx=10, pady=10) p = ttk.Button(root, text="Stop", command=stop_fun) p.grid(row=1, column=0) stop_button_state = False root.mainloop()
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/88798583
answers question: http://stackoverflow.com/q/50896847
downvote count: 0
has comment: http://stackoverflow.com/comment/88811506
accepted answer of: http://stackoverflow.com/q/50896847
score: 1
has comment: http://stackoverflow.com/comment/88797894
type: AcceptedAnswer

http://stackoverflow.com/q/50913407
score: 0
has body: I'm passing a link as an argument in a thread, that I want to scrape the timestamp on. But in the function that the thread is pointing to, the timestamp value does not change, every time i'm rescraping it. How do you get timeLink to be dynamic and change every time it goes over the while loop? Here is the code: def abcStart(timeLink): while True: res = timeLink res.raise_for_status() timestamp = BeautifulSoup(res.content, 'html.parser').find_all('b') if timestamp[0].text == otherTimestamp[0].text: work on something break if timestamp[0].text &gt; otherTimestamp[0].text: continue else: print('not yet') time.sleep(30) break timelink = requests.get('http://example.com/somelink') threadobj = threading.Thread(target=abcStart, args=(timelink)) threadobj.start() threadobj.join()
tagged with: python
has answer: http://stackoverflow.com/a/50913599
has title: Python - how to get updated link that was passed as an argument?
type: Question
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50913497
answer count: 2
has answer: http://stackoverflow.com/a/50913497
accepted answer: http://stackoverflow.com/a/50913599

http://stackoverflow.com/q/50959697
has answer: http://stackoverflow.com/a/50959740
type: AnsweredQuestion
score: 1
possible better answer: http://stackoverflow.com/a/50959740
upvote count: 1
has body: I want to get the execution time of several portions of my code. Currently I am using time.time() but I feel a bit dumb when writing again and over again code like this: start = time() function1(args1) print("Execution of function1: {}".format(time()-start)) start = time() function2(args2) print("Execution of function2: {}".format(time()-start)) start = time() function3(args3) print("Execution of function3: {}".format(time()-start)) Please do you know any smarter way to do this? I couldn't find any module that would enable to do things like this (for instance): chrono("Execution of function1") function1(args1) chrono("Execution of function2") function2(args2) chrono("Execution of function3") function3(args3)
type: Question
has answer: http://stackoverflow.com/a/50960105
answer count: 2
downvote count: 0
favorite count: 0
has title: Clean way to measure multiple code execution times in Python
tagged with: time
tagged with: python
accepted answer: http://stackoverflow.com/a/50960105

http://stackoverflow.com/q/51006714
tagged with: numpy-ndarray
has comment: http://stackoverflow.com/comment/89006722
answer count: 1
downvote count: 0
favorite count: 0
has body: Given an array X of shape (n, m) and another given number l how can I get an array Y of shape (n, l, m, l) where Y[i, j, :, :] is the null matrix that has been replaced the j-th column by the i-th row of X. For example, if X = np.array([ [1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6]]) l = 5 then Y[2, 3] = np.array([ [0, 0, 0, 3, 0], [0, 0, 0, 4, 0], [0, 0, 0, 5, 0], [0, 0, 0, 6, 0] ]) Thank you.
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89006716
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51006781
accepted answer: http://stackoverflow.com/a/51006781
score: 1
has title: Replacing each row with a column
tagged with: numpy

http://stackoverflow.com/q/50864254
score: 0
has title: Trouble installing Adafruit's DHT11 Python library
answer count: 1
has body: I followed these instructions to install the Adafruit DHT11 library (https://github.com/adafruit/Adafruit_Python_DHT): git clone https://github.com/adafruit/Adafruit_Python_DHT.git cd Adafruit_Python_DHT sudo apt-get install build-essential python-dev sudo python setup.py install And I found the library installed under /home/pi (I'm working with a Raspberry Pi 3). The file I want to fun is in /home/pi/Desktop so I move the library into that directory. However, I still can't run my python file properly. This is the error I'm getting: Traceback (most recent call last): File "sensorRead.py", line 4, in &lt;module&gt; import Adafruit_DHT ImportError: No module named 'Adafruit_DHT' How do I get rid of this error? And where should I move my file (or the library) so the library will work? Thank you.
tagged with: raspberry-pi3
has answer: http://stackoverflow.com/a/50865650
type: UnansweredQuestion
tagged with: python
tagged with: adafruit
tagged with: libraries
type: Question

http://stackoverflow.com/q/50879713
has answer: http://stackoverflow.com/a/50891920
has body: What is the practical difference between the Nuclide package for Atom and the Atom-IDE package? I'm only a novice Python programmer, and all I can piece together is that Atom-IDE is built from Nuclide, but they both seem to have similar features and language support.
accepted answer: http://stackoverflow.com/a/50891920
has title: Nuclide vs Atom-IDE
favorite count: 0
has comment: http://stackoverflow.com/comment/88832247
tagged with: python
has comment: http://stackoverflow.com/comment/88866801
score: 2
type: AnsweredQuestion
tagged with: nuclide-editor
type: Question
has comment: http://stackoverflow.com/comment/88821908
upvote count: 3
tagged with: atom-editor
has comment: http://stackoverflow.com/comment/88761727
answer count: 1
downvote count: 1
tagged with: ide

http://stackoverflow.com/comment/88795549
comment on: http://stackoverflow.com/q/50897891
has text: In general it is good to test the query in MySQL first before adding it to Python (or other) script.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89005048
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51005699
score: 1
has text: It is documented as a bug of sorts here: [Inconsistent behaviour of numpy.asarray on list of arrays #7453](https://github.com/numpy/numpy/issues/7453)

http://stackoverflow.com/comment/88720332
comment on: http://stackoverflow.com/q/50858476
score: 0
type: Comment
type: QuestionComment
has text: Your problem is not clear. What do you mean by "Divide each element by the next one"? It would have been more clear if you gave example input and output. Please read and follow [How to create a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve). Do you want `division(96, 2, 3, 2)` to calculate `96 / 2 / 3 / 2`, i.e. `((96 / 2) / 3) / 2`, and return `8.0`? Or do you want `1 / 96 / 2 / 3 / 2` and return `0.0008680555555555555`?

http://stackoverflow.com/a/50892244
has comment: http://stackoverflow.com/comment/88814150
has comment: http://stackoverflow.com/comment/88785404
type: Answer
has comment: http://stackoverflow.com/comment/88806320
upvote count: 1
has body: Make a script to read your CSVs row by row, and upload them using streaming inserts. The limit on streaming insterts is 100k rows/s or 100MB per second, whatever you reach first. bigquery.tabledata.insertAll does not have rate limiting on the number of API calls, so it's a good option for uploading lots of small files that would make you reach the quota for bigquery.tables.insert.
answers question: http://stackoverflow.com/q/50889174
downvote count: 0
score: 1

http://stackoverflow.com/comment/88952588
has text: in the except block, clean up the spacing, remember PEP8.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50978317
type: Comment

http://stackoverflow.com/comment/88849434
comment on: http://stackoverflow.com/a/50878290
type: AnswerComment
score: 0
has text: @gboffi May be it can works, but it add the array vertically, do you have to do that horizontally?
type: Comment

http://stackoverflow.com/q/51010869
has body: I'm using the python-gpg library to decrypt / encrypt. Validation while decrypting a mail works fine, but i'm also trying to check which key was used to created a PGP signature, for example when a mail was not encrypted, just signed. Is there a way to get the fingerprint or key_id from a gpg signature string using the python-gpg lib ? Thanks !
answer count: 1
has answer: http://stackoverflow.com/a/51829189
has title: How to get fingerprint or key_id from gpg signature in python?
type: UnansweredQuestion
tagged with: python
tagged with: gnupg
type: Question
tagged with: signature
score: 0

http://stackoverflow.com/comment/88786939
score: 0
has text: I guess should have specified that the points do not necessarily describe a smooth function. I updated my first sentence to reflect that.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50892760

http://stackoverflow.com/a/51501852
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/90390138
has body: Try to add some additional variable with dynamic value to URL (e.g. timestamp). This will prevent caching on the server side even if it ignores Cache-Control. Example: from: https://example.com/test to: https://example.com/test?timestamp=20180724181234
has comment: http://stackoverflow.com/comment/89975718
has comment: http://stackoverflow.com/comment/89996206
upvote count: 1
has comment: http://stackoverflow.com/comment/90388740
answers question: http://stackoverflow.com/q/50861027
downvote count: 0

http://stackoverflow.com/comment/88865483
comment on: http://stackoverflow.com/q/50933454
type: Comment
type: QuestionComment
score: 0
has text: You closed `logfile` too early? (In the for-loop)

http://stackoverflow.com/a/50940723
has comment: http://stackoverflow.com/comment/88879226
has comment: http://stackoverflow.com/comment/88879438
has comment: http://stackoverflow.com/comment/88879407
has comment: http://stackoverflow.com/comment/88879363
type: Answer
has comment: http://stackoverflow.com/comment/88879391
answers question: http://stackoverflow.com/q/50940673
has body: Have you checked that python is in your Environment PATH variable list? Try typing python --version in your windows command prompt and see if you get an error. If it does not return a version number, it has not been added to your PATH. If you don't know how to do this, refer to this link - https://www.java.com/en/download/help/path.xml
upvote count: 2
has comment: http://stackoverflow.com/comment/88879367
score: 1
downvote count: 1

http://stackoverflow.com/comment/88962475
type: Comment
has text: You might consider [paramiko](http://www.paramiko.org/) module helpful.
score: 0
comment on: http://stackoverflow.com/q/50982853
type: QuestionComment

http://stackoverflow.com/q/50947539
tagged with: pandas
has comment: http://stackoverflow.com/comment/88892393
has comment: http://stackoverflow.com/comment/88892745
favorite count: 0
tagged with: beautifulsoup
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88892832
type: UnansweredQuestion
tagged with: python
has title: Condensing Python For Loop
answer count: 0
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/88892373
type: Question
has body: I was wondering if it is possible to condense this double for loop within a web scrape. This works fine, but I just want to see if it's possible to condense to a single line: small_form = race.find_all('table', attrs={'class' : 'longFormSummary'})[0] count = (len(small_form.find_all('tr'))-1) for x in range(0,count): a = small_form.find_all('tr')[x] test = [s.text.strip().lower() for s in a.find_all('td')] I tried a few different ways but was unable to condense the test = line to absorb the two above. Edit: I tried the below with no luck: test = [a.text.strip().lower() for a in e.find_all('td') for e in small_form.find_all('tr')] Print of correct output is here: ['1', '5822', "nic's karma", '', '64', '90', '$8', '']
has comment: http://stackoverflow.com/comment/88892391
score: 0

http://stackoverflow.com/a/51009513
answers question: http://stackoverflow.com/q/51009466
downvote count: 0
type: Answer
upvote count: 1
has body: my_var = "Hello World" os.system('bash -c "linuxcmd &lt;&lt;&lt; "{}""'.format(my_var)) or in python3, using f-strings: os.system(f'bash -c "linuxcmd &lt;&lt;&lt; "{my_var}""') Tested this: my_var = 'test' os.system(f'bash -c "echo {my_var}"') with my python3 running on manjaro, works fine.
score: 1

http://stackoverflow.com/q/50980594
has answer: http://stackoverflow.com/a/50994458
tagged with: models
has comment: http://stackoverflow.com/comment/88958495
tagged with: machine-learning
type: Question
tagged with: time-series
score: -2
tagged with: data-science
downvote count: 2
has title: What kind of model can i use to forecast this data?
answer count: 1
favorite count: 0
type: UnansweredQuestion
has body: This is the dataset that I have of some orders each week. I want to predict the orders for the rest of the year. I've tried building an ARIMA model and it doesn't work. Is there any other model that I can try for such a small dataset? Maybe a HMM or try fitting a polynomial curve to it or build a time series LSTM? FW Order 1 6 2 45 3 59 4 60 5 50 6 115 7 23 8 44 9 164 10 8 11 30 12 20 13 0 14 50 15 60 16 0 17 50 18 30 19 115 20 75 21 54 22 29 23 124 24 32 25 28
tagged with: python
upvote count: 0

http://stackoverflow.com/a/50994253
score: 0
has body: You probably dont need regexp for this res = [w.split('/', 4)[3] for w in s.splitlines() if '/' in w]
answers question: http://stackoverflow.com/q/50993773
type: Answer

http://stackoverflow.com/comment/88865707
score: 0
has text: Hi all, thank you for your comments. The MySQL error I am getting is 1064 which is a standard syntax error. @user3483203.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50933434

http://stackoverflow.com/q/50948263
tagged with: mysql
type: Question
upvote count: 1
answer count: 1
tagged with: pymysql
accepted answer: http://stackoverflow.com/a/54317917
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/54317917
has title: columns with default NULL values returns as (None,) on SELECT python pymysql
type: AnsweredQuestion
has body: I'm using pymysql module to connect the database to the python project.But I'm getting an error when I run a SELECT query to get a value of a column This is my code block for sql query. sql_check_record = 'SELECT `suggestions` FROM `temp_suggestions` WHERE `word`= "%s"' %key cursor.execute(sql_check_record) new_val = cursor.fetchone() print(new_val) When the value of key exists in the word column, and suggestion column is empty it returns this (None,). But when the value of key is not exist in the word column it returns None I want to check whether the suggestion is NULL. As when the value of suggestion is NULL it returns (None,) how can I check whether it's NULL or not(if anything exists in the column). Because I want to concatenate to the existing value if a value exists.
has comment: http://stackoverflow.com/comment/88896089
downvote count: 0
score: 1

http://stackoverflow.com/comment/88757677
has text: `enumerate` is overkill here, given that `i == page - 1`
type: AnswerComment
comment on: http://stackoverflow.com/a/50877805
type: Comment
score: 1

http://stackoverflow.com/comment/88789572
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50892623
has text: @jason I'm really sorry for misunderstanding your question. Unfortunately, I cannot understand what you want. I'm sorry for my poor English skill. Can I ask you about what you want? You want to clear the font colors and formats. But you don't want to change the number format is not modified. Is my understanding correct?

http://stackoverflow.com/comment/89012163
score: 0
has text: It's not the string egg but instead the input() supplied by the user
comment on: http://stackoverflow.com/q/51009719
type: Comment
type: QuestionComment

google-app-engine-python
type: Tag
tag name: google-app-engine-python
tags question: http://stackoverflow.com/q/50909508

http://stackoverflow.com/comment/88834882
score: 0
has text: Wouldn't you want verb[0], verb[1] and verb[2]? Negatives would be out of range wouldn't they?
type: AnswerComment
comment on: http://stackoverflow.com/a/50917409
type: Comment

http://stackoverflow.com/comment/88839384
has text: Just updated it to show what I tried doing before
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50919315
score: 0

http://stackoverflow.com/comment/88852040
comment on: http://stackoverflow.com/q/50926394
score: 0
type: Comment
type: QuestionComment
has text: It's getting more and more obscure :). Please update your question with a comprehensive and detailed information about your input and output data. However, If you want to concatenate values you can use answers from https://stackoverflow.com/questions/41455975/concatenating-dict-values-which-are-lists (except the accepted answer, never use that!)

http://stackoverflow.com/comment/88900285
score: 0
has text: The error does bubble up - its just that `hasattr` catches it and returns `False`. So, this is question is just about raising alternate errors in the `hasattr` case?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50950939

http://stackoverflow.com/comment/88929262
has text: Also, why don't you want to use `firstName`?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50966390

http://stackoverflow.com/comment/88953741
type: Comment
comment on: http://stackoverflow.com/q/50978587
type: QuestionComment
has text: @Ereli the size of the dataset is 368,it is not a big dataset...
score: 0

http://stackoverflow.com/comment/133256383
has text: Remember that Stack Overflow isn't just intended to solve the immediate problem, but also to help future readers find solutions to similar problems, which requires understanding the underlying code. This is especially important for members of our community who are beginners, and not familiar with the syntax. Given that, **can you [edit] your answer to include an explanation of what you're doing** and why you believe it is the best approach?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/75526558
type: AnswerComment

http://stackoverflow.com/comment/88920884
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50960936
has text: Isn't this just hardcoding everything? I don't think this is better than the other two answers.
score: 0

http://stackoverflow.com/q/50983290
favorite count: 0
has answer: http://stackoverflow.com/a/50984318
accepted answer: http://stackoverflow.com/a/50984318
has title: passing an array with index of discrete feature to mutual_info_classif in python
tagged with: python
has answer: http://stackoverflow.com/a/50984425
upvote count: 1
type: Question
has body: I am using MI from sklearn.feature_selection.mutual_info_classif to calculate MI between 4 continuous variables(X matrix) and y(target class) X: prop_tenure prop_12m prop_6m prop_3m 0.04 0.04 0.06 0.08 0 0 0 0 0 0 0 0 0.06 0.06 0.1 0 0.38 0.38 0.25 0 0.61 0.61 0.66 0.61 0.01 0.01 0.02 0.02 0.1 0.1 0.12 0.16 0.04 0.04 0.04 0.09 0.22 0.22 0.22 0.22 0.72 0.72 0.73 0.72 0.39 0.39 0.45 0.64 **y** status 0 0 1 1 0 0 0 1 0 0 0 1 So my X is all continuous and y is discrete. There is a parameter in the function to which I can pass the index of discrete features: sklearn.feature_selection.mutual_info_classif(X, y, discrete_features=’auto’, n_neighbors=3, copy=True, random_state=None) and I am doing as below: print(mutual_info_classif(X,y,discrete_features = [3],n_neighbors = 20)) [0.12178862 0.12968448 0.15483147 0.14721018] Though this is not giving error, I am not sure if I am passing the right index for identifying the y variable as discrete and others as continuous. Can someone please clarify if I am wrong?
type: AnsweredQuestion
score: 1
answer count: 2
tagged with: feature-selection
possible better answer: http://stackoverflow.com/a/50984425
downvote count: 0
tagged with: scikit-learn

http://stackoverflow.com/a/56211475
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50913151
answers question: http://stackoverflow.com/q/50913151
type: AcceptedAnswer
has body: Okay, so for anyone else stumbling on this, the trick is to first define your colorbar the very first time you plot (initial figure) via the top Class its in, i.e., MyMplCanvas.cbar = MyMplCanvas.fig.colorbar(im). Its very important to define it up front even if you didn't want to even use it yet. Then at the top of the update plot function, simply call MyMplCanvas.cbar.remove().

http://stackoverflow.com/q/50973191
type: UnansweredQuestion
has title: Connect to MySQL db from Jupyter notebook
type: Question
score: 10
tagged with: mysql
linked to: http://stackoverflow.com/q/372885
has answer: http://stackoverflow.com/a/52054734
has answer: http://stackoverflow.com/a/50973427
favorite count: 0
has answer: http://stackoverflow.com/a/60896206
upvote count: 10
tagged with: python
has body: I am using Jupyter Notebooks to learn Python. I would like to connect to a MySQL db hosted locally hosted through MAMP. How would I approach this?
has answer: http://stackoverflow.com/a/61275606
answer count: 4
tagged with: jupyter-notebook
has comment: http://stackoverflow.com/comment/88943169
linked to: http://stackoverflow.com/q/55154372
downvote count: 0

http://stackoverflow.com/q/50899417
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88821888
has comment: http://stackoverflow.com/comment/88799749
has title: How to keep browsers open after console is closed
tagged with: python
has comment: http://stackoverflow.com/comment/88813176
score: 1
has comment: http://stackoverflow.com/comment/88800973
favorite count: 0
type: Question
upvote count: 2
has body: I am using selenium to do a bit of automation, but I would like to be able to keep the browser windows open even after the python console has been closed. Here are my current settings for the webdriver: capabilities = { 'browserName': 'chrome', 'version': '', 'platform': 'ANY', 'javascriptEnabled': True, 'chromeOptions': { 'useAutomationExtension': False, 'forceDevToolsScreenshot': True, 'detach': False, 'args': ['--start-maximized', '--disable-infobars', '--log-level=3'] } } driver = webdriver.Chrome(desired_capabilities=capabilities) Does anyone know how I can achieve this? Thanks.
has comment: http://stackoverflow.com/comment/88811157
downvote count: 1
has comment: http://stackoverflow.com/comment/88813541
has comment: http://stackoverflow.com/comment/88813720
tagged with: selenium-webdriver
has comment: http://stackoverflow.com/comment/88806973
has comment: http://stackoverflow.com/comment/88825303
has comment: http://stackoverflow.com/comment/88813745
has comment: http://stackoverflow.com/comment/88813030
has comment: http://stackoverflow.com/comment/88799658
answer count: 0

http://stackoverflow.com/comment/88824281
has text: @AjayGupta yes I have installed mysql.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50907013

http://stackoverflow.com/comment/88878565
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50939736
has text: Have you performed clicked operation ? If no, Perform and share what is an actual error you are getting.

http://stackoverflow.com/comment/88891596
type: QuestionComment
has text: When you modified the scope, did you delete ``credentials.json`` to reflect the new scopes? If you had not done it, how about deleting ``credentials.json`` once, and recreate the file by reauthorizing? If you had already done it, I'm sorry.
score: 0
comment on: http://stackoverflow.com/q/50945364
type: Comment

http://stackoverflow.com/comment/88900222
type: AnswerComment
comment on: http://stackoverflow.com/a/50950747
has text: I prefer not to add this to my answer since it should not work. As @James said _when you ran your first example, you had a variable called hotels in your global (interpreter) scope._ which is probably the case.
score: 0
type: Comment

http://stackoverflow.com/comment/88903893
score: 0
type: QuestionComment
has text: Yes, that solved the problem, in django documentation 2.0 the name attribute isn't there and for this I could think anything like that.
type: Comment
comment on: http://stackoverflow.com/q/50944043

http://stackoverflow.com/q/50977836
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/88951942
has title: DataFrame from dict of lists with column values being keys
has body: Suppose we have the following dict: things = {'George':['cat','kitty'], 'Stackoverflow':['questions','answers'], 'hungry':['im','always']} One could easily turn this into a list containing [[key1,value1]...[keyX,valueX]] and turn this into a dataframe that appears as: (index and column names ignored here) George cat George kitty Stackoverflow questions Stackoverflow answers hungry im hungry always However, is this possible to be one directly from a dictionary?
score: 4
has answer: http://stackoverflow.com/a/50977963
tagged with: pandas
has comment: http://stackoverflow.com/comment/88951686
favorite count: 0
tagged with: python-3.x
tagged with: python
accepted answer: http://stackoverflow.com/a/50977963
possible better answer: http://stackoverflow.com/a/50977899
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50977899
type: Question
upvote count: 4

http://stackoverflow.com/comment/89000145
score: 2
type: AnswerComment
has text: BTW, here is some discussion on ```import __main__```: https://stackoverflow.com/questions/24023601/is-it-good-practice-to-use-import-main. There are several points on why such imports can be bad.
comment on: http://stackoverflow.com/a/51003155
type: Comment

http://stackoverflow.com/comment/88940902
type: QuestionComment
has text: when you say "would require parallelizing (and hence use MLlib)", you mean in *multiple machines* (i.e. a cluster)?
comment on: http://stackoverflow.com/q/50915749
score: 0
type: Comment

http://stackoverflow.com/a/57893568
has comment: http://stackoverflow.com/comment/129370658
upvote count: 37
has comment: http://stackoverflow.com/comment/136453061
answers question: http://stackoverflow.com/q/50856103
score: 36
accepted answer of: http://stackoverflow.com/q/50856103
type: AcceptedAnswer
type: Answer
has body: Although this is old, here's a solution: Just put # nopep8 at the end of the line(s) that shouldn't be formatted. For a broader disabling of any formatters, # noqa can be used. (No Quality Assurance) Hope this can still help someone!
has comment: http://stackoverflow.com/comment/139743811
downvote count: 1
has comment: http://stackoverflow.com/comment/127572565

http://stackoverflow.com/comment/88859896
type: AnswerComment
has text: One possible reason why celery doesn't work is that it is installed in one virtual environment, and Apache is using a different virtual environment or a system python. It is impossible to tell without seeing the configuration but is it possible that you have Django installed in the system interpreter as well, and mod_wsgi is using it?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50930345

http://stackoverflow.com/q/50880183
accepted answer: http://stackoverflow.com/a/50880249
downvote count: 0
possible better answer: http://stackoverflow.com/a/50880327
answer count: 3
tagged with: pandas
favorite count: 0
has title: Combining columns in Pandas based on column header
has answer: http://stackoverflow.com/a/50880404
tagged with: python
has answer: http://stackoverflow.com/a/50880327
type: AnsweredQuestion
has body: I'm needing to merge columns in a dataframe. The headers will have a similar name with a different suffix, e.g. A1 | A2 | A3 | B1 | B2 | B3 I want to end up with all of them merged: A | B I have this line that successfully merges a defined set of columns into a single column: df['A'] = df'A1','A2','A3.apply(' '.join, axis=1) The problem is that the headers are inconsistent in that there might be any combination of '1','2',or '3' - e.g. A1 | A2 | A3 | B2 | C1 | C2 From the solutions I've looked at, pandas doesn't like to reference columns that don't exist, so I can't use apply statement as a blanket command. I'm having trouble visualizing a solution beyond a list of nested Try/Except steps. If anyone has an idea, I would appreciate it! Update Thanks for the solutions!!! If anyone is interested, here's what worked for me: Solution 1 for h in headers: cols = [col for col in df.columns if col.split('[')[0] == h] if cols == []: cols = [col for col in df.columns if col == h and col.split('[')[0] not in headers] ` Solution 2 df.groupby(df.columns.str.split('[').str[0],axis=1).agg(lambda x :' '.join(x.values.tolist()))
score: 1
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/50880249

http://stackoverflow.com/q/50917285
tagged with: python
tagged with: selenium-webdriver
tagged with: xpath
has comment: http://stackoverflow.com/comment/88836125
has comment: http://stackoverflow.com/comment/88836687
type: Question
tagged with: c#
linked to: http://stackoverflow.com/q/32382686
has body: I have a method to get an ancestor element of a web_element: def find_ancestor(self, name): element = self.driver.find_element_by_name(name) ancestor = element.find_element_by_xpath("ancestor::*") print(ancestor) attr = ancestor.get_attribute("outerHTML") print(attr) The output for print(ancestor) is &lt;selenium.webdriver.remote.webelement.WebElement (session="43f99228044a37dab999a9512b5e268e", element="0.22129539497775563-3")&gt; When I try to access and print attributes I get an error: UnicodeEncodeError: 'charmap' codec can't encode character u'\xae' in position 292: character maps to &lt;undefined&gt; The top of my script has # -*- coding: utf-8 -* What am I missing/doing wrong? My feeling is 'ancestor' returns differently than other xpath axes!? background/bonus help Ideally, I want methods to get parent, preceding-sibling, following-sibling etc. But when I try such actions on a table cell preceding-sibling is not getting the previous cell (no element found), and with parent I am getting back the same element (the same table cell and not table row). I am showing python but don't mind answers in c#.
score: 0
has answer: http://stackoverflow.com/a/50918363
answer count: 1
has title: Error getting ancestor web element attributes
type: UnansweredQuestion

http://stackoverflow.com/a/50891141
has comment: http://stackoverflow.com/comment/88783458
score: -1
downvote count: 1
has body: You will have another process listening on port 8080. You can check to see what that is and kill it. You can find processes listening on ports with netstat -tulpn. Before you do that, check to make sure you don't have another terminal window open with the running instance.
has comment: http://stackoverflow.com/comment/88783237
type: Answer
upvote count: 0
answers question: http://stackoverflow.com/q/50891073

http://stackoverflow.com/q/50921536
has title: csv writing alternate whitespace in lines within a loop python
tagged with: python-2.7
type: AnsweredQuestion
score: 3
has body: I have a code for generating a csv file shown below. import csv csvData = "HAI", "Hello" while(1): with open('test.csv', 'a') as csvFile: writer = csv.writer(csvFile, delimiter=',', quoting=csv.QUOTE_ALL) writer.writerows(csvData) csvFile.close() When i run this code it will generate a csv file like this 1."HAI","Hello" 3."HAI","Hello" That is it will generate on alternative lines,that is first write takes palce on line 1 ,second write takes on line 3.I want to write it on line 2. Anybody please help me.
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/50921672
type: Question
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
accepted answer: http://stackoverflow.com/a/50921672
upvote count: 3
answer count: 1
has comment: http://stackoverflow.com/comment/88842671

http://stackoverflow.com/comment/88928407
type: Comment
has text: I think I tried, and it seemed to have no effect. But I will try again next time I get back to this work and report the results of my experiments in the question.
comment on: http://stackoverflow.com/a/50950209
score: 0
type: AnswerComment

boolean
tags question: http://stackoverflow.com/q/50987850
tags question: http://stackoverflow.com/q/50865421
tags question: http://stackoverflow.com/q/51000457
tags question: http://stackoverflow.com/q/50996494
tags question: http://stackoverflow.com/q/50878867
tags question: http://stackoverflow.com/q/50861775
tag name: boolean
tags question: http://stackoverflow.com/q/50999577
tags question: http://stackoverflow.com/q/50965844
tags question: http://stackoverflow.com/q/50988348
type: Tag

http://stackoverflow.com/q/50867985
has comment: http://stackoverflow.com/comment/88738189
upvote count: 3
has comment: http://stackoverflow.com/comment/88738026
type: Question
has answer: http://stackoverflow.com/a/50868469
has comment: http://stackoverflow.com/comment/88738722
has body: I was using this method, but the for loop skips over the elements. After debugging, I know why it skipped, so I want to know if there's a better method or the proper method. Here's the code I have: class Birthday: name = '' date = '' def __init__(self, name, date): self.name = name self.date = date ... dt1 = datetime.datetime.utcfromtimestamp(1428916628.0) # Year: 2015 dt2 = datetime.datetime.utcfromtimestamp(1328916628.0) # Year: 2012 dt3 = datetime.datetime.utcfromtimestamp(1228916628.0) # Year: 2008 dt4 = datetime.datetime.utcfromtimestamp(1128916628.0) # Year: 2005 dt5 = datetime.datetime.utcfromtimestamp(1028916628.0) # Year: 2002 b1 = Birthday('John', dt1) b2 = Birthday('Larry', dt2) b3 = Birthday('David', dt3) b4 = Birthday('Joe', dt4) b5 = Birthday('Jerry', dt5) # Elements are mixed on purpose dt_list = [b3, b1, b5, b4, b2] # Sort the order of elements by date dt_list.sort(key=lambda y: y.date) for x in dt_list: dt_list.remove(x) if len(dt_list) &lt;= 3: break Expected: 2008, 2012, 2015 Result: 2005, 2012, 2015 I was thinking of adding this to the first newline of the for loop: x = dt_list[0] But it doesn't feel right.
has comment: http://stackoverflow.com/comment/88738197
has comment: http://stackoverflow.com/comment/88738286
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/88738318
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/50868469
has title: What's the best method for iterating through a list and removing elements? The current way I'm doing it causes elements to be skipped
tagged with: python
has comment: http://stackoverflow.com/comment/88738048
type: AnsweredQuestion
score: 3

hex
tags question: http://stackoverflow.com/q/51011247
tag name: hex
tags question: http://stackoverflow.com/q/51010674
tags question: http://stackoverflow.com/q/50902906
tags question: http://stackoverflow.com/q/51009018
type: Tag

http://stackoverflow.com/comment/88906821
has text: how can I remove or reset my interpreter, I restarted everything and still have this issue I even made a new class and for hotels its not giving error !!!
comment on: http://stackoverflow.com/a/50950996
type: AnswerComment
type: Comment
score: 0

http://stackoverflow.com/q/50876996
type: UnansweredQuestion
has body: I want run sensor step by step in tensorflow, so I use the partial_run_setup and partial_run. And this code run with no error: import tensorflow as tf x = tf.placeholder("float") feed = {x: 3.0} a = tf.Variable(1.0) b = tf.Variable(2.0) o1=tf.add(a,x) o2=tf.train.AdadeltaOptimizer(0.1).minimize(o1) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) print(sess.run(o2,feed)) But this code show error: import tensorflow as tf x = tf.placeholder("float") feed = {x: 3.0} a = tf.Variable(1.0) b = tf.Variable(2.0) o1=tf.add(a,x) o2=tf.train.AdadeltaOptimizer(0.1).minimize(o1) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) h = sess.partial_run_setup([o1, o2], [x]) print(sess.partial_run(h, o1,feed)) print(sess.partial_run(h, o2,feed)) And error list: Traceback (most recent call last): File "test.py", line 15, in &lt;module&gt; print(sess.partial_run(h, o2,feed)) File "/home/zhcong/.local/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 945, in partial_run return self._run(handle, fetches, feed_dict, None, None) File "/home/zhcong/.local/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1120, in _run feed_dict_tensor, options, run_metadata) File "/home/zhcong/.local/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1319, in _do_run return self._do_call(_prun_fn, self._session, handle, feeds, fetches) File "/home/zhcong/.local/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1323, in _do_call return fn(*args) File "/home/zhcong/.local/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1306, in _prun_fn raise RuntimeError('partial_run() requires empty target_list.') RuntimeError: partial_run() requires empty target_list.
has title: partial_run() requires empty target_list
has answer: http://stackoverflow.com/a/52680385
score: -1
tagged with: tensorflow
type: Question
answer count: 1
downvote count: 1
favorite count: 0
tagged with: deep-learning
tagged with: python
upvote count: 0

http://stackoverflow.com/a/50869213
has body: Use the join method. Usage below - df.set_index('Master_ID').join(df2.set_index('Master_ID'))
downvote count: 0
type: AcceptedAnswer
score: 1
accepted answer of: http://stackoverflow.com/q/50868998
type: Answer
answers question: http://stackoverflow.com/q/50868998
upvote count: 1

http://stackoverflow.com/comment/88729377
has text: How do you define if a week is in a month? Weeks can overlap between two months.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50863425

http://stackoverflow.com/q/50980884
tagged with: python
type: Question
answer count: 2
tagged with: amazon-ec2
tagged with: boto3
tagged with: amazon-web-services
has answer: http://stackoverflow.com/a/50982845
score: 0
has title: Python Boto3 invalid parameter for modify_instance_attribute
has body: I'm trying to right-size an instance and the below code seems to work. import boto3 client = boto3.client('ec2') # Insert your Instance ID here my_instance = 'i-xxxxxxxx' # Stop the instance client.stop_instances(InstanceIds=[my_instance]) waiter=client.get_waiter('instance_stopped') waiter.wait(InstanceIds=[my_instance]) # Change the instance type client.modify_instance_attribute(InstanceId=my_instance, Attribute='instanceType', Value='m3.xlarge') # Start the instance client.start_instances(InstanceIds=[my_instance]) The above works perfectly fine for 1 instance i.e. if i provide 1 instance id. But if i provide more that 1 instance id as a list like my_instance = ['i-03647275c3c33e672', 'i-0a0aa44ffa22faef3', 'i-0a3709b2bd92bbcdb'] I get an error as below: Invalid type for parameter InstanceIds, value: i-03647275c3c33e672, i-0a0aa44ffa22faef3, i-0a3709b2bd92bbcdb, type: &lt;type 'str'&gt;, valid types: &lt;type 'list'&gt;, &lt;type 'tuple'&gt; From what I understand, the error occurs on the line: client.modify_instance_attribute(InstanceId=my_instance, Attribute='instanceType', Value='m3.xlarge') at the InstanceId attribute. I tried looping over it using a for loop, still no go. Any advice?
has answer: http://stackoverflow.com/a/50990145
tagged with: python-3.x
type: UnansweredQuestion

http://stackoverflow.com/comment/89012124
type: Comment
type: QuestionComment
has text: i m not able to reproduce the error, your code works absolutely perfect for me. Try to print and check the values of dir_path and filename on the console
comment on: http://stackoverflow.com/q/51008473
score: 0

http://stackoverflow.com/a/50888104
has body: Because otherwise all function calls that didn't return anything would print None.
upvote count: 1
answers question: http://stackoverflow.com/q/50888091
has comment: http://stackoverflow.com/comment/88777542
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/comment/88858426
score: 0
type: Comment
type: QuestionComment
has text: There is only one value per 15 mins. The min, max and mean values should be calculated for every monday, tuesday, ... in the whole year for 00:15, 00:30, 00:45 and so on.
comment on: http://stackoverflow.com/q/50929063

http://stackoverflow.com/a/50900636
has comment: http://stackoverflow.com/comment/88802123
type: Answer
has comment: http://stackoverflow.com/comment/88801583
accepted answer of: http://stackoverflow.com/q/50899901
answers question: http://stackoverflow.com/q/50899901
has comment: http://stackoverflow.com/comment/88801365
upvote count: 1
downvote count: 1
has body: When using categorical ranges, you have to tell figure what the categories for the axis are and what order you want them to show up, e.g. provide x_range something like: # specify all the factors for the x-axis by passing x_range p = figure(..., x_range=sorted(df.naam.unique())) It's also possible the NaN values are a problem, since they are "contagious". I'd recommend changing them to zeros instead in any case. Finally the error message probably indicates that your colors list is the wrong length. You are stacking two bars in each column, so the list of colors needs to also be two (one color for each "row" in the stack).
type: AcceptedAnswer
score: 0

http://stackoverflow.com/comment/88787378
has text: PostgreSQL works well
type: QuestionComment
type: Comment
score: 2
comment on: http://stackoverflow.com/q/50892740

http://stackoverflow.com/comment/88961497
score: 0
has text: Im not sure, but from what i can gather because you want to multiply the first element of tensor a to the first element of tensor b,The product will be always the same for all the 20 batches, So why dont you just plainly initialize a tensor of `torch.tensor(20, 96*16, 110)` here 20 being the batch size
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50982503

virtualenv
tags question: http://stackoverflow.com/q/50966876
tags question: http://stackoverflow.com/q/50890887
tags question: http://stackoverflow.com/q/51002646
tags question: http://stackoverflow.com/q/50912733
tags question: http://stackoverflow.com/q/50975869
tags question: http://stackoverflow.com/q/50882971
tags question: http://stackoverflow.com/q/50864798
tags question: http://stackoverflow.com/q/50950571
tags question: http://stackoverflow.com/q/50949973
tags question: http://stackoverflow.com/q/50974960
tags question: http://stackoverflow.com/q/50892346
tags question: http://stackoverflow.com/q/50863043
tags question: http://stackoverflow.com/q/50995662
tags question: http://stackoverflow.com/q/50868309
tags question: http://stackoverflow.com/q/50910230
tag name: virtualenv
tags question: http://stackoverflow.com/q/50991725
tags question: http://stackoverflow.com/q/50913826
tags question: http://stackoverflow.com/q/50957229
tags question: http://stackoverflow.com/q/50946055
tags question: http://stackoverflow.com/q/50943130
type: Tag
tags question: http://stackoverflow.com/q/50902497

http://stackoverflow.com/q/50956201
favorite count: 0
has title: multiprocessing.dummy doesn't improve speed
type: UnansweredQuestion
tagged with: multithreading
tagged with: python
has comment: http://stackoverflow.com/comment/88910581
has comment: http://stackoverflow.com/comment/88910463
answer count: 0
downvote count: 0
score: 1
has body: From other posts, I read that all you need to do for multi threading in python is to use this simple code from multiprocessing.dummy import Pool as ThreadPool pool = ThreadPool(8) results = pool.map(extract_from_file, file_list) to replace for file in file_list: extract_from_file(file) In my case, extract_from_file(file) reads in a very long file and cuts it into interesting sequences, that are saved in different folders. In my case, the multi threading brings no speed improvement at all. However, what I find strange is that I can manually split up the list and just open Spyder several times and run multiple instances of python without multi threading, which leads to a big speed improvement. Does that proof anything, i.e. can I assume that my function can be multi threaded, just not with this specific library?
type: Question
tagged with: python-multiprocessing
has comment: http://stackoverflow.com/comment/88948302
has comment: http://stackoverflow.com/comment/88910518
has comment: http://stackoverflow.com/comment/88910523
upvote count: 1

http://stackoverflow.com/a/50914480
score: 4
has comment: http://stackoverflow.com/comment/140142691
upvote count: 4
downvote count: 0
type: Answer
has body: UPD from author of question: For everyone with same problem: you need to add that function to UserCreateForm: def clean(self): password = self.cleaned_data.get('password') if password: try: password_validation.validate_password(password, self.instance) except forms.ValidationError as error: self.add_error('password', error)
answers question: http://stackoverflow.com/q/50878903

http://stackoverflow.com/a/50872496
downvote count: 0
has body: If you only have two separator you can use str.split() as following: In [15]: sp = s.split(';') In [18]: result = sp[0] + sp[-1] In [19]: result Out[19]: 'abcdklmn' Otherwise, based on your string and expected result you can use regular expressions to find the desired sub-strings. Demo: In [25]: s Out[25]: 'abcd;efghij;klmn' In [26]: re.sub(r'(;[^;]*)?;', '', s) Out[26]: 'abcdklmn' In [27]: s="abcd;klmn" In [28]: re.sub(r'(;[^;]*)?;', '', s) Out[28]: 'abcdklmn'
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/88750482
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50872472
has comment: http://stackoverflow.com/comment/88750272
has comment: http://stackoverflow.com/comment/88753054
accepted answer of: http://stackoverflow.com/q/50872472

http://stackoverflow.com/comment/88948346
type: QuestionComment
has text: you can use pandas to read all the sheets https://stackoverflow.com/a/17977609/1265980 write them out in any format.
comment on: http://stackoverflow.com/q/50975695
score: 0
type: Comment

http://stackoverflow.com/q/50974936
linked to: http://stackoverflow.com/q/50952288
has title: pycharm - how to trace hidden class method __get__
has comment: http://stackoverflow.com/comment/88946045
type: Question
has answer: http://stackoverflow.com/a/50974996
score: 2
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/88946066
accepted answer: http://stackoverflow.com/a/50974996
favorite count: 0
tagged with: pycharm
upvote count: 2
tagged with: python
type: AnsweredQuestion
has body: class Foo(): def __init__(self): self.bar_ref = self.bar # Allocation occurs here self.x = 0.1 def bar(self, _): self.x *= 1.2 @wim said The dotted attribute access self.bar is an invocation of descriptor __get__, creating a bound method. How do I get Pycharm to show __get__ being executed when debugging?

http://stackoverflow.com/q/50861016
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/88726033
type: AnsweredQuestion
has title: PySpark recursive key search
has comment: http://stackoverflow.com/comment/88725577
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51154673
accepted answer: http://stackoverflow.com/a/51154673
has body: I have a deeply nested json esque structure that I need to search for a given key at all levels (up to 7) for all occurrences. There is data always present in level 0 that I need to associate with each occurrence of the search_key found at any level. I've tried pushing this data through the recursive calls and appending it on return, but I have ran into heap and unhashable type issues when I move this from standard Python to a PySpark RDD. My search function is below: def search(input, search_key, results): if input: for i in input: if isinstance(i, list): search(i, search_key, results) elif isinstance(i, dict): for k, v in i.iteritems(): if k == search_key: results.append(i) continue elif isinstance(v, list): search(v, search_key, results) elif isinstance(v, dict): search(v, search_key, results) return results And I have been calling it with: origin_rdd = sc.parallelize(origin) concept_lambda = lambda c: search(c, term, []) results = origin_rdd.flatMap(concept_lambda) Can anybody suggest a way to capture the top level data and have it as part of each object in results? Results could be 0 to n so a product of 7 keys always present in the top level and then all occurrences of the search term collection. I then want to transform each row in the resulting RDD into a PySpark Row for use with a PySpark DataFrame. I have not found a good way to start with a DataFrame instead of an RDD or apply the search function to a DataFrame column because the structure is highly dynamic in its schema, but happy to hear suggestions if somebody thinks that's a better route.
score: 1
tagged with: pyspark
tagged with: http://stackoverflow.com/tag/json
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/88790495
type: AnswerComment
has text: yes, it says that PyQt5 and jinja are installed - but why am i getting a "no module named "PyQt5"" Error in my vanilla python enviroment >.>? when i run the pyqt script in my venv, it works all well - but i have to be able to use it in vanilla in order to use my IDE
comment on: http://stackoverflow.com/a/50880692
type: Comment
score: 0

http://stackoverflow.com/comment/88763437
type: Comment
has text: Correct. There is no other <direct> way to do this
type: AnswerComment
comment on: http://stackoverflow.com/a/50879725
score: 0

http://stackoverflow.com/comment/88733990
comment on: http://stackoverflow.com/q/50865236
score: 1
has text: Possible duplicate of [creating spark data structure from multiline record](https://stackoverflow.com/questions/31227363/creating-spark-data-structure-from-multiline-record)
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50973789
score: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/88945004
has body: Here's the Pandorable solution. For splitting Character, you have a choice of splitting on whitespace or slicing on character count. Which works best depends on your dataset. Whether you choose the pure Python or Pandas solution, you do not need to use an explicit loop. # remove last 6 characters to leave names df['Character'] = df['Character'].str[:-6] # or, df['Chracter'].str.split().str[0] # calculate length in new series df['Length'] = df['Character'].map(len) # convert to dictionary d = df.set_index('Character')['Length'].to_dict() print(d) {'Amy': 3, 'Tails': 5, 'Shadow': 6, 'Blaze': 5}
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/50973663

http://stackoverflow.com/a/50996017
has comment: http://stackoverflow.com/comment/94757291
has comment: http://stackoverflow.com/comment/106894235
upvote count: 21
downvote count: 1
has comment: http://stackoverflow.com/comment/139226986
answers question: http://stackoverflow.com/q/50992713
accepted answer of: http://stackoverflow.com/q/50992713
has comment: http://stackoverflow.com/comment/106921370
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/106921245
score: 20
type: Answer
has body: I finally found the answer after Googling around a bit. import pyspark.sql.functions as F df = spark.createDataFrame([(1, float('nan')), (None, 1.0)], ("a", "b")) df.show() +----+---+ | a| b| +----+---+ | 1|NaN| |null|1.0| +----+---+ for column in df.columns: df = ( # usage of "isnan()" function to test and replace values df.withColumn(column, F.when(F.isnan(F.col(column)), F.lit(None)) .otherwise(F.col(column))) ) sqlContext.registerDataFrameAsTable(df, "df2") sql('select * from df2').show() +----+----+ | a| b| +----+----+ | 1|null| |null| 1.0| +----+----+ It doesn't use na.fill(), but it accomplished the same result, so I'm happy.

http://stackoverflow.com/comment/104678037
has text: If you're using the Sequential method in Keras and you create a new model by starting with model=Sequential(), then I agree that your previous model should be overwritten. I couldn't find confirmation in the docs, however.
comment on: http://stackoverflow.com/q/50895110
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50945403
has body: Here is a sample data. Whenever I see a Not win or Not fail in Event column, I want to change the value in row-1 of Time column to 0. x = pd.DataFrame({'Id': [102,303,944, 111, 675, 236], 'Event':['win', 'fail','Not fail','win','win','Not win'], 'Time':[10,22,0, 23, 45, 0]}) This is how the outcome should look. Event Id Time 0 win 102 10 1 fail 303 0 2 Not fail 944 0 3 win 111 23 4 win 675 0 5 Not win 236 0
favorite count: 0
has answer: http://stackoverflow.com/a/50945664
upvote count: 3
tagged with: pandas
possible better answer: http://stackoverflow.com/a/50945520
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/50945685
accepted answer: http://stackoverflow.com/a/50945685
downvote count: 0
linked to: http://stackoverflow.com/q/19226488
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/50945612
has answer: http://stackoverflow.com/a/50945520
has title: Replace cell values from pandas dataframe
tagged with: dataframe
type: Question

http://stackoverflow.com/comment/89104073
type: Comment
comment on: http://stackoverflow.com/a/50984159
has text: @JoseRamon: Your discriminative losses look correct (i.e. cross-entropy over the true/estimated "fakeness", to teach `D` to discriminate real & fake pairs; to teach `G` to fool `D` so it thinks fake images are real). About providing or not class information to `G`, it depends on your use-case. If you will always have access to this information when inferring new data, it makes sense to take advantage and use the label as generation input. If you have only class labels during training, you could have a look at solutions like Triple-GAN, PixelDA, etc. (w/ auxiliary classifier to help train `G`)
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88985528
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50992402
has text: Problem with that is the source code is extremely long.

http://stackoverflow.com/a/50999625
downvote count: 0
has comment: http://stackoverflow.com/comment/88993739
type: Answer
answers question: http://stackoverflow.com/q/50999548
score: 2
has body: Easiest would be to shuffle and zip appropriate lists: import random names = ["Hilmi", "Joris", "Isa", "Dennis", "Jasper"] prices = 2 * ["You have won the drill-motor" , "You have won the DC motor"] random.shuffle(names) random.shuffle(prices) # shuffling prices is not strictly necessary # the random name order already guarantees everybody's fair chance ;) for name, price in zip(names, prices): print(name, price) # Hilmi You have won the DC motor # Jasper You have won the drill-motor # Dennis You have won the DC motor # Joris You have won the drill-motor
has comment: http://stackoverflow.com/comment/88993933
upvote count: 2

http://stackoverflow.com/q/50934333
has comment: http://stackoverflow.com/comment/88869080
has comment: http://stackoverflow.com/comment/88867200
score: 0
has comment: http://stackoverflow.com/comment/93210627
tagged with: python
has comment: http://stackoverflow.com/comment/88868719
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/93205040
tagged with: pip
has title: Error trying to install Label-Maker Python 3 on Windows
has body: I'm trying to install label-maker on python in windows 10 using python 3 in a Jupyter Notebook of Anaconda Navigator. But I'm getting this error !pip install label-maker errors.DistutilsPlatformError: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools Command "python setup.py egg_info" failed with error code 1 in C:\Users\Yeison\AppData\Local\Temp\pip-install-1c8s62ql\pyproj\ I install "Microsoft Visual C++ 14.0, but didn't work. I've been searching for answer here, but no one solved this. I'm new on python. Thanks!
type: Question

http://stackoverflow.com/a/57539807
score: 0
type: Answer
has body: This is a bit modified and works fine for me. import random import curses s=curses.initscr() curses.curs_set(0) sh,sw=s.getmaxyx() w=curses.newwin(sh,sw,0,0) w.keypad(1) w.timeout(100) snk_x=sw//4 snk_y=sh//2 snake=[ [snk_y,snk_x], [snk_y,snk_x-1], [snk_y,snk_x-2] ] food=([sh//2,sw//2]) w.addch(food[0],food[1],curses.ACS_PI) key=curses.KEY_RIGHT while True: next_key=w.getch() key=key if next_key==-1 else next_key if snake [0][0] in [0,sh] or snake [0][1] in [0,sw] or snake[0] in snake [1:]: curses.endwin() quit() new_head =[snake[0][0],snake[0][1]] if key ==curses.KEY_DOWN: new_head[0]+=1 if key==curses.KEY_UP: new_head[0]-=1 if key==curses.KEY_LEFT: new_head[1]-=1 if key==curses.KEY_RIGHT: new_head[1]+=1 snake.insert(0,new_head) if snake[0]==food: food=None while food is None: nf=[ random.randint(1,sh-1), random.randint(1,sw-1) ] food=nf if nf not in snake else None w.addch(food[0],food[1],curses.ACS_PI) else: tail=snake.pop() w.addch(tail[0],tail[1],' ') w.addch(snake[0][0],snake[0][1],curses.ACS_CKBOARD)
answers question: http://stackoverflow.com/q/51007306

http://stackoverflow.com/q/51008903
has answer: http://stackoverflow.com/a/51008928
favorite count: 0
tagged with: python
has body: So I tried to build this simple code to try to guess a number: y = raw_input() print type(y) x = int('y') print type(x) if x &gt; 0: print 'positive' if x &gt; 10: print 'Greater than 10' else: print 'less than 10' elif x == 0: print 'equals 0' print 'Conditionals are over' print 'Bye Bye' However, running the code in windows powershell, it displays an error: Value error in line 11, stating Invalid literal for int() with Base 10. What does that mean and how can it be fixed?
has answer: http://stackoverflow.com/a/51008954
has comment: http://stackoverflow.com/comment/89010636
type: UnansweredQuestion
downvote count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/89010717
score: -1
type: Question
tagged with: python-2.7
answer count: 2
has title: Invalid literal for int() with Base 10''

http://stackoverflow.com/a/50974389
answers question: http://stackoverflow.com/q/50974075
type: Answer
has body: This program works because this snippet of code: factorial(user_input) Takes the value of the variable user_input and passes it to the number variable specified in the def factorial(number): function when the function is called. This works as such because Python is a "Pass By Value" language. The input'ed variable is not used in the function, rather the value associated with it is passed into the function and assigned to a new variable. Extra Info: Java is an example of a "Pass by Reference" Language. I.E. it would use the original variable instead of passing it to a new variable.
score: 2
downvote count: 0
upvote count: 2

http://stackoverflow.com/q/51005837
tagged with: python
has title: Issues passing self to class decorator in python
type: Question
has comment: http://stackoverflow.com/comment/89005227
has answer: http://stackoverflow.com/a/51006675
tagged with: class
score: 0
answer count: 1
tagged with: decorator
tagged with: asynchronous
has comment: http://stackoverflow.com/comment/89005208
has body: I am new to decorators but ideally I wan to use them to simply define a bunch of class functions within class OptionClass, each representing some particular option with a name and description and if it's required. I don't want to modify the operation of the class function at all if that makes sense, I only want to use the decorator to define name, description, and if it's required. Problem 1: I construct an OptionClass() and I want to call it's option_1. When I do this I receive a TypeError as the call decorator is not receiving an instance of OptionClass. Why is this? When I call option_1 passing the instance of OptionClass() it works. How do I call option_1 without needing to always pass the instance as self. The error when received is: Traceback (most recent call last): File "D:/OneDrive_P/OneDrive/projects/python/examples/dec_ex.py", line 110, in &lt;module&gt; print(a.option_1("test")) # TypeError: option1() missing 1 required positional argument: 'test_text' File "D:/OneDrive_P/OneDrive/projects/python/examples/dec_ex.py", line 80, in __call__ return self.function_ptr(*args, **kwargs) TypeError: option_1() missing 1 required positional argument: 'test_text' Problem 2: How would I run or call methods on the decorator to set_name, set_description, set_required? Problem 3: Although this is a sample I intend to code an option class using async functions and decorate them. Do I need to make the decorator call be async def __call__() or is it fine since it's just returning the function? class option_decorator(object): def __init__(self, function_pt): self.function_ptr = function_pt self.__required = True self.__name = "" self.__description = "" def set_name(self, text): self.__name = text def set_description(self, text): self.__description = text def set_required(self,flag:bool): self.__required = flag def __bool__(self): """returns if required""" return self.__required def __call__(self, *args, **kwargs): return self.function_ptr(*args, **kwargs) def __str__(self):…
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89005163

http://stackoverflow.com/q/50951889
score: 3
has comment: http://stackoverflow.com/comment/88902975
has title: Finding most similar sentence match
type: Question
tagged with: cosine-similarity
has comment: http://stackoverflow.com/comment/88901811
has answer: http://stackoverflow.com/a/50952704
tagged with: scikit-learn
has body: I have a large dataset containing a mix of words and short phrases, such as: dataset = [ "car", "red-car", "lorry", "broken lorry", "truck owner", "train", ... ] I am trying to find a way to determine the most similar word from a short sentence, such as: input = "I love my car that is red" # should map to "red-car" input = "I purchased a new lorry" # should map to "lorry" input = "I hate my redcar" # should map to "red-car" input = "I will use my truck" # should map to "truck owner" input = "Look at that yellow lorri" # should map to "lorry" I have tried a number of approaches to this with no avail, including: Vectoring the dataset and the input using TfidfVectorizer, then calculating the Cosine similarity of the vectorized input value against each individual, vectorized item value from the dataset. The problem is, this only really works if the input contains the exact word(s) that are in the dataset - so for example, in the case where the input = "trai" then it would have a cosine value of 0, whereas I am trying to get it to map to the value "train" in the dataset. The most obvious solution would be to perform a simple spell check, but that may not be a valid option, because I still want to choose the most similar result, even when the words are slightly different, i.e.: input = "broke" # should map to "broken lorry" given the above dataset If someone could suggest other potential approach I could try, that would be much appreciated.
upvote count: 3
answer count: 2
tagged with: sentence-similarity
downvote count: 0
tagged with: nlp
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50966831
tagged with: python
has comment: http://stackoverflow.com/comment/88902360

http://stackoverflow.com/q/50950973
upvote count: 1
type: Question
tagged with: robotframework
tagged with: automation
tagged with: frameworks
has comment: http://stackoverflow.com/comment/88906708
answer count: 3
has answer: http://stackoverflow.com/a/51443955
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/50954732
has body: I am using Robot Framework to do test automation and would like to know if there is a way for me to extend the Selenium Webdriver to handle a loading element universally. For reference when I say loading element I am referring to a custom Angular element. I understand that I can do a Wait Until Element Not Visible, but what I really want to do is create a constant listener on the Selenium Webdriver to halt whenever this loading element is visible. I would like to not constantly use a robot keyword to check if the element is visible, and be forced to implement arbitrary-ish sleeps. If my question is still not clear, below is some pseudocode / psuedoflow I was thinking of. I'm assuming Selenium is single threaded, otherwise this idea would be fruitless. Selenium Webdriver: AddListener(new LoadingListener) LoadingListener While ( LoadingElement is Visible) Sleep 1s Please respond with any feedback. If this isn't possible let me know, If you have any ideas also let me know.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88905131
has title: Robot Framework Extending Selenium To Handle Loading Element
tagged with: python
has answer: http://stackoverflow.com/a/50960940
score: 1
tagged with: selenium

http://stackoverflow.com/comment/88796227
type: Comment
has text: I think the link I gave already solves your issue. Have you read through it? If it doesn't, can you tell me what's missing so I can try address that? I'm not clear on your issue currently.
comment on: http://stackoverflow.com/q/50897976
score: 0
type: QuestionComment

http://stackoverflow.com/q/50891018
tagged with: debugging
score: 3
has answer: http://stackoverflow.com/a/51083519
linked to: http://stackoverflow.com/q/5626193
tagged with: types
answer count: 1
downvote count: 0
favorite count: 0
has title: Pycharm: how to set a custom string function (ie Type Renderer) for external object types?
tagged with: lxml
tagged with: python
accepted answer: http://stackoverflow.com/a/51083519
type: AnsweredQuestion
tagged with: pycharm
upvote count: 3
has body: Is it possible to configure PyCharm to use a custom function to display the __str__ representation of a type in a debug session? I am referring to built-in types or types imported from third party libraries which I would rather not modify. For example, instead of a string in the debugger like {lxml.html.HtmlElement} &lt;Element tr at 0x10e2c1418&gt; I would like to have the output of etree.tostring(element). Intellij Idea has Java Type Renderers where you can set a custom toString() method for any type, so that during debugging those types will use your custom toString() renderers. Is similar functionality available or achievable in PyCharm? I tried this approach: # for lxml.html lxml.html.HtmlElement.__str__ = lxml.html.etree.tostring This gives the expected result for lxml.html, but it feels like an ugly workaround, and I would like to find a way to do it that does not require monkey-patching external libraries. The downside of this approach is that it doesn't work for example with lxml.etree.Element because setting lxml.etree.Element.__str__ = lxml.etree.tostring has no effect, as it delegates to lxml.etree._Element which is C native module with a read-only __str__.
type: Question

http://stackoverflow.com/q/50973726
score: 2
has comment: http://stackoverflow.com/comment/88943928
type: Question
has comment: http://stackoverflow.com/comment/88989839
downvote count: 0
has body: This might be silly question but I want to still get a clear answer. I have cleaned my data by treating missing values, changing factors to numeric data and then, saved my data to excel(.csv). Later I read this data and found, categorical fields value are converted to float data type. I used below code to convert it back to 'object' data type, however, it didn't work. data.info() categorical_feature = ['NAME_CONTRACT_TYPE', 'CODE_GENDER', 'FLAG_OWN_CAR', 'FLAG_OWN_REALTY', 'NAME_TYPE_SUITE', 'NAME_INCOME_TYPE', 'NAME_EDUCATION_TYPE', 'NAME_FAMILY_STATUS', 'NAME_HOUSING_TYPE', 'OCCUPATION_TYPE', 'WEEKDAY_APPR_PROCESS_START', 'ORGANIZATION_TYPE', 'FONDKAPREMONT_MODE', 'HOUSETYPE_MODE', 'WALLSMATERIAL_MODE', 'EMERGENCYSTATE_MODE'] data[categorical_features] = data[categorical_features].astype(object) data.info() Result : &lt;class 'pandas.core.frame.DataFrame'&gt; RangeIndex: 307511 entries, 0 to 307510 Columns: 122 entries, SK_ID_CURR to AMT_REQ_CREDIT_BUREAU_YEAR dtypes: float64(121), int64(1) memory usage: 286.2 MB &lt;class 'pandas.core.frame.DataFrame'&gt; RangeIndex: 307511 entries, 0 to 307510 Columns: 122 entries, SK_ID_CURR to AMT_REQ_CREDIT_BUREAU_YEAR dtypes: float64(121), int64(1) memory usage: 286.2 MB
tagged with: pandas
has comment: http://stackoverflow.com/comment/88989851
has title: Column is not type cast to object
favorite count: 0
answer count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/110468344
type: Comment
comment on: http://stackoverflow.com/a/50872864
score: 1
type: AnswerComment
has text: @Jivan Actually, mostly we don't have a choice. On one computer, we can use shared memory. But mostly we are on different machines. We have to pay for that cost.

http://stackoverflow.com/q/50990679
has answer: http://stackoverflow.com/a/50993003
accepted answer: http://stackoverflow.com/a/50993003
tagged with: python
score: 2
downvote count: 0
has body: I want to control my python script output with values in a csv: I select a Category and some parameters like that: csv1 or like that csv2 In my python-script I got the Values of each parameter in a list that looks like that: A_Names = ("Anton", "Berta", "Charlie") Ages = ("32","18","23") Nicknames = ("Agent A", "Agent B", None) Birthdays = ("03.03.1986", "02.02.2000", "01.01.1995") IDs = (100, 200, 300) The idea now is to have a script that will combine these information so the output for csv1 would be: Anton A_Name: Anton Age: 32 Nickname: Agent A Birthday: 03.03.1986 Berta A_Name: Berta Age: 18 Nickname: Agent B Birthday: 02.02.2000 Charlie A_Name: Charlie Age: 23 Nickname: No Nickname yet Birthday: 01.01.1995 and the output for the csv2 would be: Anton Nickname: Agent A A_Name: Anton ID: 100 Berta Nickname: Agent B A_Name: Berta ID: 200 Charlie Nickname: No Nickname yet A_Name: Charlie ID: 300 and of course it should also work both together in a csv3 like that, and the same outputs just after another. So the first idea was just to code my output like that: #let's assume i got the columns from the csv in lists like that: Categories = ("Agents", "Agents") Parameter1 = ("A_Name", "Nickname") Parameter2 = ("Age", "A_Name") Parameter3 = ("Nickname", "ID") Parameter4 = ("Birthday") #then the most unflexible code would look like that: def Show_Values(): for n in range (0,len(A_Names)): print A_Names[n] print " %s: %s" % (Parameter1[0], A_Names[n]) print " %s: %s" % (Parameter2[0], Ages[n]) print " %s: %s" % (Parameter3[0], Nicknames[n]) print " %s: %s" % (Parameter4[0], Birthdays[n]) for n in range (0,len(A_Names)): print A_Names[n] print " %s: %s" % (Parameter1[1], Nicknames[n]) print " %s: %s" % (Parameter2[1], A_Names[n]) print " %s: %s" % (Parameter3[1], IDs[n]) Show_Values() So this is very stupid code and I repeat myself there over and over and always need to add the correct value for the 2nd %s. My question now is how can I create a smarter, shorter Code, that kn…
has comment: http://stackoverflow.com/comment/88976411
type: Question
type: AnsweredQuestion
has title: Controlling python script with CSV
has comment: http://stackoverflow.com/comment/88978565
has comment: http://stackoverflow.com/comment/88976266
upvote count: 2
has comment: http://stackoverflow.com/comment/88976104
answer count: 1
tagged with: variables
favorite count: 0
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/88976026

http://stackoverflow.com/a/50994909
score: 2
upvote count: 2
has body: If you are using sklearn's t-SNE, then your assumption is correct. The ordering of the inputs match the ordering of the outputs. So if you do y=TSNE(n_components=n).fit_transform(x) then y and x will be in the same order so y[7] will be the embedding of x[7]. You can trust scikit-learn that this will be the case.
downvote count: 0
answers question: http://stackoverflow.com/q/50993934
type: Answer

http://stackoverflow.com/comment/88935811
type: Comment
comment on: http://stackoverflow.com/a/50969083
has text: the file with the data you mentioned. I've changed the script to accept the file via commandline.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/88986879
has text: @metatoaster I'm still not seeing how this is different from guessing a csrf token of a logged in user..? If we assume that it's true, do you have any solution for the second part of my question? As it is, the end user is experiencing the site as flaky since for them they randomly have to refresh the page before they can submit a form.
type: Comment
comment on: http://stackoverflow.com/a/50988599
type: AnswerComment
score: 0

http://stackoverflow.com/comment/88797209
has text: The color and shape is defined by `'r','^'` `'b','s'` and `'g','o'` and you can find more colors in matplotlib (r is red, b is blue, g is green). As for changing to non random numbers... you can always do `np.array([1., 2., 3., 4., 5.])` or any other numbers you want. You can also load a text file...
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/50897746

http://stackoverflow.com/comment/88976183
score: 0
type: AnswerComment
type: Comment
has text: Thank uu soooo much
comment on: http://stackoverflow.com/a/50989566

http://stackoverflow.com/comment/88800137
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50899541
type: Comment
has text: added *errState*, that will make it show the msg only once

http://stackoverflow.com/comment/88928731
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50965262
has text: are you using the `pandas` library?
type: Comment

http://stackoverflow.com/a/50975969
type: AcceptedAnswer
score: 60
type: Answer
downvote count: 0
upvote count: 60
accepted answer of: http://stackoverflow.com/q/50971123
has body: In response your comment question, let's compare 2 ways of creating an array First make an array from a list of arrays (all same length): In [302]: arr = np.array([np.arange(3), np.arange(1,4), np.arange(10,13)]) In [303]: arr Out[303]: array([[ 0, 1, 2], [ 1, 2, 3], [10, 11, 12]]) The result is a 2d array of numbers. If instead we make an object dtype array, and fill it with arrays: In [304]: arr = np.empty(3,object) In [305]: arr[:] = [np.arange(3), np.arange(1,4), np.arange(10,13)] In [306]: arr Out[306]: array([array([0, 1, 2]), array([1, 2, 3]), array([10, 11, 12])], dtype=object) Notice that this display is like yours. This is, by design a 1d array. Like a list it contains pointers to arrays elsewhere in memory. Notice that it requires an extra construction step. The default behavior of np.array is to create a multidimensional array where it can. It takes extra effort to get around that. Likewise it takes some extra effort to undo that - to create the 2d numeric array. Simply calling np.array on it does not change the structure. In [307]: np.array(arr) Out[307]: array([array([0, 1, 2]), array([1, 2, 3]), array([10, 11, 12])], dtype=object) stack does change it to 2d. stack treats it as a list of arrays, which it joins on a new axis. In [308]: np.stack(arr) Out[308]: array([[ 0, 1, 2], [ 1, 2, 3], [10, 11, 12]])
answers question: http://stackoverflow.com/q/50971123

asynchronous
tags question: http://stackoverflow.com/q/50975543
tags question: http://stackoverflow.com/q/50948859
tags question: http://stackoverflow.com/q/51005837
type: Tag
tag name: asynchronous
tags question: http://stackoverflow.com/q/50938545
tags question: http://stackoverflow.com/q/50957341
tags question: http://stackoverflow.com/q/50875213
tags question: http://stackoverflow.com/q/50975012
tags question: http://stackoverflow.com/q/50969641
tags question: http://stackoverflow.com/q/50910945
tags question: http://stackoverflow.com/q/50945329
tags question: http://stackoverflow.com/q/50971042

http://stackoverflow.com/comment/88975656
type: Comment
has text: @HristoBuyukliev I like your systematic approach to achieve an O(1) target operation cost for the search for a median value -- **would you mind to also add to graph also values measured for the native `numpy` `.median()` method**, called on a ready-to-go `numpy.array` of pre-generated numbers, i.e. **without skewing readings** with also including into measured section all TimeDOMAIN costs of building a respective list-alike representation and the iterator loop. Also would be reasonable to benchmark only on the out of in-cache list/array sizes ... 1E7, 1E8 ... right? **That is fair, isn't it?**
type: QuestionComment
comment on: http://stackoverflow.com/q/50899486
score: 0

http://stackoverflow.com/comment/88920306
has text: @coldspeed Also, it's not a duplicate of https://stackoverflow.com/questions/22219004/grouping-rows-in-list-in-pandas-groupby...I want to get a list of lists, the other is looking for a dataframe. Thanks for the answer though.
type: Comment
comment on: http://stackoverflow.com/a/50961402
score: 0
type: AnswerComment

http://stackoverflow.com/q/50895461
type: Question
has comment: http://stackoverflow.com/comment/88806257
has comment: http://stackoverflow.com/comment/88791904
has comment: http://stackoverflow.com/comment/88791518
downvote count: 0
has title: Retrain tensorflow models(resnet and inceptionV3) from scratch on custom dataset
favorite count: 0
type: UnansweredQuestion
has body: I have training images in JPEG format as follows: /train_dir/class1/img1 /train_dir/class1/img2 ... /train_dir/class2/img1 /train_dir/class2/img2 ... and so on for 10 classes with each class having around 1000 images. In need to retrain(not fine tune) resnet, inceptionV3 models from scratch on this dataset. How can i do so? I tried using the methods mentioned here https://github.com/tensorflow/models/tree/master/research/slim#Training but these only seem to work for predefined datasets like imagenet/MNIST/flowers/CIFAR. Training a model from scratch. We provide an easy way to train a model from scratch using any TF-Slim dataset. The following example demonstrates how to train Inception V3 using the default parameters on the ImageNet dataset. ```shell DATASET_DIR=/tmp/imagenet TRAIN_DIR=/tmp/train_logs python train_image_classifier.py \ --train_dir=${TRAIN_DIR} \ --dataset_name=imagenet \ --dataset_split_name=train \ --dataset_dir=${DATASET_DIR} \ --model_name=inception_v3 ``` I edited the code provided above in hope to train it on my own images as follows - $ DATASET_DIR=/home/harshit/Music/malignant_or_benign/train/ $ TRAIN_DIR=/home/harshit/Music/malignant_or_benign/out/ $ python train_image_classifier.py --train_dir=${TRAIN_DIR} --dataset_name=mal_ben --dataset_split_name=train --dataset_dir=${DATASET_DIR} --model_name=inception_v3 /usr/local/lib/python2.7/dist-packages/h5py/__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from float to np.floating is deprecated. In future, it will be treated as np.float64 == np.dtype(float).type. from ._conv import register_converters as _register_converters WARNING:tensorflow:From train_image_classifier.py:398: create_global_step (from tensorflow.contrib.framework.python.ops.variables) is deprecated and will be removed in a future version. Instructions for updating: Please switch to tf.train.create_global_step Traceback (most recent call last): File "train_image_classifier.py", line 571, in &lt;mod…
tagged with: python
tagged with: computer-vision
tagged with: artificial-intelligence
has comment: http://stackoverflow.com/comment/88793221
tagged with: conv-neural-network
answer count: 0
score: 1
upvote count: 1
tagged with: tensorflow

http://stackoverflow.com/comment/88921550
type: Comment
score: 0
has text: Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question.
type: QuestionComment
comment on: http://stackoverflow.com/q/50962410

http://stackoverflow.com/comment/88725147
type: AnswerComment
comment on: http://stackoverflow.com/a/50860752
score: 0
type: Comment
has text: @Maruf Use [`numpy.average`](https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.average.html): `values = np.arange(len(freq_array)); mu = np.average(values, weights=freq array)`. The std dev is a bit harder: `sigma = np.sqrt(np.average((values-mu)**2, weights=freq array))`.

http://stackoverflow.com/comment/88821025
comment on: http://stackoverflow.com/q/50910480
type: QuestionComment
score: 1
has text: If you update `var_1` or `current_var`, one update will not change the other, no
type: Comment

http://stackoverflow.com/q/50957772
has body: I have an SVG (Xml) file from which I want to select some elements. For the sake of a MCRE I have cut down the file to this &lt;svg &gt; &lt;!-- xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" --&gt; &lt;g&gt; &lt;path style="fill:#19518b;fill-opacity:1;fill-rule:nonzero;stroke:none" /&gt; &lt;path style="fill:#a80c3d;fill-opacity:1;fill-rule:nonzero;stroke:none" /&gt; &lt;path style="fill:#a98b6e;fill-opacity:1;fill-rule:nonzero;stroke:none" /&gt; &lt;/g&gt; &lt;/svg&gt; Where some optional namespace attributes for the root element are located in a comment so they can be inserted back in to replicate the real scenario (where SVG root element is fulsomely attributed). From the following Xml (SVG) I want to select the elements styled with fill:#19518b;fill-opacity:1;fill-rule:nonzero;stroke:none. There is one of match. The following code works on the given Xml. from lxml import etree sFileName = 'C:/Users/Simon/Downloads/pdf_skunkworks/inflation-report-may-2018-page6 - Copy.svg' tree = etree.Parse(sFileName) svgNamespace = "xmlns:svg='http://www.w3.org/2000/svg'" #xpath = r"//svg:path[@style='fill:#19518b;fill-opacity:1;fill-rule:nonzero;stroke:none']" xpath = r"//path[@style='fill:#19518b;fill-opacity:1;fill-rule:nonzero;stroke:none']" Print (XPath) #bluePaths = tree.xpath(xpath,namespaces={ 'svg': svgNamespace }) bluePaths = tree.XPath(XPath) print (bluePaths[0]) but it works on the given Xml because it does not have the namespace attributes that one finds in a real SVG file. Once I reinsert the namespace attributes thus &lt;svg xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" &gt; then the Python code (as given fails). I know I need to use namespaces and you can see my attempts commented out in the Python but they don't work. One of the namespace prefix is an empty string and could not be passed to the namespace dictionary. Anyway, in the morning I will write could to clone the SVG file and remove the attributes f…
type: Question
upvote count: 2
accepted answer: http://stackoverflow.com/a/50958274
answer count: 1
has answer: http://stackoverflow.com/a/50958274
tagged with: lxml
tagged with: python
favorite count: 0
tagged with: http://stackoverflow.com/tag/xml
tagged with: xml-namespaces
tagged with: xpath
has comment: http://stackoverflow.com/comment/88913852
has title: Python XPath lxml could not read SVG path element due to empty namespace?
downvote count: 0
type: AnsweredQuestion
score: 2

http://stackoverflow.com/comment/88865560
score: 0
type: QuestionComment
has text: MySQL errors typically include information about where in the query MySQL had a problem; including that in your question can help diagnose the issue. (The error number itself can often be the least helpful part of the error message.)
type: Comment
comment on: http://stackoverflow.com/q/50933434

http://stackoverflow.com/q/50868186
has title: Append DataFrame inside Function
answer count: 2
tagged with: pandas
tagged with: function
downvote count: 0
has answer: http://stackoverflow.com/a/50879536
favorite count: 0
has comment: http://stackoverflow.com/comment/88738458
linked to: http://stackoverflow.com/q/38895768
accepted answer: http://stackoverflow.com/a/50879536
tagged with: python
possible better answer: http://stackoverflow.com/a/50868214
has answer: http://stackoverflow.com/a/50868214
type: AnsweredQuestion
upvote count: 3
has comment: http://stackoverflow.com/comment/88738494
has comment: http://stackoverflow.com/comment/88738438
has body: I have a function test that takes a DataFrame and appends data to it. I want the global variable placed into the function to be changed. I have the script below: import pandas as pd global dff def test(df): df = df.append({'asdf':1, 'sdf':2}, ignore_index=True) return(df) dff = pd.DataFrame() test(dff) After this, dff remains empty; it was not edited. However, if you do this: import pandas as pd def test(df): df['asdf'] = [1,2,3] return(df) dff = pd.DataFrame() test(dff) dff will have [1,2,3] under the column 'asfd'. Notice that I didn't even have to declare the variable as global. Why is this happening? I actually would like to know, because the second I think I understand variable workspaces, I'm proven wrong and I'm getting sick and tired of constantly running into this BS* I know the solution to the problem is: import pandas as pd def test(df): df = df.append({'asdf':1, 'sdf':2}, ignore_index=True) return(df) dff = pd.DataFrame() dff = test(dff) but I'm really just trying to figure out why the initial method isn't working, especially in light of the second script I've shown. *obviously it's not complete BS, but I can't understand it after 3 years of casual programming
type: Question
score: 3
linked to: http://stackoverflow.com/q/4693120
has comment: http://stackoverflow.com/comment/88738422
has comment: http://stackoverflow.com/comment/88738364
has comment: http://stackoverflow.com/comment/88738399
has comment: http://stackoverflow.com/comment/88738481
tagged with: dataframe

http://stackoverflow.com/comment/88785690
comment on: http://stackoverflow.com/a/50889604
has text: I will answer one by one:
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/88805956
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50902909
has text: I dont want to change the topics generated, just want to change to (0, '0.068*"murder" + 0.043*"crime" + 0.021*"shooting"') , the '0' value to some manually assigned name

http://stackoverflow.com/a/50974150
upvote count: 1
answers question: http://stackoverflow.com/q/50974075
type: Answer
has body: The user_input variable gets passed to the factorial() function with this line factorial_of_the_number = factorial(user_input) Then the the math is handled inside the factorial() function and returned to be stored in the factorial_of_the_number variable.
downvote count: 0
score: 1

http://stackoverflow.com/q/50871390
has answer: http://stackoverflow.com/a/50871622
score: 0
answer count: 3
linked to: http://stackoverflow.com/q/40749377
has comment: http://stackoverflow.com/comment/88744432
has answer: http://stackoverflow.com/a/50871532
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88744312
upvote count: 3
downvote count: 3
has title: Why doesn't the loop work as it be programmed?
type: Question
has answer: http://stackoverflow.com/a/50871846
has body: While I tried to execute the following code, I faced some problem in loop iterations and couldn't figure out what's the problem might be. def string_splosion(s): """Takes a non-empty string s like "Code" and returns a string like "CCoCodCode" """ for i in range(len(s)): return s[i] * (i+1) print(string_splosion('Code'))
has comment: http://stackoverflow.com/comment/88744327
has comment: http://stackoverflow.com/comment/88745281

http://stackoverflow.com/q/50912994
tagged with: tensorflow
type: Question
type: AnsweredQuestion
tagged with: conv-neural-network
has body: With the help of tf.layers module I created a simple CNN to train it on MNIST database. First we load the data: import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("/tmp/data/", one_hot=True) And then set some basic parameters, build and train the model: learning_rate = 0.01 training_epochs = 10 batch_size = 100 x = tf.placeholder(tf.float32, [None, 784], name='InputData') y = tf.placeholder(tf.float32, [None, 10], name='LabelData') with tf.name_scope('Model'): input_layer = tf.reshape(x, [-1, 28, 28, 1], name='InputReshaped') conv1 = tf.layers.conv2d(inputs=input_layer, filters=32, kernel_size=[4, 4], padding="same", activation=tf.nn.relu) pool1 = tf.layers.max_pooling2d(inputs=conv1, pool_size=[2, 2], strides=2) dropout1 = tf.layers.dropout(inputs=pool1, rate=0.25) conv2 = tf.layers.conv2d(inputs=dropout1, filters=32, kernel_size=[4, 4], padding="same", activation=tf.nn.relu) pool2 = tf.layers.max_pooling2d(inputs=conv2, pool_size=[2, 2], strides=2) dropout2 = tf.layers.dropout(inputs=pool2, rate=0.25) pool2_flat = tf.reshape(dropout2, [-1, 7 * 7 * 32]) dense = tf.layers.dense(inputs=pool2_flat, units=256, activation=tf.nn.relu) dropout3 = tf.layers.dropout(inputs=dense, rate=0.5) pred = tf.layers.dense(inputs=dropout3, units=10) with tf.name_scope('Loss'): loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=pred, labels=y)) with tf.name_scope('SGD'): optimizer = tf.train.GradientDescentOptimizer(learning_rate) train_step = optimizer.minimize(loss) with tf.name_scope('Accuracy'): acc = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1)) acc = tf.reduce_mean(tf.cast(acc, tf.float32)) init = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init) for epoch in range(training_epochs): avg_cost = 0. avg_acc = 0. total_batch = int(mnist.train.num_examples/batch_size) for i in range(total_batch): batch_xs, batch_ys = mnist.train.next_batch(batch_size) _, c, ac = sess.run([t…
answer count: 1
tagged with: neural-network
has title: Poor performance of CNN after rewriting it from tf.layers to raw tf
has answer: http://stackoverflow.com/a/50913586
score: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/50913586
tagged with: machine-learning

http://stackoverflow.com/comment/102710266
score: 0
type: Comment
type: QuestionComment
has text: @ReKx not sure if you still care about this but what I did was store the lists of options in a dictionary then stored the keys to the options in the data frame.
comment on: http://stackoverflow.com/q/50917384

http://stackoverflow.com/a/50949939
has body: Probably you want to use EXISTS: subq = Process.select().where( (Process.name == 'proc') &amp; (Process.computer == Computer.id)) query = Computer.select().where(~fn.EXISTS(subq)) Note: it's a best practice not to use plural form for model classes. Similarly, not to include "xxx_id" in your field names.
answers question: http://stackoverflow.com/q/50938499
downvote count: 0
has comment: http://stackoverflow.com/comment/89211625
upvote count: 2
type: Answer
score: 2

http://stackoverflow.com/comment/88833813
type: Comment
comment on: http://stackoverflow.com/a/50916363
has text: Well, you still have to wait to the far-off future date of 27 June 2018 before you can use `dataclass` without installing something off PyPI… Anyway, as I said, I think you've explained enough, and I don't want to push you to make your answers even more overly verbose than mine usually are. :)
score: 0
type: AnswerComment

http://stackoverflow.com/a/50877694
accepted answer of: http://stackoverflow.com/q/50877387
has comment: http://stackoverflow.com/comment/88816232
score: 4
has comment: http://stackoverflow.com/comment/88818119
upvote count: 4
has body: A LoggingAdapter is a separate object, it does not replace the result of logging.getLogger() calls. You'll need to store it somewhere that it can be shared between different modules. You could use a separate module that everything else in your project imports from, for example. I'll detail below how to handle this, but there is also an alternative that doesn't involve adapters at all, and instead uses a filter which is attached to the handler you created, letting you avoid having to deal with adapters altogether. See further down. I'd separate out configuration and log object handling too; have the main module call the 'setup' function to configure the handlers and log levels, and set up the adapter in the module for others to import: log.py: import logging import socket def setup_logging(): """Adds a configured stream handler to the root logger""" syslog = logging.StreamHandler() formatter = logging.Formatter( '{"label":"%(name)s", "level":"%(levelname)s",' ' "hostname":"%(hostname)s", "logEntry": %(message)s,' ' "timestamp", "%(asctime)s"}') syslog.setFormatter(formatter) logger = logging.getLogger() logger.addHandler(syslog) logger.setLevel(logging.DEBUG) def host_log_adapter(logger): hostname = {"hostname": socket.gethostname()} return logging.LoggerAdapter(logger, hostname) logger = host_log_adapter(logging.getLogger()) Then in main do: import log import test log.setup_logging() def entry_point(): log.logger.debug("entry_point") test.test_function() entry_point() and in test: from log import logger def test_function(): logger.debug("test_function") Alternatively, rather than use an adapter, you could add information to log records by (ab)using a filter: class HostnameInjectingFilter(logging.Filter): def __init__(self): self.hostname = socket.gethostname()} def filter(self, record): record.hostname = self.hostname return True This adds the extra field directly on the record object and always returns True. Then just add this filter to the handler that needs to ha…
has comment: http://stackoverflow.com/comment/88822160
has comment: http://stackoverflow.com/comment/88819629
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88817889
has comment: http://stackoverflow.com/comment/88818003
has comment: http://stackoverflow.com/comment/88815255
answers question: http://stackoverflow.com/q/50877387
type: Answer

http://stackoverflow.com/a/50978563
answers question: http://stackoverflow.com/q/50978492
has body: That is beacuse there is no 1986-01-01 00:00:00 After 1985-12-31 11:59:59 PM, Clocks were jumped to 1986-01-01 12:15:00 AM, so 1986-01-01 00:00:00 just being skip. which means the clock had been set forward 15mins
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88953005
type: Answer
has comment: http://stackoverflow.com/comment/88952991
accepted answer of: http://stackoverflow.com/q/50978492
downvote count: 0
score: 1

http://stackoverflow.com/a/50898278
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50894672
has body: For clicking on Get Likes button you can use this code : get_likes = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.ID, "get_likes_button"))) After that if input type changed from type='hidden' , you can interact with input field as : input_field = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.NAME, "id"))) It's quite strange to see HTML like this : &lt;input name="id"&gt; By the way, hope this will help.

http://stackoverflow.com/a/51000544
score: 0
has body: Here's a simple way to create platforms: I define a list of rects (just tuples with four elements in this case), iterate over it to create the platform instances and add them to the sprite groups. import pygame as pg pg.init() # Better create or load the images/surfaces before the game # starts because that's more efficient. PLATFORM_IMAGE = pg.Surface((50, 50)) PLATFORM_IMAGE.fill(pg.Color('dodgerblue1')) class Platform(pg.sprite.Sprite): def __init__(self, x, y, image): super().__init__() self.image = image self.rect = self.image.get_rect(topleft=(x, y)) def main(): screen = pg.display.set_mode((640, 480)) clock = pg.time.Clock() all_sprites = pg.sprite.Group() platforms = pg.sprite.Group() coords = [(100, 200), (150, 200), (350, 100)] for x, y in coords: # Pass the x- and y-coords and the surface. platform = Platform(x, y, PLATFORM_IMAGE) # Add the sprite to the corresponding groups. all_sprites.add(platform) platforms.add(platform) done = False while not done: for event in pg.event.get(): if event.type == pg.QUIT: done = True all_sprites.update() screen.fill((30, 30, 30)) all_sprites.draw(screen) pg.display.flip() clock.tick(30) if __name__ == '__main__': main() pg.quit() If you want to use a list of strings as your level, you can use two for loops and the enumerate function: level = [ "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB", "B B", "B B", "B BBBB B", "B B", "B BBBB B", "B B", "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB", ] all_sprites = pg.sprite.Group() platforms = pg.sprite.Group() width = PLATFORM_IMAGE.get_width() for y, row in enumerate(level): for x, item in enumerate(row): if item == 'B': platform = Platform(x*width, y*width, PLATFORM_IMAGE) all_sprites.add(platform) platforms.add(platform)
type: Answer
answers question: http://stackoverflow.com/q/51000165

http://stackoverflow.com/comment/88745686
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50871572
has text: @@Julien - Thanks for your answer, I have updated my article question. What should I do if I want to find a logical index?
type: AnswerComment

http://stackoverflow.com/q/50967990
has answer: http://stackoverflow.com/a/50968084
has answer: http://stackoverflow.com/a/50968051
accepted answer: http://stackoverflow.com/a/50968084
has body: I'm still starting with python and got stuck with this error and have no idea what to do, I use spyder : File "C:\Users\Win8.1\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2963, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "&lt;ipython-input-26-d3792eadd9d7&gt;", line 1, in &lt;module&gt; runfile('C:/Users/Win8.1/Documents/Python Scripts/ipnd-starter-code-master/stage_3/lesson_3.3_classes/c_profanity_editor/check_profanity.py', wdir='C:/Users/Win8.1/Documents/Python Scripts/ipnd-starter-code-master/stage_3/lesson_3.3_classes/c_profanity_editor') File "C:\Users\Win8.1\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 705, in runfile execfile(filename, namespace) File "C:\Users\Win8.1\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "C:/Users/Win8.1/Documents/Python Scripts/ipnd-starter-code-master/stage_3/lesson_3.3_classes/c_profanity_editor/check_profanity.py", line 18 quotes = open("C:\Users\Win8.1\Documents\Python Scripts\ipnd-starter-code-master\stage_3\lesson_3.3_classes\c_profanity_editor\movies_quotes.txt") ^ SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape code: import urllib def read_text(): quotes = open("C:\Users\Win8.1\Documents\Python Scripts\ipnd- starter-code- master\stage_3\lesson_3.3_classes\c_profanity_editor\movies_quotes.txt") contents_of_file = quotes.read() print(contents_of_file) read_text() mind the indentation and my ignorance..
tagged with: urllib
score: 0
answer count: 2
has title: python error in opening file (codec can't decode bytes in position 2-3), i use spyder
tagged with: spyder
tagged with: python
type: AnsweredQuestion
type: Question
possible better answer: http://stackoverflow.com/a/50968051

http://stackoverflow.com/comment/88790382
has text: thanks, this part is solved. Now how to get the current selected in combobox and display the text file in textbox tb4, can you help me in getting the function for diplay and use it in button pbtn6
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50895154

http://stackoverflow.com/comment/88900709
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50951335
score: 1
has text: @PatrickHaugh it's string interpolation, `namedtuple`s are `exec`uted strings

http://stackoverflow.com/q/50962903
has comment: http://stackoverflow.com/comment/88923847
tagged with: django
type: Question
tagged with: escaping
has comment: http://stackoverflow.com/comment/88922674
has body: I am very new to Django and I've encountered the following problem. I have a small script to give me a random quote from my list @register.simple_tag(name='quote') def random_quote(): quote, author = random.choice(quotes_list) return """%s &lt;br&gt; %s""" %(quote, author) And I call the selected quote in my template as: {% load quotes %}{% quote %} which is working just fine, however I'm not able to pass the HTML formatting together with my quote. How can I escape HTML in my quote to get e.g. a single line break between quote and author? Thank you!
has comment: http://stackoverflow.com/comment/88926845
score: 0
tagged with: http://stackoverflow.com/tag/html
tagged with: python
tagged with: django-templates
answer count: 0
has title: Django keep HTML formatting with passed string
type: UnansweredQuestion

http://stackoverflow.com/a/50962326
type: Answer
has body: you are pretty close. df.loc[(df.max_speed == 1) &amp; (df.shield == 2), "new"] = 10 For further reading, see here.
has comment: http://stackoverflow.com/comment/88921490
answers question: http://stackoverflow.com/q/50962280
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/88921448
upvote count: 2
has comment: http://stackoverflow.com/comment/88921494

http://stackoverflow.com/comment/88848447
has text: I'm afraid this doesn't answer the question, which *requires* a compromise. A `datetime` object can't have day "removed".
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50924031

http://stackoverflow.com/q/50963852
has answer: http://stackoverflow.com/a/50966793
linked to: http://stackoverflow.com/q/16585952
tagged with: python
accepted answer: http://stackoverflow.com/a/50966793
type: AnsweredQuestion
score: 3
linked to: http://stackoverflow.com/q/41200127
has title: Remove all images from docx files
has answer: http://stackoverflow.com/a/50964189
possible better answer: http://stackoverflow.com/a/50964774
downvote count: 1
has answer: http://stackoverflow.com/a/50964774
type: Question
upvote count: 4
has body: I've searched the documentation for python-docx and other packages, as well as stack-overflow, but could not find how to remove all images from docx files with python. My exact use-case: I need to convert hundreds of word documents to "draft" format to be viewed by clients. Those drafts should be identical the original documents but all the images must be deleted / redacted from them. Sorry for not including an example of things I tried, what I have tried is hours of research that didn't give any info. I found this question on how to extract images from word files, but that doesn't delete them from the actual document: Extract pictures from Word and Excel with Python From there and other sources I've found out that docx files could be read as simple zip files, I don't know if that means that it's possible to "re-zip" without the images without affecting the integrity of the docx file (edit: simply deleting the images works, but prevents python-docx from continuing to work with this file because of missing references to images), but thought this might be a path to a solution. Any ideas?
tagged with: python-docx
answer count: 3
linked to: http://stackoverflow.com/q/44435595
favorite count: 0
tagged with: http://stackoverflow.com/tag/docx

http://stackoverflow.com/comment/88765754
type: QuestionComment
comment on: http://stackoverflow.com/q/50881693
has text: I bet because the interpreter can "see" and analyze _both_ statements at the same time, Python is able to do some optimizations to eliminate the variables altogether and do stuff like `12345 is 12345`.
score: 0
type: Comment

http://stackoverflow.com/q/50978894
score: 1
has comment: http://stackoverflow.com/comment/88953662
type: Question
has comment: http://stackoverflow.com/comment/88978428
tagged with: scikit-learn
tagged with: keras
has answer: http://stackoverflow.com/a/50984097
accepted answer: http://stackoverflow.com/a/50984097
has body: So I was following some of the examples provided on this post: How to one-hot-encode sentences at the character level? And they seem to hot encoding at character level. However, I am not able to figure out to hot encode at character level for a string with ints in it. for example: "hello" # h=7, e=4 l=11 o=14 would be: [[0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] I was able to achieve that with the help of the post I mentioned above. But would someone be able to help me hot encoding the following: "Hello0311" Any help and guidance is highly apprecaited
downvote count: 0
answer count: 1
favorite count: 0
has title: One hot Encoding at character Level
linked to: http://stackoverflow.com/q/43618245
upvote count: 1
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/50857160
score: 0
has answer: http://stackoverflow.com/a/55481114
has title: Install MiniConda and Extra Packages
linked to: http://stackoverflow.com/q/27904532
answer count: 1
type: UnansweredQuestion
tagged with: package
tagged with: windows
has comment: http://stackoverflow.com/comment/97690832
tagged with: python
tagged with: installation
tagged with: miniconda
type: Question
has body: I need to distribute a python 2.7 windows installation with the openpyxl module in a corporate environment with no admin or live access to the repository. There are a number of openpyxl prerequisites. Installing miniconda normally involves the user downloading the correct installation for their operating system with the installation managing correct module installation. I'd prefer not to hard-code versions because they will become outdated some time after they are downloaded but I can't see any way around it. I am looking to include the following batch file in a zip file (say like self-extracting archive). Is there a smarter way to assemble the software and distribute it? @echo off rem Manual Download and Installing Anaconda Python Packages rem could change to use http://www.coreftp.com rem eg for miniconda2 with Python 2.7 at 14/06/2018 rem Download MiniConda rem https://repo.continuum.io/miniconda/Miniconda2-latest-Windows-x86_64.exe rem Download coda packages from Anaconda repositories rem https://repo.continuum.io/pkgs/main/win-64/et_xmlfile-1.0.1-py27h1de5d23_0.tar.bz2 rem https://repo.continuum.io/pkgs/main/win-64/jdcal-1.3-py27h8c72977_0.tar.bz2 rem https://repo.continuum.io/pkgs/main/win-64/openpyxl-2.4.10-py27_0.tar.bz2 rem set CondaInstallDir=%UserProfile%\AppData\Local\Continuum\miniconda2 echo Installing MiniConda with extra packages to %CondaInstallDir% echo ^&lt;Ctrl^&gt;C to cancel OR pause echo Installing MiniConda to %CondaInstallDir% echo Please wait ... cd %UserProfile% %~dp0Miniconda2-latest-Windows-x86_64 /AddToPath=0 /S /D=%CondaInstallDir% cd %CondaInstallDir%\Scripts %HomeDrive%conda install --offline %~dp0jdcal-1.4-py27_0.tar.bz2 %HomeDrive%conda install --offline %~dp0et_xmlfile-1.0.1-py27h1de5d23_0.tar.bz2 %HomeDrive%conda install --offline %~dp0openpyxl-2.4.10-py27_0.tar.bz2 echo done. pause

http://stackoverflow.com/q/50862609
tagged with: sqlalchemy
upvote count: 15
has title: Creating Hypertables through SQL Alchemy
downvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50879452
favorite count: 0
linked to: http://stackoverflow.com/q/9839746
has answer: http://stackoverflow.com/a/67028942
score: 15
type: Question
has body: Our current project relies heavily on SQL Alchemy for table creation/data insertion. We would like to switch to timescaledb's hypertables, but it seems the recommended way to create hypertables is by executing a create_hypertable command. I need to be able to dynamically create tables, and so manually doing this for every table created is not really an option. One way of handling the conversion is to run a python script sending psycopg2 commands to convert all newly-created tables into hypertables, but this seems a little clumsy. Does timescaledb offer any integration with SQL Alchemy with regards to creating hypertables?
answer count: 2
tagged with: python
tagged with: timescaledb

http://stackoverflow.com/a/50864765
downvote count: 0
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50862920
type: Answer
answers question: http://stackoverflow.com/q/50862920
score: 2
has body: As pointed out by ImportanceOfBeingErnest in the comments, the bins will be spread out among the range of your data unless you specifically set the range parameter when plotting. So in my case, for some lines the range was 0-0.18, in other places 0-0.98, thus causing the variation in bar width. The solution is to amend the histogram line to: ax1.hist(graphed_data, bins=50, range=(0,1), label=['both', 'selective', 'clearcut']) using the range parameter, and with the rwidth parameter being unrelated and optional.
type: AcceptedAnswer

http://stackoverflow.com/q/50979354
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88954687
tagged with: python
has comment: http://stackoverflow.com/comment/88967650
score: 2
has answer: http://stackoverflow.com/a/69964914
upvote count: 3
has answer: http://stackoverflow.com/a/50979528
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88954681
answer count: 2
has title: flask input date parsing
tagged with: flask
has body: I have a html form. But I am in trouble to get the date. I try to get the day/month/year. Look the html: data da apreensão and now the flask code: @app.route('/cars/novo', methods=['GET','POST']) def addCarro(): if request.method == 'POST': marca = request.form['marca'] modelo = request.form['modelo'] placa = request.form['placa'] motivo = request.form['motivo'] situacao = request.form['situacao'] # HERE I GOT THE PROBLEM #data_apreensao = datetime.datetime.strptime(request.form['data_apreensao'], '%d, %m, %Y') data_apreensao = datetime.strptime(request.form['data_apreensao'], '%d, %m, %Y') print (data_apreensao) carros.append(Apreensao(marca,modelo, placa, motivo, situacao)) return redirect('/cars') return render_template('apreensaoForm.html', titulo='Nova Apreensao') error: ValueError ValueError: time data '2018-01-01' does not match format '%d, %m, %Y' Can someone tell me what is wrong please?

http://stackoverflow.com/q/50928229
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50928295
downvote count: 2
tagged with: python
answer count: 4
type: AnsweredQuestion
tagged with: list
score: 1
has answer: http://stackoverflow.com/a/50934030
has body: I have a list as below: A=[[1,2,3],[4,5,6],[7,8,9]] Now I would like to subtract all the lists in A with B B=[1,1,1] to get the following result C: C=[[0,1,2],[3,4,5],[6,7,8]] I know I can use zip to do two list subtraction, but I cannot use it directly on list within list. How can I do the above subtraction? Thanks
accepted answer: http://stackoverflow.com/a/50928252
type: Question
possible better answer: http://stackoverflow.com/a/50928295
tagged with: arrays
tagged with: list-comprehension
has title: Subtract list within list with a same list in Python
has answer: http://stackoverflow.com/a/50928252
upvote count: 3
has answer: http://stackoverflow.com/a/50931055
favorite count: 0

http://stackoverflow.com/comment/88952193
type: Comment
type: QuestionComment
has text: Then try `re.findall(r'(?i)(\b\d\.\d\d% (?:to|-) \d\d\.\d\d%)', str)`
comment on: http://stackoverflow.com/q/50977971
score: 0

http://stackoverflow.com/comment/88851223
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/50926012
has text: Have you tried? anything at all? an input function at least? You should show us where you're stuck so we don't have to write an entire tutorial for you, just answer your question
type: Comment

http://stackoverflow.com/a/50965517
has comment: http://stackoverflow.com/comment/88928196
downvote count: 0
answers question: http://stackoverflow.com/q/50965308
has body: You can do so: play = play.replace(newdict) The difference between replace and applymap is that when an element in your df is not in the dictionary, with replace the element will stay as it is: df: No Yes Wednesday Monday Thursday Tuesday a day Friday with replace: No Yes 0 2 0 1 3 1 2 a day 4 With applymap you will have NaN: No Yes 0 2.0 0 1 3.0 1 2 NaN 4
type: Answer
has comment: http://stackoverflow.com/comment/88967809
upvote count: 1
has comment: http://stackoverflow.com/comment/88967745
score: 1
has comment: http://stackoverflow.com/comment/88928093

http://stackoverflow.com/comment/89004836
comment on: http://stackoverflow.com/q/51000457
score: 0
type: QuestionComment
type: Comment
has text: Thank you. I have never used javascript before, how can I integrate it with my Django app? Should I create a separate file and then reference it in my HTML?

http://stackoverflow.com/comment/88888507
has text: In your conditional statements you are using True. As such it will always enter this block and that is why you are seeing the message about the else block being unreachable.
type: QuestionComment
type: Comment
score: 2
comment on: http://stackoverflow.com/q/50945463

http://stackoverflow.com/a/51204196
accepted answer of: http://stackoverflow.com/q/50946003
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/50946003
has body: Here you go, this uses anaconda for instillation conda install -c memex pyldavis That fixed it on my end and can use pyLDAvis
has comment: http://stackoverflow.com/comment/89389968
upvote count: 4
downvote count: 0
score: 4

http://stackoverflow.com/comment/88946906
has text: @BehdadAhmadi I don't know, but that's a separate question that's (presumably) about the best way to use Keras, not about how to convert things between Pandas and NumPy or how to deal with multiple datatypes in NumPy, so I'd ask a new question.
score: 0
comment on: http://stackoverflow.com/q/50974965
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88957843
score: 0
type: Comment
has text: @kit- Option 2 does not iterate by row now
type: AnswerComment
comment on: http://stackoverflow.com/a/50963963

http://stackoverflow.com/q/50875060
tagged with: python
linked to: http://stackoverflow.com/q/111155
upvote count: 3
downvote count: 1
has answer: http://stackoverflow.com/a/50875900
has comment: http://stackoverflow.com/comment/88754155
duplicate of: http://stackoverflow.com/q/111155
has title: Execute a certain command before closing window in tkinter
has comment: http://stackoverflow.com/comment/88753913
type: AnsweredQuestion
score: 2
accepted answer: http://stackoverflow.com/a/50875900
has body: I am using tkinter with python. Is it possible to execute a certain command (eg. print ("hello")) before closing the window, when close button is pressed? I am using the close button of the desktop environment (along with maximize and minimize) and not any special close button. Note that I am asking how to execute a certain command before closing, and not how to close the window (which can already be done with the window buttons). So this is not a duplicate of this question
favorite count: 0
tagged with: tkinter
type: Question
possible better answer: http://stackoverflow.com/a/50875438
answer count: 2
has answer: http://stackoverflow.com/a/50875438

http://stackoverflow.com/q/50906416
type: UnansweredQuestion
tagged with: python
has body: I am writing a python script, where I use pymysql to connect to my MYSQL database and execute a query. #sql query to get a list of country codes with country names query = ("SELECT MCC as 'MCC',Name as 'Name' FROM Enum.Country") cursor.execute(query) a = cursor.fetchall() print(a) #convert a to dataframe df = pd.DataFrame(list(a),columns=["MCC","Name"]) print(df) #get the user input user_input2 = raw_input("From the list, please enter the mcc of the country you want to create the service for:") My data frame looks like: MCC Name 0 276 Albania 1 603 Algeria 2 0 All Countries 3 213 Andorra 4 631 Angola 5 722 Argentine Republic 6 283 Armenia 7 505 Australia 8 232 Austria 9 400 Azerbaijan How can I check if the user_input2 is present in the dataframe df? Thanks In advance.
linked to: http://stackoverflow.com/q/19960077
tagged with: mysql
has title: Python script to check if user input value exists in dataframe
type: Question
has comment: http://stackoverflow.com/comment/88812957
tagged with: pymysql
has comment: http://stackoverflow.com/comment/88813314
has comment: http://stackoverflow.com/comment/88812845
has answer: http://stackoverflow.com/a/50906515
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/88816333
answer count: 1
has comment: http://stackoverflow.com/comment/88814332
duplicate of: http://stackoverflow.com/q/19960077
has comment: http://stackoverflow.com/comment/88813421

http://stackoverflow.com/q/50968639
type: Question
has comment: http://stackoverflow.com/comment/88935368
has comment: http://stackoverflow.com/comment/88935223
has answer: http://stackoverflow.com/a/50992751
answer count: 1
downvote count: 0
has body: I'm new to tensorflow and am trying to learn to save and restore my model. I saved it like this: with tf.Session() as sess: sess.run(tf.initialize_all_variables()) for epoch in range(hm_epochs): #Training Model... accuracy = tf.reduce_mean(tf.cast(correct, 'float')) print(sess.run('b1:0')) saver = tf.train.Saver() save_path = saver.save(sess, r"C:\...\Desktop\model.ckpt") And Restoring this model like this: sess = tf.Session() new_saver = tf.train.import_meta_graph(r'C:\...\Desktop\model.ckpt.meta') new_saver.restore(sess,tf.train.latest_checkpoint("C:/.../Desktop")) print(sess.run('b1:0')) But the values in b1 are different in each program. Can someone tell me what I'm doing wrong? Thanks in advance!
favorite count: 0
accepted answer: http://stackoverflow.com/a/50992751
tagged with: python
type: AnsweredQuestion
score: 1
has title: TensorFlow Variable not being restored correctly
upvote count: 1
tagged with: tensorflow

http://stackoverflow.com/q/50969282
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50969501
tagged with: python
has answer: http://stackoverflow.com/a/50969346
answer count: 4
type: AnsweredQuestion
score: 3
linked to: http://stackoverflow.com/q/9607240
upvote count: 3
possible better answer: http://stackoverflow.com/a/50969354
has body: I have this complex list: boundarylist = [('eː', 'n'), ('a', 'k'), ('a', 's')] I want to convert boundarylist to a string, so that I can store it in an external .txt file. boundarystring = ' '.join(boundarylist) does not work. The output should be something like this: boundarystring = 'eːn ak as' #seperated by \s or \n I tried these algorithms suggested in “”.join(list) if list contains a nested list in python?, but it returns 'eːnakas' respectively 'eː n a k a s': import itertools lst = [['a', 'b'], ['c', 'd']] ''.join(itertools.chain(*lst)) 'abcd' and ''.join(''.join(inner) for inner in outer)
has answer: http://stackoverflow.com/a/50969354
type: Question
has answer: http://stackoverflow.com/a/50969451
accepted answer: http://stackoverflow.com/a/50969346
downvote count: 0
has title: How to convert a complex list to string in Python?
has comment: http://stackoverflow.com/comment/88934836
has comment: http://stackoverflow.com/comment/88935075
favorite count: 0

http://stackoverflow.com/q/50877182
has title: Python / Spark .map function : Accessing sub list from record
tagged with: apache-spark-sql
tagged with: pyspark
upvote count: 1
favorite count: 0
tagged with: python
has body: I'm working with the movieLens dataset and the goal is to map and transform the dataset into a couple informative and readable dataframes before creating a top-10 list of recommendations for every user in the dataset. The dataset also contains the next movieId every user is going to watch, which is used to check if the next movieId is present in the top-10 recommendations per user. So far i've been able to pull it off solo or with the help of some addtional information here on stackoverflow and/or some tutorials. I wrote a simple function with an if/else statement used to map a RDD and if the nextmovie is present in my top-10 list of recommendations it returns 1, else 0. # MOVIE RECOMMENDOR #All movies, orderd by popularity allMoviesRDD = movieStatsDF.rdd.map(lambda x: x[0]).collect() sample: [296, 356, 593, 318, 480, 260, 110, 589, 2571, 527] #Joined dataframe that im using +------+---------+--------------------+ |userId|nextmovie| seen| +------+---------+--------------------+ | 148| 2629|[2396, 2671, 4306...| | 471| 4122|[3101, 1645, 2858...| | 833| 527|[364, 150, 432, 4...| | 1580| 1196|[7161, 1203, 8610...| | 1645| 26|[608, 107, 7, 256...| +------+---------+--------------------+ root |-- userId: integer (nullable = true) |-- nextmovie: integer (nullable = true) |-- seen: array (nullable = true) | |-- element: string (containsNull = true # Mapping function def recommend(record): userid, nextmovie, seen = record if nextmovie in allMoviesRDD[:10]: return 1 else: return 0 # Call the function eval = joinDF.rdd.map(recommend) # Print succes percentage print ("Succes% =", 100 * eval.sum() / eval.count()) The above is very crude and basic but it works and gives a succes rate of 3.936 %. However, because its possible that a user has already seen one of the movies in the top-10 list, i have to check the top-10 list and the list with movies the user has already seen. If a movieId is present in both lists, i have to remove it from the top-10 recommendations and add the next…
answer count: 0
downvote count: 0
type: UnansweredQuestion
score: 1
type: Question

http://stackoverflow.com/a/50894536
downvote count: 0
has body: you can do like: keys = stripeId['keys'] secret = keys['secret'] publishable = keys['publishable'] Now you can save values of secret and publishable in database.
accepted answer of: http://stackoverflow.com/q/50892254
answers question: http://stackoverflow.com/q/50892254
type: Answer
upvote count: 1
score: 1
type: AcceptedAnswer

http://stackoverflow.com/q/50899952
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/88799851
score: 2
has comment: http://stackoverflow.com/comment/88800078
has title: Translator using a dictionary
has comment: http://stackoverflow.com/comment/88799865
upvote count: 3
has comment: http://stackoverflow.com/comment/88800204
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88800292
answer count: 1
has body: I'm trying to solve a problem that can be found in the Book The Coder's Apprentice by Pieter Spronck, in section 13.2.4. This is the code I wrote so far: english_dutch = {"last":"laatst", "week":"week", "the":"de", "royal":"koninklijk", "festival":"feast", "hall":"hal", "saw":"zaag", "first":"eerst", "performance":"optreden", "of":"van", "a":"een", "new":"nieuw", "symphony":"symphonie", "by":"bij", "one":"een", "world":"wereld", "leading":"leidend", "modern":"modern", "composer":"componist", "composers:componisten" "two":"twee", "shed":"schuur", "sheds":"schuren"} text = "Last week The Royal Festival Hall saw the first \ performance of a new symphony by one of the world's leading \ modern composers, Arthur 'Two-Sheds' Jackson." def clean(t): t = t.lower() t = t.split() new_t = "" for word in t: new_word = "" for letter in word: if "a" &lt;= letter &lt;= "z": new_word += letter if letter == "-": new_word += " " else: continue new_t += new_word + " " return new_t def translate(t): translation = "" for word in t.split(): if english_dutch.get(word): translation += english_dutch[word] + " " else: translation += word + " " return translation def auto_correct(): news = "" a = translate(clean(text)).split() for word in a: if len(word) &gt; 1: news += word + " " print(news) auto_correct() It seems to work OK, but when I run it, the words "composers" and "two" are not translated.
tagged with: python-3.6
has answer: http://stackoverflow.com/a/50899986
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/50980088
has comment: http://stackoverflow.com/comment/89494809
linked to: http://stackoverflow.com/q/379906
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88959985
upvote count: 1
tagged with: python
downvote count: 1
has body: 0.03611642492570208 such numbers are present as string in a CSV file, I wish to read them and perform mathematical operations, but when I read it it is read as String and when i convert it to numeric form it is rounded off. How can i convert it to numeric value without loosing precision. Edited : item_id,deal_probability 6544e41a8817,0.299918385137877 65b9484d670f,0.09258187813010357 8bab230b2ecd,0.15371873083249338 8e348601fefc,0.07208665773638352 8bd2fe400b89,0.25543690938853253 c63dbd6c657f,0.05238764253800446 6d1a410df86e,0.0512983797826358 e8d3e7922b80,0.009989860172001194 2bc1ab208462,0.04119998171932098 This is the format of my csv file and when I read it in my jupyter notebook the value under deal_probability is rounded off to 6 places after decimal. Expected result :- I want to read the entire csv without any change in the value under deal_probability
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50980153
has title: String of decimal values to numeric without round off
has answer: http://stackoverflow.com/a/51257246
accepted answer: http://stackoverflow.com/a/51257246
has comment: http://stackoverflow.com/comment/88955934
has answer: http://stackoverflow.com/a/50980154
type: Question
has comment: http://stackoverflow.com/comment/88955920
score: 0
answer count: 3
tagged with: pandas
possible better answer: http://stackoverflow.com/a/50980153

alpha-transparency
type: Tag
tags question: http://stackoverflow.com/q/50930770
tag name: alpha-transparency

http://stackoverflow.com/comment/88932565
type: QuestionComment
has text: I don't think it's activating because nothing is printed to console signaling that it's being used. When I run something like `lgb.train({'device': 'gpu'}, data)`, it prints status messages from the GPU, and when I run `lgb.train({'device': 'cpu'}, data)`, nothing is printed out. This is why I suspected that it is not hitting the gpu
score: 0
comment on: http://stackoverflow.com/q/50956103
type: Comment

http://stackoverflow.com/comment/134390927
type: QuestionComment
comment on: http://stackoverflow.com/q/50928592
has text: Many of the answers below suggest to use `float` only because `int` gets implied. But that seems to be the case only when doing type hinting. What if I am *both* using it for type hinting and for determining actions in the function? Specifically, I am making up fake data using `faker`, and I want a wrapper function with a match statement that generates different fake data depending upon what the type is. I guess still `Union[float, int]`, right?
score: 0
type: Comment

http://stackoverflow.com/comment/88892119
has text: Ok, but +1-2-2+6=3. So it is not a cumulative sum. Or do you only want the cumulative sum of consecutive negative numbers?
score: 0
comment on: http://stackoverflow.com/q/50946534
type: Comment
type: QuestionComment

web-services
type: Tag
tags question: http://stackoverflow.com/q/50956377
tags question: http://stackoverflow.com/q/50949540
tags question: http://stackoverflow.com/q/50981036
tag name: web-services

http://stackoverflow.com/comment/88934104
type: Comment
type: QuestionComment
has text: yeah but you lost the 'apple' because it's not in your output. plus if u give as input ['apple','carlo','apple','elephant','tower','rank'] you get [['elephant'], ['elephant'], ['tower'], ['rank']] and it doesn't look than correct... could u pls give me a bigger example?
comment on: http://stackoverflow.com/q/50968717
score: 0

http://stackoverflow.com/q/50895035
has answer: http://stackoverflow.com/a/50895074
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/50895074
has title: Sorting multiple numpy arrays elementwise
tagged with: arrays
downvote count: 0
answer count: 1
favorite count: 0
has body: Suppose I have 3 arrays (I know the number of arrays beforehand) that I want to sort, element by element. For example, suppose I have: import numpy as np x = np.array([ [100, 200, 300], [400, 500, 600], [700, 800, 900] ]) y = np.array([ [1, 2, 3], [4, 5, 6], [7, 8, 9], ]) z = np.array([ [10, 20, 30], [40, 50, 60], [70, 80, 90] ]) And I'd want to get the order for each element: [ [[0, 2, 1], [0, 2, 1], [0, 2, 1]], [[0, 2, 1], [0, 2, 1], [0, 2, 1]], [[0, 2, 1], [0, 2, 1], [0, 2, 1]], [[0, 2, 1], [0, 2, 1], [0, 2, 1]], [[0, 2, 1], [0, 2, 1], [0, 2, 1]], [[0, 2, 1], [0, 2, 1], [0, 2, 1]], [[0, 2, 1], [0, 2, 1], [0, 2, 1]], [[0, 2, 1], [0, 2, 1], [0, 2, 1]], [[0, 2, 1], [0, 2, 1], [0, 2, 1]] ] In this case all the positions are on the same order to keep the example simple (0 > 2 > 1), but in reality each element on each array could be bigger than its counterpart on another array. I'm also working with higher dimension arrays (3d rather than 2d), but I think the general idea would be the same. I believe I need to reshape the arrays and then np.argsort them (or just regular np.sort, I'm more interested in the values rather than where they came from, though if the overhead of having the origin isn't high, it might be useful down the line). But I'm not sure how to reshape them such that I can apply the operation. All arrays are guaranteed to have the same shape, and despite my example here, it will always be an even number. I'm not sure if the format I have in mind would be good for indexing after I have the order, but at the moment I can't figure out a better way to group the results. I believe I can just split them later with something like answer[...,0] for the maximum indexes (or maximum values), answer[...,1] for the second and so on. Though if I have the indexes, I'd have to map them later on to the arrays. Shouldn't be that hard I think, I'd just have to np.stack them together I believe. Any suggestions?
tagged with: multidimensional-array
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1

http://stackoverflow.com/q/50997457
upvote count: 0
answer count: 1
has title: how to install packages without direct internet considered packages dependencies?
has answer: http://stackoverflow.com/a/50997558
linked to: http://stackoverflow.com/q/36014334
tagged with: dependencies
favorite count: 0
type: UnansweredQuestion
tagged with: python
downvote count: 1
has body: I want to install packages without using the Internet. I searched for it. For example, using this reference: pip install relative_path_to_seaborn.tar.gz But I think if I can not consider package dependencies , it can not be installed properly. In R, using library miniCRAN, consider dependencies. So how to install packages without the Internet connection and taking into account the package dependencies?
tagged with: installation
score: -1
type: Question

http://stackoverflow.com/q/50883703
favorite count: 0
tagged with: python
tagged with: c++
upvote count: 7
accepted answer: http://stackoverflow.com/a/51043861
type: Question
has title: pybind how can I operate over a py::list object
type: AnsweredQuestion
score: 7
tagged with: pybind11
has answer: http://stackoverflow.com/a/51043861
answer count: 1
downvote count: 0
has body: For a better understanding of how to pass arguments from Python to C++ functions with the pybind library, I wanted to build a small dummy/demo code where I could receive a Python list on the C++ side, cast it to a float pointer object, and then print it. Though I know I can use the py::list class I haven't figured out the methods available of this class. I looked in the documentation reference, and then in the code (list.h, stl.h) and couldn't figure out which methods where available. What is the equivalent of __getitem__? Do I have every python method available for py::list?

http://stackoverflow.com/comment/88938603
type: Comment
comment on: http://stackoverflow.com/a/50970628
score: 0
type: AnswerComment
has text: I understand writing a rough draft and then updating it as you go. Just be more careful on your wording. I know and you should know that calling something a copy can be taken very badly in the world of coding.

http://stackoverflow.com/a/77821755
has body: A simple solution if you don't want to subclass logging.Formatter is to overwrite/monkeypatch logging.Formatter.formatTime() directly like so: import logging from datetime import datetime def formatTime(self, record, datefmt=None): return datetime.fromtimestamp(record.created).astimezone().isoformat(timespec='milliseconds') logging.Formatter.formatTime = formatTime logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(name)s %(message)s') logger = logging.getLogger(__name__) # __name__ myvar = 1 logger.info("test %s", myvar) which will print the timestamp as a ISO8601 with milliseconds and UTC offset: 2024-01-15T19:31:29.303+01:00 INFO __main__ test 1 Or you can subclass logging.Formatter like his import logging import logging.config from datetime import datetime class MyCustomFormatter(logging.Formatter): def formatTime(self, record, datefmt=None): return datetime.fromtimestamp(record.created).astimezone().isoformat(timespec='milliseconds') logging.config.dictConfig({ 'version': 1, 'formatters': { 'mycustomformatter': { '()': MyCustomFormatter, 'format': '%(asctime)s %(levelname)s %(name)s %(message)s', }, }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'formatter': 'mycustomformatter', }, }, 'loggers': { 'root': { 'level': 'DEBUG', 'handlers': ['console'], }, } }) logger = logging.getLogger(__name__) myvar = 1 logger.info("test %s", myvar) which produces the exact same output with ISO8601 timestamps: 2024-01-15T19:31:29.303+01:00 INFO __main__ test 1 In both cases the formatTime() code uses: record.created is the LogRecord attribute representing the number of seconds (float) since the epoch returned by time.time() datetime.fromtimestamp() is a class method that converts the epoch seconds to a datetime (naive) astimezone() converts the naive datetime to timezone-aware datetime in the local timezone isoformat(): converts the timezone aware datetime to a ISO8601 string.
answers question: http://stackoverflow.com/q/50873446
score: 0
type: Answer

http://stackoverflow.com/comment/88832629
comment on: http://stackoverflow.com/q/50869065
score: 0
type: QuestionComment
has text: Can you provide more info about why you think it doesn't work? Is there an error message you can include in your question?
type: Comment

http://stackoverflow.com/q/50973815
score: 7
possible better answer: http://stackoverflow.com/a/55265181
has answer: http://stackoverflow.com/a/55265181
answer count: 2
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/50974082
has body: I'm trying to install pycurl via: sudo pip install pycurl It downloaded fine, but when when it runs setup.py I get the following traceback: Downloading/unpacking pycurl Running setup.py egg_info for package pycurl Traceback (most recent call last): File "&lt;string&gt;", line 16, in &lt;module&gt; File "/tmp/pip-build-root/pycurl/setup.py", line 563, in &lt;module&gt; ext = get_extension() File "/tmp/pip-build-root/pycurl/setup.py", line 368, in get_extension ext_config = ExtensionConfiguration() File "/tmp/pip-build-root/pycurl/setup.py", line 65, in __init__ self.configure() File "/tmp/pip-build-root/pycurl/setup.py", line 100, in configure_unix raise ConfigurationError(msg) __main__.ConfigurationError: Could not run curl-config: [Errno 2] No such file or directory Complete output from command python setup.py egg_info: Traceback (most recent call last): File "&lt;string&gt;", line 16, in &lt;module&gt; File "/tmp/pip-build-root/pycurl/setup.py", line 563, in &lt;module&gt; ext = get_extension() File "/tmp/pip-build-root/pycurl/setup.py", line 368, in get_extension ext_config = ExtensionConfiguration() File "/tmp/pip-build-root/pycurl/setup.py", line 65, in __init__ self.configure() File "/tmp/pip-build-root/pycurl/setup.py", line 100, in configure_unix raise ConfigurationError(msg) __main__.ConfigurationError: Could not run curl-config: [Errno 2] No such file or directory Any idea why this is happening and how to get around it using Alpine Linux?
tagged with: python
tagged with: installation
tagged with: alpine-linux
upvote count: 7
tagged with: pycurl
type: Question
has title: “Could not run curl-config: [Errno 2] No such file or directory” when installing pycurl on Alpine Linux
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50974082

http://stackoverflow.com/a/50999699
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50997189
type: Answer
answers question: http://stackoverflow.com/q/50997189
has body: Replace this code : def search(): elem2 = browser.find_element_by_name('txtFind') elem2.send_keys('14066') elem2.send_keys(Keys.RETURN) To this : def search(): elem2 = WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.ID, "txtFind"))) elem2.send_keys('14066') elem2.send_keys(Keys.RETURN) Note that if ID is given , then there is no need to go for any locator.

http://stackoverflow.com/comment/89146144
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50997436
has text: I have reduced the model and verified data once again. Tried using batch normalisation but the result is validation accuracy is still not changing. While the training accuracy seems to move between 0.85 -0.86. It is not going above 0.86 while loss and validation loss are constantly improving.
type: AnswerComment

http://stackoverflow.com/a/50894076
has comment: http://stackoverflow.com/comment/89227085
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/89237601
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50893819
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88789285
answers question: http://stackoverflow.com/q/50893819
has body: Not sure this is really the same, but by eye it looks close enough: import numpy as np phi, theta, R = np.ogrid[-40:40:21j, -40:40:21j, 3480:6371:21j] y, x = np.tan(phi*np.pi/180), np.tan(theta*np.pi/180) z = R / np.sqrt(x*x + y*y + 1) y, x = y*z, x*z from mpl_toolkits.mplot3d import Axes3D import pylab fig = pylab.figure(1) ax = fig.add_subplot(111, projection='3d') ax.plot_wireframe(x[..., 20], y[..., 20], z[..., 20]) ax.plot_wireframe(0.01*x[..., 20], 0.01*y[..., 20], 0.01*z[..., 20]) # hack to scale z axis ax.plot_wireframe(x[:, 20, :], y[:, 20, :], z[:, 20, :]) ax.plot_wireframe(x[0, ...], y[0, ...], z[0, ...]) fig.show()
has comment: http://stackoverflow.com/comment/88789746
type: Answer

http://stackoverflow.com/comment/88904703
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50953377
has text: Try taking a screenshot. Where you are trying to 'move', might not be displayed. A screenshot will help you diagnose what is happening.
type: Comment

http://stackoverflow.com/a/50880291
has body: You got the write_to_file function but you never call it? mode have to be w or w+(if you wanna overwrite in the case if the file already exists)
has comment: http://stackoverflow.com/comment/88815756
has comment: http://stackoverflow.com/comment/88928053
has comment: http://stackoverflow.com/comment/88822523
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50880175
has comment: http://stackoverflow.com/comment/88815701

http://stackoverflow.com/comment/88773582
type: Comment
has text: @VaibhavSharma I do not use try, except. What do you mean by that?
comment on: http://stackoverflow.com/a/50885893
type: AnswerComment
score: 0

http://stackoverflow.com/q/50917156
has comment: http://stackoverflow.com/comment/88834491
has comment: http://stackoverflow.com/comment/88834797
has title: NPM install can't execute Python in MAC
upvote count: 2
answer count: 2
has comment: http://stackoverflow.com/comment/88834541
has answer: http://stackoverflow.com/a/69920745
tagged with: macos
has comment: http://stackoverflow.com/comment/88834671
linked to: http://stackoverflow.com/q/6819661
favorite count: 0
has answer: http://stackoverflow.com/a/50917682
accepted answer: http://stackoverflow.com/a/50917682
has body: I'm new to MAC (OSX version is High Sierra 10.13.3). I installed python 3.6.5 with the installer from python.org and I tried doing it with brew too by running brew install python. Now, I'm trying to run sudo npm install in a Angular project and I get the following errors: gyp verb check python checking for Python executable "/path/to/python3/python" in the PATH gyp verb `which` failed Error: not found: /path/to/python3/python gyp ERR! stack Error: Can't find Python executable "/path/to/python3/python", you can set the PYTHON env variable. I have tried all the answers in here : python location on mac osx Can't find Python executable "python" Inside of my projects folder I do the following: when I type 'which python' I get: /usr/local/opt/python/libexec/bin/python When I type 'which python3.6.5' I get: /Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6
tagged with: npm
tagged with: python
has comment: http://stackoverflow.com/comment/88834315
score: 2
type: AnsweredQuestion
downvote count: 0
possible better answer: http://stackoverflow.com/a/69920745
has comment: http://stackoverflow.com/comment/88835330
linked to: http://stackoverflow.com/q/23571257
has comment: http://stackoverflow.com/comment/88834394
type: Question
has comment: http://stackoverflow.com/comment/88834550
has comment: http://stackoverflow.com/comment/88834411

dynamic-pivot
type: Tag
tag name: dynamic-pivot
tags question: http://stackoverflow.com/q/50855155

http://stackoverflow.com/a/50971314
upvote count: 2
type: Answer
score: 2
has body: With the small sample data you have provided I have been able to group the rows into intervals. For the sake of this example I have used a range of 20ms instead of 120 seconds so it is clear whether the groups actually appear # Note the index is formatted to a datetime using pd.to_datetime() # The index is also sorted using df.sort_index() df Out[]: 1 2 3 4 5 6 7 8 9 10 date 2018-05-30 01:00:00.177335 0.008845 0.078787 0.075259 0.062903 0.080644 0.070641 0.123609 0.123609 0.379142 0.334873 2018-05-30 01:00:00.197618 0.008165 0.072722 0.069466 0.058061 0.084252 0.065204 0.114090 0.114090 0.349875 0.309034 2018-05-30 01:00:00.198604 0.007582 0.077386 0.084229 0.123003 0.078229 -0.028003 0.046915 0.105932 -0.038534 0.277084 2018-05-30 01:00:00.209000 -0.001327 0.067707 0.082986 0.135505 0.151487 0.058935 0.096654 0.092678 0.100460 0.241702 2018-05-30 01:00:00.209151 0.125945 0.072224 0.088524 0.144552 0.172234 0.062866 0.103104 0.098863 0.329249 0.268425 2018-05-30 01:00:00.209954 0.008740 0.063721 0.078101 0.127524 0.152567 0.055466 0.090963 0.087222 0.094545 0.227452 2018-05-30 01:00:00.211234 0.008255 0.060179 0.073759 0.120431 0.144079 0.052383 0.075903 0.082372 -0.070497 0.005282 2018-05-30 01:00:00.212916 0.078199 0.067070 0.069874 0.114085 0.136485 0.049624 0.081938 0.078034 0.093496 0.215160 2018-05-30 01:00:00.213127 0.074286 0.073802 0.076467 0.108375 0.129652 0.047142 0.057717 0.074129 -0.071906 -0.006338 2018-05-30 01:00:00.246716 0.101065 0.151183 0.143619 0.123444 0.133590 0.044896 0.054967 0.070597 -0.068484 -0.006036 2018-05-30 01:00:00.254647 0.096466 0.144302 0.137082 0.117827 0.127510 0.042855 0.052468 0.067385 -0.065373 -0.005762 Your Solution (I have focused on this part of the problem only): %%timeit X = [] Y = [] for date in df.index: window = df.loc[(df.index &lt;= date) &amp; (df.index &gt;= date-datetime.timedelta(seconds=0.02))] if len(window) &gt; 0: X.append(window.values) 4.06 ms ± 55 µs per loop (mean ± std. dev. of 7 runs, 100 loops each…
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50951700
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50951700

http://stackoverflow.com/a/50894069
has comment: http://stackoverflow.com/comment/89005838
has body: Python Socket TCP connection size limit? Your are actually asking the wrong question. The real problem is that TCP is a streaming protocol and you are treating it as a message protocol, i.e. you assume in your code that each send on one side will be handled by exactly one recv at the peer. Apart from that you assume that send will write the complete buffer given as argument but the documentation clearly states that it does not: Applications are responsible for checking that all data has been sent; if only some of the data was transmitted, the application needs to attempt delivery of the remaining data. Ignoring this means that you might face incomplete "messages" when reading or that you get multiple "messages" (or one fill and one partial or similar) when reading the data. This might for example lead to crashes when trying to unpickle data. But to get to the size limit: it is limited how many data you can actually write within a single send. This limit depends on the size of the socket buffer and also on the current state of the socket, i.e. if the socket is already filled or not. If you use ssl sockets it is further limited by the maximum size of a SSL frame. But by itself TCP has no limits on how much data can be transmitted, but you need multiple writes to the socket if you deliver many data. The client program contains a keylogger, which is for now useless because I haven't created a command to activate it yet, so you can just ignore that. It helps a lot when debugging a problem yourself or asking others to help you debugging it, if you throw everything away which is not actually needed to reproduce the problem. See How to create a Minimal, Complete, and Verifiable example.
has comment: http://stackoverflow.com/comment/88917828
accepted answer of: http://stackoverflow.com/q/50893815
has comment: http://stackoverflow.com/comment/88917598
has comment: http://stackoverflow.com/comment/88841487
type: Answer
has comment: http://stackoverflow.com/comment/89007567
score: 7
upvote count: 7
answers question: http://stackoverflow.com/q/50893815
has comment: http://stackoverflow.com/comment/88842069
has comment: http://stackoverflow.com/comment/88917525
has comment: http://stackoverflow.com/comment/88917534
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/50978408
answers question: http://stackoverflow.com/q/50976274
score: 0
type: Answer
has body: try something like this d = {1:[9,9,9],2:[8,8,8],3:[7,7,7]} newkeylist = [4,2,3] d_copy = d.copy() for i, (k, v) in enumerate(d_copy.items()): if k != newkeylist[i]: d[newkeylist[i]] = v del d[k] but as @jonrsharpe said, it's not an ordered dict: the output is random

http://stackoverflow.com/a/73044106
has body: I'm using the Bootstrap 5 Navs and Tabs snippet which may also be helpful for this sort of problem https://getbootstrap.com/docs/5.2/components/navs-tabs/#javascript-behavior
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51005915
has comment: http://stackoverflow.com/comment/129038478

http://stackoverflow.com/q/50877663
score: 4
upvote count: 4
answer count: 2
has answer: http://stackoverflow.com/a/50877710
tagged with: pandas
downvote count: 0
tagged with: nan
favorite count: 0
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50877710
possible better answer: http://stackoverflow.com/a/70967626
has body: I am working with quite a large dataset (over 4 GB), which I imported in pandas. Quite some columns in this dataset are simple True/False indicators, and naturally the most memory-efficient way to store these would be using a bool dtype for this column. However, the column also contains some NaN values I want to preserve. Right now, this leads to the column having dtype float (with values 1.0, 0.0 and np.nan) or object, but they both use way too much memory. As an example: df = pd.DataFrame([[True,True,True],[False,False,False], [np.nan,np.nan,np.nan]]) df[1] = df[1].astype(bool) df[2] = df[2].astype(float) print(df) print(df.memory_usage(index=False, deep=True)) print(df.memory_usage(index=False, deep=False)) results in 0 1 2 0 True True 1.0 1 False False 0.0 2 NaN True NaN 0 100 1 3 2 24 dtype: int64 0 24 1 3 2 24 dtype: int64 What would be the most efficient way to store these kinds of values, knowing they can only take on 3 different kinds of values: True, False and &lt;undefined&gt;
tagged with: memory
has title: Memory efficient way to store bool and NaN values in pandas
has answer: http://stackoverflow.com/a/70967626
type: Question

http://stackoverflow.com/a/50992399
has comment: http://stackoverflow.com/comment/89197783
type: AcceptedAnswer
has body: w3.eth.sendTransaction() only supports sending unsigned transactions. In order to use it, your node must be managing your private key. Since the node must manage your key, you must not use it with a hosted node. w3.eth.sendRawTransaction() requires that the transaction be already signed and serialized. So it requires extra serialization steps to use, but enables you to broadcast transactions on hosted nodes. There are other reasons that you might want to use a local key, of course. All of them would require using sendRawTransaction().
upvote count: 9
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50985798
has comment: http://stackoverflow.com/comment/89199234
answers question: http://stackoverflow.com/q/50985798
score: 9

http://stackoverflow.com/comment/88987832
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50996305
has text: If it was generated by 3.3+, the encoding is probably just a red herring, and it's trying to read non-strings as strings, and you'll need to use `pickletools` to debug it.
score: 0

http://stackoverflow.com/a/50999628
has comment: http://stackoverflow.com/comment/88993225
has comment: http://stackoverflow.com/comment/88993245
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50999548
has body: You can shuffle the names list at the beginning, and just iterate over them once. Also random.choice is the better option than random.sample when only one item is chosen. Here's the code import random price = ["You have won the drill-motor" , "You have won the DC motor"] names = ["Hilmi", "Joris", "Isa", "Dennis", "Jasper"] shuffled_names = names[:] # create a copy if you want original order preserved random.shuffle(shuffled_names) for name in shuffled_names: print(name, random.choice(price))

http://stackoverflow.com/comment/88828253
score: 0
has text: I stuck there, I am not able to find the link for the click using selenium. I want to make a list of all three options i.e. Point, Hourly and Daily after that iterate over them. but noble to find the link for these three options.
type: Comment
comment on: http://stackoverflow.com/a/50913975
type: AnswerComment

http://stackoverflow.com/a/50941690
has comment: http://stackoverflow.com/comment/88882365
downvote count: 0
has body: One of the ways to achieve this is by creating another CSV file by merging data from existing CSV files (assuming you have the CSV files in the format aa##.csv)... contents = [] for filenum in range(2): f = open('aa{}.csv'.format(filenum + 1), 'r') lines = f.readlines() print(lines) f.close() if contents == []: contents = [[] for a in range(len(lines))] for row in range(len(lines)): contents[row].append(lines[row].rstrip('\n')) print(lines[row]) print(contents) f = open('aa_new.csv', 'w') for row in range(len(contents)): line = str(contents[row]) line = line.strip('[]') f.write(line + '\n') f.close() You can then open &amp; display this file as you wish using pandas.
type: Answer
has comment: http://stackoverflow.com/comment/88882646
answers question: http://stackoverflow.com/q/50941165
upvote count: 1
has comment: http://stackoverflow.com/comment/88882681
has comment: http://stackoverflow.com/comment/88882415
score: 1
has comment: http://stackoverflow.com/comment/88881827

http://stackoverflow.com/comment/88998389
comment on: http://stackoverflow.com/a/50959375
score: 0
type: AnswerComment
has text: I figured it out, I'm posting my solution as the answer to my own questing now. I think it should be something else besides date_cell?
type: Comment

http://stackoverflow.com/a/50888637
accepted answer of: http://stackoverflow.com/q/50888612
has comment: http://stackoverflow.com/comment/135521969
has comment: http://stackoverflow.com/comment/135648445
has body: You can create the mask using a regular expression as below. The dollar sign will ensure the hyphen is only matched at the end of the string. df.a.str.contains('-$') This will return a boolean series. Using your example: 0 True 1 False 2 False You can then drop the rows as usual using df.drop(): df.drop(df[df.a.str.contains('-$')].index, inplace=True) And reset the index if you would like: df.reset_index(inplace=True, drop=True)
type: Answer
score: 12
answers question: http://stackoverflow.com/q/50888612
upvote count: 12
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/88742527
type: QuestionComment
comment on: http://stackoverflow.com/q/50870437
has text: Such questions are off-topic in SO; please see [What topics can I ask about here?](https://stackoverflow.com/help/on-topic)
score: 0
type: Comment

http://stackoverflow.com/q/50944469
type: Question
upvote count: 4
accepted answer: http://stackoverflow.com/a/50946185
answer count: 2
has title: Python; Why passing function arguments not mandatory
possible better answer: http://stackoverflow.com/a/50945108
has comment: http://stackoverflow.com/comment/88888049
linked to: http://stackoverflow.com/q/20125172
downvote count: 0
has comment: http://stackoverflow.com/comment/88887484
score: 4
tagged with: arguments
has body: It seems to me that it is not mandatory to pass the variables you want to use inside a function to that function in python. This code: def functionWithoutArgs(): print(theList) theList.append('asdf') print(theList) theNewList = theList + ['qwer'] print(theNewList) return theNewList theList = ['this', 'is', 'a', 'list'] theLastList = functionWithoutArgs() print(theLastList) gives me this output (without errors or warnings): ['this', 'is', 'a', 'list'] ['this', 'is', 'a', 'list', 'asdf'] ['this', 'is', 'a', 'list', 'asdf', 'qwer'] ['this', 'is', 'a', 'list', 'asdf', 'qwer'] I was surprised that no exceptions were raised. This because (it seems to me that) allowing functions to use variables that have not been passed to them obfuscates how that function interacts with other code pretty severely. As far as I understand the whole point of functions is to break programs into small parts that have their interaction with the rest of the code clearly defined. Question: Why does python allow using variables inside a function that has not been passed to that function? Additional info: The reason for the excess code in the example is this thread Use a Variable in a Function Without Passing as an Argument where the accepted answer claims that using unpassed variables is only allowed when the called function does not modify or rename the variable (as I understood at least), which the above code counterexamples. I understand that this question is borderline subjective or opinion based as it is a "Why..." question, but I felt that this is so fundamental that there has to be some kind of consensus argument for this. In addition, it would be useful knowledge for many new python programmers.
favorite count: 0
has comment: http://stackoverflow.com/comment/88886570
has answer: http://stackoverflow.com/a/50946185
linked to: http://stackoverflow.com/q/28379373
tagged with: python
has comment: http://stackoverflow.com/comment/88886832
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50945108

http://stackoverflow.com/a/50878637
answers question: http://stackoverflow.com/q/50878549
score: 0
type: Answer
has body: This should do it: estabilidade([^(]+) It's using a negative character class, that's the key take away and a good tool in your bag to have. [] is a character class. It is a list of characters, if you put in ^ as the first character it's a list of characters not in there. So [^(] means any character that isn't (. Adding the + means at least 1 of the item to the left. So, putting all that together we want at least 1 non (. Here is it in Python: import re text = "hello estabilidade how are you today (at the farm)" print (re.search("estabilidade([^(]+)", text).group(1)) Output: how are you today Example to play with: https://regex101.com/r/2qxa0y/1/ Here is a good site to learn some of the basic regex tricks, this will go a long way: https://www.regular-expressions.info/tutorial.html
has comment: http://stackoverflow.com/comment/88762962
has comment: http://stackoverflow.com/comment/88762845

http://stackoverflow.com/comment/88884060
type: QuestionComment
has text: Hi Evgeny. Thank you for your answer. Nonetheless, I am not sure whether that is my problem or not. I know with `.to_csv()` you can write your dataframe on an existing .txt file. The problem is that you overwrite/erase all data that exist on it. Then, there is another option `mode = 'a'` which allows you to append your dataframe to existing file. My question is whether you can append your dataframe from specific row (removing everything below that row).
comment on: http://stackoverflow.com/q/50923265
score: 0
type: Comment

http://stackoverflow.com/a/57997471
downvote count: 0
answers question: http://stackoverflow.com/q/50964427
has body: The pingouin package has a Welch's ANOVA implemented. You can find the documentation for it at https://pingouin-stats.org/generated/pingouin.welch_anova.html.
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/comment/88802053
type: AnswerComment
type: Comment
has text: That worked perfectly! Thank you MaxU! Really appreciate the detailed response!
comment on: http://stackoverflow.com/a/50900488
score: 0

http://stackoverflow.com/comment/88829623
comment on: http://stackoverflow.com/q/50913834
score: 1
type: Comment
has text: Spark uses snappy as default compression format for writing parquet files. Seems like snappy compression is causing issue as its not able to find all requisite on one of the executor [ld-linux-x86-64.so.2]. Could you please try setting "--conf spark.io.compression.codec=lz4", just to narrow down on probable cause? Also make sure os and java have same arch on all executors and driver.
type: QuestionComment

http://stackoverflow.com/comment/89016384
comment on: http://stackoverflow.com/a/51011723
type: Comment
has text: This changes the shape of the data, which isn't what I'm looking for. But otherwise, this is a good solution.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/88948440
has text: You'll probably run into many problems if these two get out of synch. Ultimately if you are going to use an ORM to handle your application, you should use it to manage the database. Youll get hurt by the ORM is the schema does nto match the model. Speaking of your data model, do you think its a good idea to make a city name unique? There is more than one Charleston in the USA. There's more than one Cuba in the world. If you think you must have this, try a composite unique constraint on State and City.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50976041
score: 1

http://stackoverflow.com/comment/88973877
comment on: http://stackoverflow.com/q/50985140
score: 1
has text: `pytest` escapes parametrized ids, this can't be reconfigured. See [issue #2482](https://github.com/pytest-dev/pytest/issues/2482) for details.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88769228
score: 0
type: AnswerComment
has text: Thanks for the response Sahil! Unfortunately, I keep getting the error "data frame object has no string." Any thoughts?
type: Comment
comment on: http://stackoverflow.com/a/50869426

http://stackoverflow.com/comment/88864642
score: 0
comment on: http://stackoverflow.com/a/50932882
type: Comment
type: AnswerComment
has text: I strongly disagree about making the logic cleaner or easier. That code is highly unreadable.

http://stackoverflow.com/a/50978546
score: 2
downvote count: 0
upvote count: 2
has body: Here is a solution that would stop iteration as soon as it finds a dup &gt;&gt;&gt; from itertools import dropwhile &gt;&gt;&gt; s=set(); next(dropwhile(lambda c: not (c in s or s.add(c)), letters)) 'c'
answers question: http://stackoverflow.com/q/50976511
type: Answer

http://stackoverflow.com/q/50873757
favorite count: 0
has comment: http://stackoverflow.com/comment/88753536
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/50874007
tagged with: python
has body: If inputed an numpy 2d array such as 100 100 100 100 100 100 0 0 0 100 100 0 0 0 100 100 0 0 0 100 100 100 100 100 100 an output like this should be obtained 100 100 100 100 100 100 50 25 50 100 100 25 0 25 100 100 50 25 50 100 100 100 100 100 100 where every number except the border becomes the mean of its adjacent numbers. My current code works but I need to use it without for loops and vectorize it using numpy. My current code: import numpy as np def evolve_heat_slow(u): u2 = np.copy(u) x=u2.shape[0] y=u2.shape[1] for i in range(1,x-1): for s in range(1,y-1): u2[i,s]=(u[i-1,s]+u[i+1,s]+u[i,s+1]+u[i,s-1])/4 return u2
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/50874007
has title: How to make for loop faster with numpy
downvote count: 1
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/50874565
has answer: http://stackoverflow.com/a/50874122
upvote count: 3
has answer: http://stackoverflow.com/a/50874565
answer count: 3
linked to: http://stackoverflow.com/q/50440592

http://stackoverflow.com/comment/88804411
score: 0
type: Comment
type: QuestionComment
has text: `num_points:` The shape is an integer. Representing how many classses you are sampling from each logits
comment on: http://stackoverflow.com/q/50901790

http://stackoverflow.com/a/50989364
upvote count: 4
answers question: http://stackoverflow.com/q/50989048
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: variable that you want to refer to is one_album but you are calling it album. change &lt;form action = "{% url 'music:favorite' album.id %}" method="post" &gt; to &lt;form action = "{% url 'music:favorite' one_album.id %}" method="post" &gt;
accepted answer of: http://stackoverflow.com/q/50989048
has comment: http://stackoverflow.com/comment/89016207
score: 4

http://stackoverflow.com/comment/88849221
comment on: http://stackoverflow.com/a/50924951
type: AnswerComment
score: 0
has text: so why don't you add a new statement elif not response.status_code == "409:" and in this case you take care of this case and write in the document that the data haven't been saved because duplicate?
type: Comment

http://stackoverflow.com/a/50959375
downvote count: 0
has body: I would suggest changing it in your Excel if you want to preserve what is being read in by openpyxl. That said, when a cell has been formatted to a date in Excel, it becomes altered to fit a specified format so you've lost the initial string format in either case. For example, let's say that the user enters the date 1/1/2018 into a cell that is formatted MM/DD/YYYY, Excel will change the data to 01/01/2018 and you will lose the original string that was entered. If you only care to see data of the form MM/DD/YYYY, an alternate solution would be to cast the date with date_cell.strftime("%m/%d/%Y")
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/88998389
has comment: http://stackoverflow.com/comment/89011298
has comment: http://stackoverflow.com/comment/88954878
answers question: http://stackoverflow.com/q/50959226

http://stackoverflow.com/a/50996992
score: 12
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: Here are some reasons which might be a cause of this behaviour With increasing no. of threads, there is an apparent overhead incurred for intializing and releasing each thread. I ran your code on my i7 7700HQ, I saw the following behaviour with each inceasing n_job when n_job=1 and n_job=2 the time per thread(Time per model evaluation by GridSearchCV to fully train the model and test it) was 2.9s (overall time ~2 mins) when n_job=3, time was 3.4s (overall time 1.4 mins) when n_job=4, time was 3.8s (overall time 58 secs) when n_job=5, time was 4.2s (overall time 51 secs) when n_job=6, time was 4.2s (overall time ~49 secs) when n_job=7, time was 4.2s (overall time ~49 secs) when n_job=8, time was 4.2s (overall time ~49 secs) Now as you can see, time per thread increased but overall time seem to decrease (although beyond n_job=4 the different was not exactly linear) and remained constained withn_jobs>=6` This is due to the fact that there is a cost incurred with initializing and releaseing threads. See this github issue and this issue. Also, there might be other bottlenecks like data being to large to be broadcasted to all threads at the same time, thread pre-emption over RAM (or other resouces,etc.), how data is pushed into each thread, etc. I suggest you to read about Ahmdal's Law which states that there is a theoretical bound on the speedup that can be achieved through parallelization which is given by the formula Image Source : Ahmdal's Law : Wikipedia Finally, it might be due to the data size and the complexity of the model you use for training as well. Here is a blog post explaining the same issue regarding multithreading.
answers question: http://stackoverflow.com/q/50993867
accepted answer of: http://stackoverflow.com/q/50993867
upvote count: 12

http://stackoverflow.com/comment/115481054
comment on: http://stackoverflow.com/q/50977636
has text: Does this answer your question? [Plotly Dash Share Callback Input in another page with dcc.Store](https://stackoverflow.com/questions/63490202/plotly-dash-share-callback-input-in-another-page-with-dcc-store)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50988051
has comment: http://stackoverflow.com/comment/88971255
has comment: http://stackoverflow.com/comment/88970974
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50985762
type: Answer
has comment: http://stackoverflow.com/comment/88971091
has comment: http://stackoverflow.com/comment/88970668
has body: You'd need to pass the address of the c_char pointer using byref: foo.argtypes = [..., POINTER(POINTER(c_char)), ...] foo.restype = c_int par_name_list = POINTER(c_char)() # pass by reference foo(byref(par_name_list)) par = cast(par_name_list, POINTER(c_char * MAX_PARAM_NAME)) You may need to free the memory afterwards.
accepted answer of: http://stackoverflow.com/q/50985762
upvote count: 1
has comment: http://stackoverflow.com/comment/88971206
has comment: http://stackoverflow.com/comment/88971562
score: 1

http://stackoverflow.com/q/50970977
answer count: 1
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/50971158
upvote count: 1
type: AnsweredQuestion
tagged with: python-packaging
score: 1
has title: How do I spell Python package/module imports for this situation?
type: Question
accepted answer: http://stackoverflow.com/a/50971158
has body: I have these Python files project/packages/foo/job.py project/packages/foo/models.py project/packages/foo/stuff/Thing.py models.py contains class Thing and Thing.py contains functions related to Thing job.py tries to do this: from . import models from . import stuff def job (): x = models.Thing (123) stuff.Thing.related_function (x) This yields an error: AttributeError: module 'foo.stuff' has no attribute 'Thing' I've tried variations on the import spellings but can't get it to work. I want to not bring Thing into the namespace, but always have to refer to it as models.Thing or stuff.Thing How do I do this?
downvote count: 0
has comment: http://stackoverflow.com/comment/88938594
has comment: http://stackoverflow.com/comment/88938691

http://stackoverflow.com/comment/88728659
type: Comment
has text: when i send request to this view
type: QuestionComment
comment on: http://stackoverflow.com/q/50858231
score: 0

http://stackoverflow.com/comment/88864983
has text: The decision is based on an entropy threshold or min. Threshold value that is fixed throughout the tree. Thats not possible. My point here is, any rule or property you set, is fixed throughout the tree.
comment on: http://stackoverflow.com/a/50914545
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/comment/88882626
type: Comment
type: QuestionComment
has text: `pyodbc` used to have issues with large `executemany()` batches, which `to_sql()` uses under the hood. The `fast_executemany` flag should solve that to some degree (>100x speedups).
comment on: http://stackoverflow.com/q/50940145
score: 0

http://stackoverflow.com/comment/88916503
has text: Likely a column given how it's referenced in the attempt
comment on: http://stackoverflow.com/q/50959624
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88853000
type: QuestionComment
comment on: http://stackoverflow.com/q/50926951
has text: Why does your last item only have one element, i.e. `['1979']`? Is this correct?
score: 0
type: Comment

http://stackoverflow.com/q/50922326
has comment: http://stackoverflow.com/comment/88844088
downvote count: 2
has comment: http://stackoverflow.com/comment/88843972
upvote count: 1
type: Question
has title: How to extract only the entries with values from a python dataframe after splitting it over comma
score: -1
has comment: http://stackoverflow.com/comment/88845255
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/88845313
answer count: 1
has comment: http://stackoverflow.com/comment/88844627
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88845086
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50924526
has body: How to extract only the entries with values from a python dataframe after splitting it over comma? In this example, for row 0 I want columns 1,2,3 but for row 1 I want columns 2,3,4, i.e. the three columns that I extract should be the last three entries of the dataframe row (excluding None) Here is what I did import pandas as pd import numpy as np from pathlib import Path filepath = Path("/home/anand/Downloads/Python Test/Python Test/data/input/test_addresses.csv") def extract_address_components(filepath): mms = pd.read_csv(filepath) mms.fillna(0, inplace=True) addr = mms['Address'].str.split(',', expand=True) mms['Locality'] = addr.apply(loca, axis=1) mms['City'] = addr.apply(cit, axis=1) mms['State'] = addr.apply(sta, axis=1) return mms def loca(x): if x.last_valid_index() is None: return np.nan else: return x[x.last_valid_index()-2] def cit(x): if x.last_valid_index() is None: return np.nan else: return x[x.last_valid_index()-1] def sta(x): if x.last_valid_index() is None: return np.nan else: return x[x.last_valid_index()] if __name__ == '__main__': mms = extract_address_components(filepath=filepath) mms.to_csv('/home/anand/Desktop/address_components.csv') Is there a better way using pandas?
tagged with: python
has comment: http://stackoverflow.com/comment/88844281
has comment: http://stackoverflow.com/comment/88845814
tagged with: jupyter-notebook

http://stackoverflow.com/a/50979153
answers question: http://stackoverflow.com/q/50928040
upvote count: 2
score: 2
downvote count: 0
has body: Yes, if you create your own Docker container you can use Tensorflow with Python 3. The default Tensorflow Dockerfiles are available here and you can modify them to suit your needs.
type: Answer

http://stackoverflow.com/q/51008481
tagged with: python
tagged with: python-requests
has title: Requests.get function not retrieving any data. What's wrong?
has comment: http://stackoverflow.com/comment/89009928
has body: Trying to loop through some license ids to get data from a website. Example: when I enter id "E09OS0018" in the search box, I get a list of one school/daycare. But when I type the following code in my python script (website link and arguments obtained from developer tools), I get no data in the file. What's wrong with this requests.get() command? If I should use requests.post() instead, what arguments would I use with the requests.post() command (not very familiar with this approach). flLicenseData = requests.get('https://cares.myflfamilies.com/PublicSearch/SuggestionSearch?text=E09OS0018&amp;filter%5Bfilters%5D%5B0%5D%5Bvalue%5D=e09os0018&amp;filter%5Bfilters%5D%5B0%5D%5Boperator%5D=contains&amp;filter%5Bfilters%5D%5B0%5D%5Bfield%5D=&amp;filter%5Bfilters%5D%5B0%5D%5BignoreCase%5D=true&amp;filter%5Blogic%5D=and') openFile = open('fldata', 'wb') for chunk in flLicenseData.iter_content(100000): openFile.write(chunk)
type: Question
has comment: http://stackoverflow.com/comment/89018821
has answer: http://stackoverflow.com/a/51008572
score: 0
answer count: 1
linked to: http://stackoverflow.com/q/7127075
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89045406
has comment: http://stackoverflow.com/comment/89012536
type: UnansweredQuestion

http://stackoverflow.com/q/50869441
tagged with: python
has comment: http://stackoverflow.com/comment/88740598
has answer: http://stackoverflow.com/a/50876958
type: AnsweredQuestion
tagged with: anaconda
linked to: http://stackoverflow.com/q/43592879
accepted answer: http://stackoverflow.com/a/50876958
tagged with: conda
type: Question
has title: Remember a different set of files in Spyder with different conda environments
answer count: 1
score: 0
tagged with: spyder
has body: I have spyder installed for different conda environments. Despite this, when I open any spyder for python 2.X I have the same source files open. The same goes for any spyder for python 3.X. I would like to have different source files open in spyder per every environment.

http://stackoverflow.com/q/50969381
has answer: http://stackoverflow.com/a/50969430
type: AnsweredQuestion
tagged with: dataframe
type: Question
upvote count: 4
accepted answer: http://stackoverflow.com/a/50969430
answer count: 1
downvote count: 0
tagged with: reindex
score: 4
favorite count: 0
has title: Moving index from one column to another in pandas data frame
has body: I get a DataFrame from a library with an index already set to one of the data columns. What would be the easiest way to set it to another column, preserving the original index column. Input: df = pd.DataFrame([[1,2,3],[4,5,6],[7,8,9]],columns=['a','b','c']) df = df.set_index('a') b c a 1 2 3 4 5 6 7 8 9 Output: (f.e. changing index from column a to column b) a c b 2 1 3 5 4 6 8 7 9
tagged with: pandas
tagged with: python

http://stackoverflow.com/q/50982287
tagged with: python
has answer: http://stackoverflow.com/a/51424194
downvote count: 0
score: 1
tagged with: tensorflow-serving
tagged with: tensorflow
has body: I am trying to send 3 dense matrices to a tensorflow-serving module. This module should take in 3 dense matrices and return a list of floats. I'm doing this in Python. I am having serious difficulty figuring out how to do this. I'm not sure how to send more than one piece of data at a time. I looked at this link and it looked like it would be helpful? https://www.tensorflow.org/serving/signature_defs But I'm not sure. I was previously looking at this website as a resource: https://towardsdatascience.com/deploy-tensorflow-models-9813b5a705d5 However, req_data = [{'in_tensor_name': 'inputs', 'in_tensor_dtype': 'DT_FLOAT', 'data': np.random.rand(1,2)}] prediction = client.predict(req_data, request_timeout=10) does not seem analogous to what I'm trying to do. Sorry if this question is pretty vague, but I have really no idea where to start. I have these 3 matrices, and apparently the model I'm sending these matrices to receives 3 matrices and outputs one list of numbers. How do I send and receive the data from this model? Thanks
type: Question
has title: Sending matrices to a Tensorflow-Serving module
has comment: http://stackoverflow.com/comment/112815199
upvote count: 1
answer count: 1
favorite count: 0
type: UnansweredQuestion

argparse
tags question: http://stackoverflow.com/q/50965583
tags question: http://stackoverflow.com/q/50870870
tags question: http://stackoverflow.com/q/50881403
tags question: http://stackoverflow.com/q/50944302
tags question: http://stackoverflow.com/q/50869939
tags question: http://stackoverflow.com/q/50896992
tag name: argparse
tags question: http://stackoverflow.com/q/50967625
tags question: http://stackoverflow.com/q/50998710
tags question: http://stackoverflow.com/q/50942501
tags question: http://stackoverflow.com/q/50886471
tags question: http://stackoverflow.com/q/50945208
type: Tag
tags question: http://stackoverflow.com/q/50916124

http://stackoverflow.com/comment/88725040
has text: It's because `Amazon` has already detected you as a bot and they do this in some different manners. Take a breather and run again then you should get the desired results. Thanks.
type: AnswerComment
comment on: http://stackoverflow.com/a/50860567
score: 0
type: Comment

http://stackoverflow.com/q/50861243
tagged with: scipy
type: Question
tagged with: feature-selection
upvote count: 2
downvote count: 1
has title: different chi2 value in sklearn and scipy.stats for the same contingency table
has body: X=np.array([7.20E+01,2.40E+01,0.00E+00,9.00E+00,0.00E+00,3.00E+00,0.00E+00,5.40E01,0.00E+00,0.00E+00,0.00E+00,0.00E+00,0.00E+00,0.00E+00,0.00E+00,0.00E+00,0.00E+00,0.00E+00,0.00E+00,0.00E+00,0.00E+00,3.00E+00,0.00E+00,0.00E+00,0.00E+00,0.00E+00,0.00E+00,0.00E+00,1.50E+01,0.00E+00,0.00E+00,0.00E+00,0.00E+00,0.00E+00,0.00E+00,0.00E+00,0.00E+00,0.00E+00,0.00E+00,1.11E+02,2.70E+01,0.00E+00,6.00E+00,0.00E+00,0.00E+00,0.00E+00,0.00E+00,0.00E+00,0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 3.00E+00, 0.00E+00, 0.00E+00, 1.70E+01, 3.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 8.00E+00, 5.20E+01, 1.80E+01, 5.20E+01, 5.20E+01, 5.00E+01, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00, 0.00E+00]) y=np.array([0.00E+00 0.00E+00 0.00E+00 0.00E+00 0.00E+00 0.00E+00 0.00E+00 0.00E+00 0.00E+00 0.00E+00 0.00E+00 0.00E+00 0.00E+00 0.00E+00 0.00E+00 0.00E+00 0.00E+00 0.00E+00 0.00E+00 0.00E+00 0.00E+00 0.00E+00 0.00E+00 0.00E+00 0.00E+00 0.00E+00 0.00E+00 0.00E+00 0.00E+00 0.00E+00 0.00E+00 0.00E+00 0.00E+00 0.00E+00 0.00E+00 0.00E+00 0.00E+00 0.00E+00 0.00E+00 0.00E+00 0.00E+00 0.00E+00 0.00E+00 0.00E+00 0.00E+00 0.00E+00 0.00E+00 0.00E+00 0.00E+00 0.00E+00 0.00E+00 0.00E+00 0.00E+00 0.00E+00 0.00E+00 0.00E+00 0.00E+00 0.00E+00 0.00E+00 0.00E+00 0.00E+00 0.00E+00 0.00E+…
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/88725724
favorite count: 0
has comment: http://stackoverflow.com/comment/88725848
has comment: http://stackoverflow.com/comment/88736438
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88725508
has comment: http://stackoverflow.com/comment/88725769
answer count: 0
has comment: http://stackoverflow.com/comment/88725903
score: 1
has comment: http://stackoverflow.com/comment/88743859
tagged with: machine-learning

http://stackoverflow.com/a/51017668
type: Answer
downvote count: 0
score: 5
answers question: http://stackoverflow.com/q/51006939
has body: with help by @ehsan-barkhordar this code wrote and it`s correct: import pykka import asyncio from flask import Flask from flask import request from balebot.handlers import * from balebot.filters import * from balebot.models.base_models import Peer from balebot.models.messages import * from balebot.updater import Updater updater = Updater(token="token", loop=asyncio.get_event_loop()) dispatcher = updater.dispatcher bale_bot = updater.bot def success(result, err): print("success : ", result) print("success : ", err) def failure(result, err): print("failure : ", result) @dispatcher.command_handler("/start") def start_command(bot, update): message = update.get_effective_message() bot.respond(update, message, success_callback=success, failure_callback=failure) app = Flask(__name__) class ServerActor(pykka.ThreadingActor): def __init__(self, flask_app): super(ServerActor, self).__init__() self.flask_app = flask_app def on_receive(self, message): print(message) def run(self): self.flask_app.run(host='0.0.0.0', port=5050) def shutdown_server(self): func = request.environ.get('werkzeug.server.shutdown') if func is None: raise RuntimeError('Not running with the Werkzeug Server') func() @app.route("/", methods=['GET']) def send_to_user(): message = "hello" m = TextMessage(message) bale_bot.send_message(m, Peer('User', "1533910422", "6644828719985087310"), success_callback=success, failure_callback=failure) return "message sent" # class SMStarter(): def start(notification_sender, server_actor_ref): server_proxy = server_actor_ref.proxy() future = server_proxy.run() notification_sender.run() notification_sender.stop() start(notification_sender=updater, server_actor_ref=ServerActor.start(flask_app=app))
upvote count: 5

http://stackoverflow.com/comment/89012172
score: 1
type: Comment
type: QuestionComment
has text: Can you post the code for DirectedGraph ? Is this a custom class you created ? What JSON format are you expecting ?
comment on: http://stackoverflow.com/q/51009717

seq2seq
tag name: seq2seq
type: Tag
tags question: http://stackoverflow.com/q/50886684

http://stackoverflow.com/a/51011075
type: Answer
downvote count: 0
score: 1
has body: QAction does not support styleSheet! You can use a QWidgetAction Try it: import sys from PyQt5.QtWidgets import * from PyQt5.QtCore import * from PyQt5.QtGui import * class MenuDemo(QMainWindow): def __init__(self,parent=None, *args): super().__init__(parent, *args) bar = self.menuBar() file = bar.addMenu('File') quit = bar.addMenu('Quit') open_action = QAction('Open', self) save_action = QWidgetAction(self) # &lt;------------------------ label = QLabel(" \n New \n") save_action.setDefaultWidget(label); save_action.setText('New') file.addAction(open_action) file.addAction(save_action) # ----- setStyleSheet --------------- self.setStyleSheet(""" QMenu { background-color: #ABABAB; border: 1px solid black; margin: 2px; } QMenu::item { background-color: transparent; padding: 20px 25px 20px 20px; } QMenu::item:selected { background-color: blue; } QLabel { background-color: yellow; color: red; font: 18px; } QLabel:hover { background-color: #654321; } """) quit.aboutToShow.connect(exit) file.triggered.connect(self.selected) self.setWindowTitle("Demo QWidgetAction") self.resize(300, 200) self.show() def selected(self, q): print('\n{} &lt;- selected -&gt; {}'.format(q.text(), q)) if __name__ == '__main__': app = QApplication(sys.argv) menus = MenuDemo() sys.exit(app.exec_())
answers question: http://stackoverflow.com/q/51004728
upvote count: 1

http://stackoverflow.com/q/50972464
tagged with: owlready
tagged with: python
has comment: http://stackoverflow.com/comment/88994592
has comment: http://stackoverflow.com/comment/88984150
has body: The ontology was created using protege and populated data from database using the owlready2 library. Now this line is giving this error: sync_reasoner(my_world) This is the error I have encountered: Could not parse ontology. Either a suitable parser could not be found, or parsing failed. See parser logs below for explanation. The following parsers were tried: 1) RDFXMLParser 2) OWLXMLParser 3) OWLFunctionalSyntaxOWLParser 4) TurtleOntologyParser 5) OWLOBOParser 6) KRSS2OWLParser 7) ManchesterOWLSyntaxOntologyParser Detailed logs: Parser: RDFXMLParser org.xml.sax.SAXParseException; systemId: file:///C:/Users/THARIN~2/AppData/Local/Temp/tmpin0r193y; lineNumber: 1; columnNumber: 8; Element type "http:" must be followed by either attribute specifications, "&gt;" or "/&gt;". -------------------------------------------------------------------------------- Parser: OWLXMLParser org.xml.sax.SAXParseException; systemId: file:///C:/Users/THARIN~2/AppData/Local/Temp/tmpin0r193y; lineNumber: 1; columnNumber: 8; Element type "http:" must be followed by either attribute specifications, "&gt;" or "/&gt;". -------------------------------------------------------------------------------- Parser: OWLFunctionalSyntaxOWLParser Encountered " &lt;FULLIRI&gt; "&lt;http://www.semanticweb.org/yashoda/ontologies/2017/12/MovieOnto&gt; "" at line 1, column 1. Was expecting: "Ontology" ... (Line 0) -------------------------------------------------------------------------------- Parser: TurtleOntologyParser uk.ac.manchester.cs.owl.owlapi.turtle.parser.ParseException: Encountered " &lt;ERROR&gt; "&lt; "" at line 64, column 1. Was expecting: &lt;EOF&gt; -------------------------------------------------------------------------------- Parser: OWLOBOParser org.coode.owlapi.obo.parser.ParseException: Encountered "&lt;EOF&gt;" at line 941, column 114. Was expecting one of: "[" ... &lt;TAG_NAME&gt; ... &lt;QUOTED_STRING&gt; ... &lt;STRING&gt; ... &lt;TAG_VALUE_WS&gt; ... &lt;COMMENT&gt; ... (Line 941) ---…
type: Question
has comment: http://stackoverflow.com/comment/89006514
tagged with: ontology
has answer: http://stackoverflow.com/a/51012802
has comment: http://stackoverflow.com/comment/88999237
has comment: http://stackoverflow.com/comment/89013841
tagged with: protege
tagged with: rdflib
score: 0
has comment: http://stackoverflow.com/comment/88999830
answer count: 1
has title: Owlready2 parsing error when calling sync_reasoner
has comment: http://stackoverflow.com/comment/88998483
has comment: http://stackoverflow.com/comment/89009469
type: UnansweredQuestion

http://stackoverflow.com/comment/88860082
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50929182
type: QuestionComment
has text: could u tell what is "uInput" in your ajax method, I think you are not passing the input values to the request.

http://stackoverflow.com/a/50902515
answers question: http://stackoverflow.com/q/50902416
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/93791535
upvote count: 3
has body: Try slicing the columns: import pandas as pd df = pd.read_csv("whatever.csv") df.loc[:,'col1':'col18'].sum(axis = 1)
downvote count: 1

http://stackoverflow.com/comment/88873055
has text: Thank you so much for explanation. There was a mistake in my solution
comment on: http://stackoverflow.com/a/50936051
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/88892717
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50947665
has text: You should create one bash script that takes the varying value as an argument.
score: 4

http://stackoverflow.com/a/50953378
has comment: http://stackoverflow.com/comment/88905596
has comment: http://stackoverflow.com/comment/88907059
has comment: http://stackoverflow.com/comment/88906694
has comment: http://stackoverflow.com/comment/88904790
type: Answer
has comment: http://stackoverflow.com/comment/88905680
downvote count: 0
has comment: http://stackoverflow.com/comment/88904922
score: 6
has comment: http://stackoverflow.com/comment/88905387
answers question: http://stackoverflow.com/q/50953131
accepted answer of: http://stackoverflow.com/q/50953131
upvote count: 6
has comment: http://stackoverflow.com/comment/88905893
type: AcceptedAnswer
has body: Not strictly a programming question, but here are the registry keys that are responsible for the context menu entries on Python files in the Windows Explorer. I've made an "Edit with IDLE" sub-menu as there are multiple versions of Python installed on my machine. (Disclaimer: This is hand-crafted and will not be removed automatically when you uninstall Python. You have to clean it up yourself.) Windows Registry Editor Version 5.00 [HKEY_CLASSES_ROOT\Python.File\shell\editwithidle] "MUIVerb"="&Edit with IDLE" "Subcommands"="" [HKEY_CLASSES_ROOT\Python.File\shell\editwithidle\shell] ; Python 2.7 ----------------------------------------------------------------------- [HKEY_CLASSES_ROOT\Python.File\shell\editwithidle\shell\edit27-32] "MUIVerb"="Edit with IDLE 2.7 (32-bit)" [HKEY_CLASSES_ROOT\Python.File\shell\editwithidle\shell\edit27-32\command] @="\"C:\\Python27\\pythonw.exe\" \"C:\\Python27\\Lib\\idlelib\\idle.pyw\" -e \"%1\"" ; Python 3.6 ----------------------------------------------------------------------- [HKEY_CLASSES_ROOT\Python.File\shell\editwithidle\shell\edit36-32] "MUIVerb"="Edit with IDLE 3.6 (32-bit)" [HKEY_CLASSES_ROOT\Python.File\shell\editwithidle\shell\edit36-32\command] @="\"C:\\Python36\\pythonw.exe\" -m idlelib \"%L\" %*" Of course change the paths according to your installation directories. Add/remove sections according to the installed Python versions. Then save as .reg file and import. Also note that I've picked sensible subkey names like edit36-32. It's not strictly required, these only need to be unique, but if I'm creating registry entries, I like them to contain what they say. So, adapt those accordingly. If you have only one Python version installed and never plan on getting a second installation, or if you like the menu entries in the top level instead of in a sub-menu: Windows Registry Editor Version 5.00 [HKEY_CLASSES_ROOT\Python.File\shell\editwithidle] @="Edit with IDLE 3.6 (32-bit)" [HKEY_CLASSES_ROOT\Python.File\shell\editwithidle\…

http://stackoverflow.com/comment/88789065
comment on: http://stackoverflow.com/q/50894326
has text: My `reply` variable contains header. Is that a problem ? Should I just send the html to browser ?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50905020
has body: I have changed my code and I hope that it is more clear now: NetMergeABC = [] for i in range(100): ActInA = Input(shape=(4,), dtype='int32') ActInB = Input(shape=(4,), dtype='int32') ActInC = Input(shape=(1,), dtype='int32') NetA = Dense(4, activation="relu")(ActInA) NetA = Dense(3, activation="relu")(NetA) NetB = Dense(4, activation="relu")(ActInB) NetB = Dense(3, activation="relu")(NetB) NetAB = concatenate([NetA, NetB]) NetAB = Dense(1, activation="relu")(NetAB) NetMergeABC.append(NetAB) NetMergeABC.append(ActInC) NetABC = concatenate(NetMergeABC) NetABC = Dense(10, activation="relu")(NetABC) NetABC = Dense(6, activation="relu")(NetABC) NetABC = Dense(4, activation="relu")(NetABC) NetABC = Dense(1, activation="relu")(NetABC) The problem now is, that (I guess) the weights of the NetA/B/C 1-100 arent shared.
has comment: http://stackoverflow.com/comment/88810967
type: Answer
answers question: http://stackoverflow.com/q/50876172
score: 0

http://stackoverflow.com/q/50932433
has comment: http://stackoverflow.com/comment/129137714
downvote count: 0
tagged with: scikit-learn
has body: I an using sklearn.feature_selection.chi2 for feature selection and found out some unexpected results (check the code). Do anyone knows what is the reason or can point me to some documentation or pull request? I include a comparison of the results I got and the expected ones obtained by hand and using scipy.stats.chi2_contingency. The code: import numpy as np import pandas as pd from scipy.stats import chi2_contingency from sklearn.feature_selection import chi2, SelectKBest x = np.array([[1, 1, 1, 0, 1], [1, 0, 1, 0, 0], [0, 0, 1, 1, 1], [0, 0, 1, 1, 0], [0, 0, 0, 1, 1], [0, 0, 0, 1, 0]]) y = np.array([1, 1, 2, 2, 3, 3]) scores = [] for i in range(x.shape[1]): result = chi2_contingency(pd.crosstab(x[:, i], y)) scores.append(result[0]) sel = SelectKBest(score_func=chi2, k=3) sel.fit(x, y) print(scores) print(sel.scores_) print(sel.get_support()) The results are: [6., 2.4, 6.0, 6.0, 0.0] (Expected) [4. 2. 2. 2. 0.] (Unexpected) [ True True False True False] Using scipy, it keeps features 0, 2, 3, while, with sklearn it keeps features 0,1,3.
has answer: http://stackoverflow.com/a/69842793
favorite count: 0
type: UnansweredQuestion
has title: Scipy and Sklearn chi2 implementations give different results
tagged with: machine-learning
tagged with: python
has comment: http://stackoverflow.com/comment/128518769
has comment: http://stackoverflow.com/comment/133883547
score: 3
has answer: http://stackoverflow.com/a/50936930
upvote count: 3
tagged with: scipy
type: Question
answer count: 2
tagged with: feature-selection

http://stackoverflow.com/comment/88957769
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50980455
type: Comment
has text: Just ran this @Dark. I was planning on keeping the dataset as is but it's not imperative. This works well.

http://stackoverflow.com/q/50925888
downvote count: 0
has comment: http://stackoverflow.com/comment/88851753
type: Question
has title: Installing pyodbc failed on Linux
score: 4
has body: I just run this command: sudo pip install pyodbc then I get below message and error: steven81@PythonWEBVM:~$ sudo pip install pyodbc The directory '/home/steven81/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. The directory '/home/steven81/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. Collecting pyodbc Downloading https://files.pythonhosted.org/packages/aa/71/cef225c4889620a1a00251d24c1746fe0cf4124290a75d1c2dc5c187b61f/pyodbc-4.0.23.tar.gz (215kB) 100% |████████████████████████████████| 225kB 13.5MB/s Installing collected packages: pyodbc Running setup.py install for pyodbc ... error Complete output from command /usr/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-install-NR7ytY/pyodbc/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-record-voJYBN/install-record.txt --single-version-externally-managed --compile: running install running build running build_ext building 'pyodbc' extension creating build creating build/temp.linux-x86_64-2.7 creating build/temp.linux-x86_64-2.7/src x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fno-strict-aliasing -Wdate-time -D_FORTIFY_SOURCE=2 -g -fstack-protector-strong -Wformat -Werror=format-security -fPIC -DPYODBC_VERSION=4.0.23 -I/usr/include/python2.7 -c src/pyodbcmodule.cpp -o build/temp.linux-x86_64-2.7/src/pyodbcmodule.o -Wno-write-strings cc1plus: warning: command line option ‘-Wstrict-prototypes’ is valid for C/ObjC but not for C++ In file included from src/pyodbcmodule.cpp:11:0: src/pyodbc.h:56:17: fatal error: sql.h: No …
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
upvote count: 4
has answer: http://stackoverflow.com/a/62291147
linked to: http://stackoverflow.com/q/45303870

http://stackoverflow.com/q/50948615
has comment: http://stackoverflow.com/comment/88894796
has body: My Model: class Mail(models.Model): subject = models.CharField(max_length=300) message = models.TextField() receiver = models.ForeignKey(User, related_name='receiver', on_delete=models.CASCADE) sender = models.ForeignKey(User, related_name='sender', on_delete=models.CASCADE) sent_date = models.DateTimeField(auto_now_add=True) conversation = models.ForeignKey(Conversation, on_delete=models.CASCADE) read = models.BooleanField(default=False) My query: Conversation.objects.filter(mail__receiver=request.user).annotate(latest_msg=Max('mail__id')).values('id','mail__id','mail__subject','mail__message','mail__sender__username','mail__sent_date','mail__read').order_by('-latest_msg') It returns all the Conversations which contains any Mail received by the logged user (request.user). Why? I want the last message received grouped by Conversations, like Gmail. Edited: Here's the native query: Query: SELECT "app_conversation"."id", "app_mail"."id", "app_mail"."subject", "app_mail"."message", T6."username", "app_mail"."sent_date", "app_mail"."read" FROM "app_conversation" INNER JOIN "app_mail" ON ("app_conversation"."id" = "app_mail"."conversation_id") INNER JOIN "app_user" T6 ON ("app_mail"."sender_id" = T6."id") WHERE "app_mail"."receiver_id" = 1 GROUP BY "app_conversation"."id", "app_conversation"."owner_id", "app_conversation"."user_id", "app_conversation"."create_date", "app_conversation"."archived", "app_mail"."id", "app_mail"."subject", "app_mail"."message", T6."username", "app_mail"."sent_date", "app_mail"."read" ORDER BY MAX("app_mail"."id") DESC
has comment: http://stackoverflow.com/comment/88894879
type: Question
has comment: http://stackoverflow.com/comment/88896891
has comment: http://stackoverflow.com/comment/88898023
accepted answer: http://stackoverflow.com/a/50981755
has title: Django query: the last Mail received grouped by Conversations
score: 0
answer count: 1
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/50981755
type: AnsweredQuestion

http://stackoverflow.com/q/50884217
tagged with: batch-file
tagged with: windows
score: 1
favorite count: 0
type: Question
has title: How can I set Windows "DPI-scaling overrides" via a script?
tagged with: python
answer count: 1
has answer: http://stackoverflow.com/a/53665872
upvote count: 1
downvote count: 0
tagged with: wxpython
type: UnansweredQuestion
has body: We have a Python-based application with a WxPython GUI that we create for multiple operating systems. In Windows 10, at least in my environment (inside a VM on a high resolution monitor), the text elements in the interface are blurry. I can improve the appearance by setting the Windows application DPI-scaling override. However, the only way I have found so far is to do it manually from the Windows file explorer interface. My question: Is there a way to set this property from the command line, so that I can script this as part of building our application?
tagged with: dpi

http://stackoverflow.com/comment/88760334
type: QuestionComment
comment on: http://stackoverflow.com/q/50877963
has text: @scharette - Added the tag. And there isn't a problem, it just seems like there should be a better way.
score: 0
type: Comment

http://stackoverflow.com/comment/88754733
type: QuestionComment
has text: got it need to add this config in $.ajax contentType: 'application/json; charset=utf-8',
comment on: http://stackoverflow.com/q/50875335
score: 0
type: Comment

http://stackoverflow.com/q/50994746
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50994811
score: 3
has body: The problem is a little hard to explain with just the title. I have a huge list of dictionaries, dict_list, about 18k long. One of the keys on each of them is "PROCESS". The processes are "Etch" and "Depo", and each will repeat for a bit, then change to the other, and back. These are called "runs". I need to group similar processes together into a list, until the process changes, then insert that list into a "runs" dictionary. Here is a better visual explanation: dict_list = [{"PROCESS": "Etch"},{"PROCESS": "Etch"},{"PROCESS": "Etch"}, {"PROCESS": "Etch"},{"PROCESS": "Etch"},{"PROCESS": "Etch"}, {"PROCESS": "Etch"},{"PROCESS": "Etch"},{"PROCESS": "Etch"}, {"PROCESS": "Etch"},{"PROCESS": "Etch"},{"PROCESS": "Etch"}, {"PROCESS": "Etch"},{"PROCESS": "Etch"},{"PROCESS": "Etch"}, {"PROCESS": "Depo"},{"PROCESS": "Depo"},{"PROCESS": "Depo"}, {"PROCESS": "Depo"},{"PROCESS": "Depo"},{"PROCESS": "Depo"}, {"PROCESS": "Depo"},{"PROCESS": "Depo"},{"PROCESS": "Depo"}, {"PROCESS": "Depo"},{"PROCESS": "Depo"},{"PROCESS": "Depo"}, {"PROCESS": "Depo"},{"PROCESS": "Depo"},{"PROCESS": "Depo"}, {"PROCESS": "Etch"},{"PROCESS": "Etch"},{"PROCESS": "Etch"}, {"PROCESS": "Etch"},{"PROCESS": "Etch"}] Basically, if I loop over dict_list, printing each "PROCESS" line by line, it would look like: &gt;&gt;"Etch" &gt;&gt;"Etch" &gt;&gt;"Etch" &gt;&gt;"Etch" &gt;&gt;"Depo" &gt;&gt;"Depo" &gt;&gt;"Depo" &gt;&gt;"Depo" &gt;&gt;"Etch" &gt;&gt;"Etch" &gt;&gt;"Etch" &gt;&gt;"Etch" &gt;&gt;"Depo" &gt;&gt;"Depo" &gt;&gt;"Depo" &gt;&gt;"Depo" For that example I would have 4 "runs" dictionaries, each with a list of 4 dictionaries. I would need to group them into lists and then into dictionaries like such: new_dict_list = { "run 1": [{"PROCESS": "Etch"},{"PROCESS": "Etch"},{"PROCESS": "Etch"},{"PROCESS": "Etch"},{"PROCESS": "Etch"},{"PROCESS": "Etch"},{"PROCESS": "Etch"},{"PROCESS": "Etch"},{"PROCESS": "Etch"},{"PROCESS": "Etch"},{"PROCESS": "Etch"},{"PROCESS": "Etch"},{"PROCESS": "Etch"},{"PROCESS": "Etch"}…
answer count: 1
favorite count: 0
downvote count: 1
tagged with: python
tagged with: dictionary
upvote count: 4
has title: Break list of dictionaries into dictionaries for common elements
tagged with: list
accepted answer: http://stackoverflow.com/a/50994811

http://stackoverflow.com/comment/89003979
type: QuestionComment
has text: Also see this forum posting https://github.com/Microsoft/vscode-cpptools/issues/2079 as well as https://github.com/explosion/spaCy/issues/2441 as well as https://blogs.msdn.microsoft.com/vcblog/2015/11/02/announcing-visual-c-build-tools-2015-standalone-c-tools-for-build-environments/
comment on: http://stackoverflow.com/q/51005141
score: 0
type: Comment

http://stackoverflow.com/comment/89149621
type: Comment
has text: look at `Update-1`
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50924550

polynomial-math
tags question: http://stackoverflow.com/q/51003899
type: Tag
tag name: polynomial-math

http://stackoverflow.com/comment/89003167
type: QuestionComment
has text: If you `addAtHead()` on an empty list (`current is None`) you never assign a new value to the list.
comment on: http://stackoverflow.com/q/51004401
score: 0
type: Comment

http://stackoverflow.com/comment/89276118
type: QuestionComment
has text: Thanks. I see that I am miss using the while loop by trying to nest them. Ultimately, I want the program to be "listening" for a mouse click in both windows at the same time.
score: 0
comment on: http://stackoverflow.com/q/50979719
type: Comment

http://stackoverflow.com/a/50952494
type: Answer
answers question: http://stackoverflow.com/q/50950575
score: 0
has body: this is how I interpreted the code delivered by Taohidul Islam: might be right? recursion

http://stackoverflow.com/a/50867500
answers question: http://stackoverflow.com/q/50867435
has comment: http://stackoverflow.com/comment/130113748
has body: subnet is simply a binary mask that must be and'ed bitwise with the IP address. You can apply the mask yourself: ".".join(map(str, [i &amp; m # Apply the mask for i,m in zip(map(int, ip.split(".")), map(int, subnet.split(".")))])) #'192.178.2.0' This solution works only for IPv4 addresses.
score: 5
has comment: http://stackoverflow.com/comment/130114761
upvote count: 5
has comment: http://stackoverflow.com/comment/130140448
downvote count: 0
type: Answer

http://stackoverflow.com/comment/88818249
type: QuestionComment
comment on: http://stackoverflow.com/q/50908642
has text: if I have an update view for this model as well, can it trigger my post_save?
score: 0
type: Comment

http://stackoverflow.com/comment/88729739
type: AnswerComment
has text: If you are having trouble getting my example to run, you can see it running at: https://repl.it/repls/VastMistyProcess. I added a loop there. Nothing will print if there are no combinations to work with.
type: Comment
comment on: http://stackoverflow.com/a/50863086
score: 0

http://stackoverflow.com/comment/132801207
score: 0
type: AnswerComment
type: Comment
has text: re `has_schema`: `NotImplementedError: This method is not implemented for SQLAlchemy 2.0.`
comment on: http://stackoverflow.com/a/55345404

http://stackoverflow.com/comment/88910511
comment on: http://stackoverflow.com/q/50956456
has text: What *does* the program do? "does not work at all" is not a problem specification.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/59642060
has body: The Below is to Find the radius and circumference of circle # Name Name = raw_input("Enter Your Name: ") # Give area for the circle Area = input("Enter Area of the circle: ") PI = 3.14 # Calculation of radius and circumference R = (Area / PI )**0.5 C = (2 * PI * R) print "Area of the Circle = %.2f"%Area print "Radius of Circle = %.2f"%R print "Circumference of Circle = %.2f"%C
type: Answer
has comment: http://stackoverflow.com/comment/105445910
answers question: http://stackoverflow.com/q/50925390
score: 0

http://stackoverflow.com/q/50969917
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88936917
has title: Unexpected character after line continuation character error when i try to print
has body: I'm trying to make a calculator visual interface with text characters but when i try to print the lines I get this error. L1="┏━━━━━━━━━━━━━━━━━┓\n┃ ┏━━━━━━━━━━━━━┓ ┃" LS=" " LL="┃ ┃" L2="┃ ┣━━━━━━━━━━━━━┫ ┃\n┃ ┣━┳━┳━┳━━━┳━━━┫ ┃\n┃ ┃7┃8┃9┃DEL┃A.C┃ ┃" L3="┃ ┣━╋━╋━╋━━━╋━━━┫ ┃\n┃ ┃4┃5┃6┃ x ┃ ÷ ┃ ┃\n┃ ┣━╋━╋━╋━━━╋━━━┫ ┃" L4="┃ ┃1┃2┃3┃ + ┃ - ┃ ┃\n┃ ┣━╋━╋━╋━━━╋━━━┫ ┃\n┃ ┃0┃.┃ ┃ANS┃ = ┃ ┃" L5="┃ ┗━┻━┻━┻━━━┻━━━┛ ┃\n┗━━━━━━━━━━━━━━━━━┛" print(L1,\nLL,LS,LL,\nLL,LS,LL,\nL2,\nL3,\nL4,\nL5) this is what my code looks like and idk how to fix it, any help would be greatly appreciated :)
has comment: http://stackoverflow.com/comment/88936284
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/50969983
score: -1
answer count: 2
has answer: http://stackoverflow.com/a/50970019
upvote count: 0

http://stackoverflow.com/a/50901588
type: Answer
score: 4
has body: You can use os to list all of the files. Then just construct a DataFrame and use the string methods to get the parts of the filenames you need. import pandas as pd import os path = 'path to the saved txt files/fldr' file_list = os.listdir(path) df = pd.DataFrame(file_list, columns=['file_name']) df['data'] = df.file_name.str[0:8] df['date'] = df.file_name.str.extract('(\d{4}-\d{2}-\d{2})', expand=True) file_name data date 0 09066271_142468576_1_Haha_-Haha-haha_2016-10-0... 09066271 2016-10-07 1 09014271_142468576_1_Haha_-Haha-haha_2013-02-1... 09014271 2013-02-18
upvote count: 4
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50901525
accepted answer of: http://stackoverflow.com/q/50901525

http://stackoverflow.com/q/50984829
has answer: http://stackoverflow.com/a/57149826
has body: I have successfully created a webhook in stackstorm and it is visible in the webhook lists. [centos@ip- ~]$ sudo st2 webhook list +------------+------------------+-------------+ | url | type | description | +------------+------------------+-------------+ | wfcreation | core.st2.webhook | | +------------+------------------+-------------+ [centos@ip- ~]$ I triggered the webhook giving a payload and setting proper headers using stackstorm api key. The webhook gets triggered and returns with a status code of 200. But the underlying stackstorm workflow fails giving the below error. { "traceback": " File \"/opt/stackstorm/st2/lib/python2.7/site-packages/st2actions/container/base.py\", line 119, in _do_run (status, result, context) = runner.run(action_params) File \"/opt/stackstorm/st2/lib/python2.7/site-packages/retrying.py\", line 49, in wrapped_f return Retrying(*dargs, **dkw).call(f, *args, **kw) File \"/opt/stackstorm/st2/lib/python2.7/site-packages/retrying.py\", line 206, in call return attempt.get(self._wrap_exception) File \"/opt/stackstorm/st2/lib/python2.7/site-packages/retrying.py\", line 247, in get six.reraise(self.value[0], self.value[1], self.value[2]) File \"/opt/stackstorm/st2/lib/python2.7/site-packages/retrying.py\", line 200, in call attempt = Attempt(fn(*args, **kwargs), attempt_number, False) File \"/opt/stackstorm/runners/mistral_v2/mistral_v2/mistral_v2.py\", line 247, in run result = self.start_workflow(action_parameters=action_parameters) File \"/opt/stackstorm/runners/mistral_v2/mistral_v2/mistral_v2.py\", line 284, in start_workflow **options) File \"/opt/stackstorm/st2/lib/python2.7/site-packages/mistralclient/api/v2/executions.py\", line 65, in create return self._create('/executions', data) File \"/opt/stackstorm/st2/lib/python2.7/site-packages/mistralclient/api/base.py\", line 100, in _create self._raise_api_exception(resp) File \"/opt/stackstorm/st2/lib/python2.7/site-packages/mistralclient/api/base.py\", line 160, in _raise_api_exception …
type: UnansweredQuestion
type: Question
has title: Stackstorm 2.7 webhook "AccessRefused: 403" error
answer count: 2
tagged with: webhooks
tagged with: python
score: 0
has answer: http://stackoverflow.com/a/51038249

http://stackoverflow.com/comment/88860644
type: AnswerComment
has text: You need to use `-o example.json`
comment on: http://stackoverflow.com/a/50927153
score: 0
type: Comment

http://stackoverflow.com/q/50965533
score: 1
type: Question
has body: Jython is an implementaion of python. Is there any way to find the version of python that is being supported by a particular jython jar. eg: Few posts in the web say that Jython 2.5 supports python 2.5 Similarly I want to know the jython version that supports python 2.7.14 or more. It would be helpful if the version mapping can be referred to in any user-guides or pages.
tagged with: jython
downvote count: 0
tagged with: jython-2.7
tagged with: python-2.7
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/89010823
answer count: 0
type: UnansweredQuestion
has title: jython to python version mapping
upvote count: 1
has comment: http://stackoverflow.com/comment/100964750

http://stackoverflow.com/comment/88859340
has text: Camera behaviour is managed by "interactor style" of the vtkRenderWindowInteractor (called "iren" in your code), you can get it/set it through iren.GetInteractorStyle. The default i think is vtkInteractorStyleTrackballCamera (https://www.vtk.org/doc/nightly/html/classvtkInteractorStyleTrackballCamera.html). You can try looking at all the derived classes from vtkInteractorStyle (https://www.vtk.org/doc/nightly/html/classvtkInteractorStyle.html) if you find one that you like better or create your own one that behaves the way you want and than set it by iren.SetInteractorStyle.
comment on: http://stackoverflow.com/a/50911165
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50919315
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50922122
has title: pygame adding images to the player class
type: Question
has body: I am having some trouble adding images to my classes. I would like to have my player be a cartoon character but I do not want animations. I just want the player to be a still image. I tried loading a png file and setting the self.image= to the file but that did not work. Thanks for the help! My code can be found here https://gist.github.com/eddison12345/0c55cc5e0af93854582f1c972b55fc31 class Player(pygame.sprite.Sprite): def __init__(self,X,Y,W,H): pygame.sprite.Sprite.__init__(self) self.image=pygame.image.load("PlayerOne.png") self.rect=self.image.get_rect() self.X=X self.Y=Y self.W=W self.H=H self.rect=pygame.Rect(self.X,self.Y,self.H,self.W) self.objectVy=0 self.RUN_SPEED= 10 self.JUMP_SPEED=5 self.GRAVITY=2 self.GROUND=600 self.RED=RED def draw(self,screen): pygame.draw.rect(screen, self.RED, self.rect) def redrawGameWindow(): screen.fill(BLACK) player1.draw(screen) #DRAWING THE PLAYER pygame.display.update()
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/88839384
has comment: http://stackoverflow.com/comment/88839305
has comment: http://stackoverflow.com/comment/88839133
tagged with: python
tagged with: pygame

http://stackoverflow.com/q/50980410
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/50980465
score: 0
linked to: http://stackoverflow.com/q/50979760
accepted answer: http://stackoverflow.com/a/50980465
answer count: 1
favorite count: 0
duplicate of: http://stackoverflow.com/q/50979760
tagged with: python-3.x
has title: dot product of two vectors in python 3 with out using the sum or zip function
has body: I'm writing a code that checks that the length of two vectors matches and if so it computes the dot product of the two vectors. I'm getting the vector multiplication as my output but I need to sum them to obtain the dot product. I do not want to use the sum function to do so any help would be greatly appreciated. Thank you in advance. def dot(vector01,vector02): result= [] if len(vector01) != len(vector02): raise ValueError for i in range(len(vector01)): total = 0 total += vector01[i] * vector02[i] result.append(total) return result vector01 = [2, 3, 4] vector02 = [4, 2, 1] print(dot(vector01,vector02))
tagged with: python
type: AnsweredQuestion
upvote count: 1

http://stackoverflow.com/comment/88970271
score: 0
has text: Have you thought about finding contours (cv2.findcontours) and filter your contours out with convexity criterion or size criterion (to eliminate squares) and then resizing the contour (multiply the list of points) and finally drawing them on a new image mask.
comment on: http://stackoverflow.com/q/50985319
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50871364
has comment: http://stackoverflow.com/comment/88746456
tagged with: pip
tagged with: python
tagged with: pylibmc
type: AnsweredQuestion
downvote count: 0
score: 1
has title: I can't install pylibmc in virtual enviroment with Python 3.4.0
accepted answer: http://stackoverflow.com/a/50872473
type: Question
has body: First of all I use Ubuntu 17.10 and I downloaded previous version of python - python 3.4.0 because this older version is required in my project. I installed both memcached and libmemcached-dev and I can install without issues pylibmc in virtual env based on python 3.6.3. However during installing pylibmc in enviroment based on Python 3.4.0 I get erros: Collecting pylibmc==1.5.1 (from -r requirements.txt (line 2)) Using cached https://files.pythonhosted.org/packages/23/f4/3904b7171e61a83eafee0ed3b1b8efe4d3c6ddc05f7ebdff1831cf0e15f1/pylibmc-1.5.1.tar.gz Building wheels for collected packages: pylibmc Running setup.py bdist_wheel for pylibmc ... error Complete output from command /home/przemek/usosApi34/bin/python3.4 -u -c "import setuptools, tokenize;__file__='/tmp/pip-install-859hcscx/pylibmc/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d /tmp/pip-wheel-_u6qlw_7 --python-tag cp34: running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-3.4 creating build/lib.linux-x86_64-3.4/pylibmc copying src/pylibmc/__main__.py -&gt; build/lib.linux-x86_64-3.4/pylibmc copying src/pylibmc/__init__.py -&gt; build/lib.linux-x86_64-3.4/pylibmc copying src/pylibmc/client.py -&gt; build/lib.linux-x86_64-3.4/pylibmc copying src/pylibmc/consts.py -&gt; build/lib.linux-x86_64-3.4/pylibmc copying src/pylibmc/test.py -&gt; build/lib.linux-x86_64-3.4/pylibmc copying src/pylibmc/pools.py -&gt; build/lib.linux-x86_64-3.4/pylibmc running build_ext building '_pylibmc' extension creating build/temp.linux-x86_64-3.4 creating build/temp.linux-x86_64-3.4/src gcc -pthread -Wno-unused-result -Werror=declaration-after-statement -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -DUSE_ZLIB -I/home/przemek/opt/python-3.4.0/include/python3.4m -c src/_pylibmcmodule.c -o build/temp.linux-x86_64-3.4/src/_pylibmcmodule.o -fno-strict-aliasing -std=c99 src/_pyl…
has answer: http://stackoverflow.com/a/50872473
has comment: http://stackoverflow.com/comment/88746142
has comment: http://stackoverflow.com/comment/88746309
upvote count: 1
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88746418

http://stackoverflow.com/comment/88783313
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50891167
has text: Which window are you talking about?
score: 0

http://stackoverflow.com/a/50868636
downvote count: 0
has comment: http://stackoverflow.com/comment/88742578
has body: There is a better explanation here: KalmanFilter always predict 0,0 in first time The Kalman filter implementation of opencv doesn't let you set an initial state. This is not intuitive and the lack of documentation makes things even worse. The way to circumvent this problem is to override the kalman.correct and kalman.predict methods. You set an initial value of the variable you want to work with and every time you call correct, you first subtract the initial value. When you call predict, you have to add the initial value. I have an implementation example here where the Kalman filter is used in an visual tracking problem (tracking car chased by police): https://github.com/fredguth/unb-cv-3183/blob/master/p6/r4.py
type: Answer
has comment: http://stackoverflow.com/comment/89632287
has comment: http://stackoverflow.com/comment/88783369
has comment: http://stackoverflow.com/comment/88743705
upvote count: 3
answers question: http://stackoverflow.com/q/50863397
score: 3

http://stackoverflow.com/comment/88894696
type: Comment
comment on: http://stackoverflow.com/a/50948598
has text: Does this only work for variations at the end of the sequence? Perhaps I should have been more explicit about it, but the difference can be anywhere in the string.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/88968250
has text: @brunodesthuilliers, thx! i agree with you
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50986578
type: Comment

http://stackoverflow.com/a/50902971
has body: When the parameters to do_a_thing are evaluated, there is no reference to self. That is why it is not working. You need to use the common default argument pattern, like this class Foo: def __init__(self, bar): self.bar = bar def do_a_thing(self, my_arg=None): if my_arg is None: my_arg = self.bar do_something_else(my_arg)
downvote count: 0
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/50902933

http://stackoverflow.com/comment/88985777
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50995581
has text: No. The number of digits can be anything (e.g. 51) and the number of factorials can also be anything. E.g. `"51!/50!"` is a possibility.
score: 0

class
tags question: http://stackoverflow.com/q/50964304
tags question: http://stackoverflow.com/q/50872410
tags question: http://stackoverflow.com/q/50916006
tags question: http://stackoverflow.com/q/50869654
tags question: http://stackoverflow.com/q/50891514
tags question: http://stackoverflow.com/q/50939773
tags question: http://stackoverflow.com/q/50980735
tags question: http://stackoverflow.com/q/50969736
tags question: http://stackoverflow.com/q/50936747
tags question: http://stackoverflow.com/q/50925583
tags question: http://stackoverflow.com/q/51002998
tags question: http://stackoverflow.com/q/50970783
tags question: http://stackoverflow.com/q/50883923
tags question: http://stackoverflow.com/q/51005837
tags question: http://stackoverflow.com/q/50903390
tags question: http://stackoverflow.com/q/50964041
tags question: http://stackoverflow.com/q/50951284
tags question: http://stackoverflow.com/q/50890416
tags question: http://stackoverflow.com/q/50887512
tags question: http://stackoverflow.com/q/50864772
tags question: http://stackoverflow.com/q/50927915
type: Tag
tags question: http://stackoverflow.com/q/50901470
tags question: http://stackoverflow.com/q/50869093
tags question: http://stackoverflow.com/q/50909641
tags question: http://stackoverflow.com/q/50981037
tags question: http://stackoverflow.com/q/50955336
tag name: class
tags question: http://stackoverflow.com/q/50994373
tags question: http://stackoverflow.com/q/50940542
tags question: http://stackoverflow.com/q/50995225
tags question: http://stackoverflow.com/q/50954306
tags question: http://stackoverflow.com/q/50935345
tags question: http://stackoverflow.com/q/50999001
tags question: http://stackoverflow.com/q/50958699
tags question: http://stackoverflow.com/q/50911128
tags question: http://stackoverflow.com/q/50863152
tags question: http://stackoverflow.com/q/50957382
tags question: http://stackoverflow.com/q/50991142

http://stackoverflow.com/comment/88718837
has text: you seem to have answered the question yourself, as noted by @Kevin. if you want you can additinaly [check the types](https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertIsInstance) and fail tests, if there is a mismatch
comment on: http://stackoverflow.com/q/50857927
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50988462
tagged with: cdf
downvote count: 0
answer count: 1
favorite count: 0
has title: CDF of a multivariate Normal in Tensorflow
accepted answer: http://stackoverflow.com/a/51218340
tagged with: python
has body: I want to evaluate the cdf of a multivariate normal distribution using tensorflow. What I have tried so far: import tensorflow as tf ds = tf.contrib.distributions # Initialize a single 3-variate Gaussian. mu = [0., 0., 0.] cov = [[ 0.36, 0.12, 0.06], [ 0.12, 0.29, -0.13], [ 0.06, -0.13, 0.26]] mvn = ds.MultivariateNormalFullCovariance( loc=mu, covariance_matrix=cov) value = tf.constant([0., 0., 0.]) with tf.Session() as sess: print mvn.cdf(value).eval() This yields the error: NotImplementedError: cdf is not implemented when overriding event_shape I don't understand why I am overriding the event_shape since event_shape and the shape of value are the same. What am I doing wrong?
upvote count: 2
tagged with: tensorflow
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51218340
type: Question

http://stackoverflow.com/comment/89149812
type: QuestionComment
comment on: http://stackoverflow.com/q/50881468
has text: Are you doing a Softmax?
score: 0
type: Comment

http://stackoverflow.com/q/50875816
has title: Django timedelta (DurationField) to seconds
type: Question
has body: How to convert a timedelta to seconds in Django? I have a Django backed serving an API which at some point returns a calculated field: enhanced_client = client.objects.annotate(duration=ExpressionWrapper((F('end_time')-F('start_time')), output_field=DurationField())) with the following value (timedelta): P0DT00H02M00.102730S How can I turn this into seconds in javascript? I'm also using moment js but I can't parse this at all. Thanks
tagged with: django-models
upvote count: 2
answer count: 1
tagged with: timedelta
favorite count: 0
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/50875879
accepted answer: http://stackoverflow.com/a/50875879
tagged with: momentjs
score: 2
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/comment/88871939
comment on: http://stackoverflow.com/q/50929322
type: Comment
type: QuestionComment
score: 0
has text: Doe you know if this support HTTPS with Client Authentication using a Certificate?

http://stackoverflow.com/comment/88815862
type: Comment
has text: Just put a link to the question here, and I'll see it.
comment on: http://stackoverflow.com/a/50856918
type: AnswerComment
score: 0

http://stackoverflow.com/q/50953074
tagged with: pandas
type: AnsweredQuestion
downvote count: 0
favorite count: 0
tagged with: python-3.x
type: Question
tagged with: python
score: 4
has answer: http://stackoverflow.com/a/50953338
has body: I have the following strange error with pandas(pandas==0.23.1) : import pandas as pd df = pd.DataFrame({'t1': ["a","b","c"]*10000, 't2': ["x","y","z"]*10000, 'i1': list(range(5000))*6, 'i2': list(range(5000))*6, 'dummy':0}) # works fast with less memory piv = df.pivot_table(values='dummy', index=['i1','i2'], columns=['t1','t2']) d2 = df.copy() d2.t1 = d2.t1.astype('category') d2.t2 = d2.t2.astype('category') # needs &gt; 20GB of memory and takes for ever piv2 = d2.pivot_table(values='dummy', index=['i1','i2'], columns=['t1','t2']) I am wondering if this is expected and I am doing something wrong, or if this is a bug in pandas. Should dtype category for str not be very transparent (for this use case)?
answer count: 1
linked to: http://stackoverflow.com/q/48471648
has title: pivot_table requires more memory if dtype is category (MemoryError)
tagged with: dataframe
upvote count: 4
accepted answer: http://stackoverflow.com/a/50953338

http://stackoverflow.com/comment/88741380
type: AnswerComment
has text: Thanks for the suggestion. However this seems to me like a hacky workaround as well. Isn't there a more simple/ straight forward approach to this general problem?
type: Comment
comment on: http://stackoverflow.com/a/50859789
score: 0

http://stackoverflow.com/comment/89027316
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50997574
has text: I haven't realized that. Simple but important point. Tesekkurler

http://stackoverflow.com/q/50970504
answer count: 1
tagged with: google-cloud-sql
has answer: http://stackoverflow.com/a/52997928
tagged with: python
has title: RuntimeError: OperationalError: (2003, Can't connect to MySQL server on 'IPaddress of the instance'
type: UnansweredQuestion
tagged with: mysql
type: Question
tagged with: google-cloud-dataflow
linked to: http://stackoverflow.com/q/50701736
score: 0
has body: I'm trying to run a Python(version 2.7.1') script where I am using pymysql package to create a table into a database from a CSV file. It runs correctly in my local system, however, the problem appears when running the same script as a part of a pipeline in Google Cloud Dataflow. My Python function is the following one: class charge_to_db(beam.DoFn): def process(self, element): import pymysql with open(element, 'r') as f: data = f.read().decode("UTF-8") datalist = [] for line in data.split('\n'): datalist.append(line.split(',')) db = pymysql.connect(host='IPaddress', user='root', password='mypassword', database='stack_model') cursor = db.cursor() cursor.execute("DROP TABLE IF EXISTS stack_convergence") # create column names from the first line in fList up = "upper_bnd" primal = "primal" d = "dualit" gap = "gap_rel" teta = "teta" alpha = "alpha" imba = "imba_avg" price = "price_avg" # create STUDENT table // place a comma after each new column except the last queryCreateConvergenceTable = """CREATE TABLE stack_convergence( {} float not null, {} float not null, {} float not null, {} float not null, {} float not null, {} float not null, {} float not null, {} float not null )""".format(up, primal, d, gap, teta, alpha, imba, price) cursor.execute(queryCreateConvergenceTable) When running this function in the cloud I'm obtaining the following error: RuntimeError: OperationalError: (2003, 'Can\'t connect to MySQL server on \'35.195.1.40\' (110 "Connection timed out")') I don't know why this error is occurring because it runs correctly in local system, so from the local system I have access to my cloud SQL instance, but not from the dataflow in the cloud. Why is this error occurring?
tagged with: google-cloud-platform

http://stackoverflow.com/a/50949906
upvote count: 2
type: Answer
has body: It seems fine, the only thing I can think of is you can use a tuple in isinstance, so isinstance(x, (str, dict)) does the same thing as the isinstance(x, str) or isinstance(x, dict).
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50949766
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50949766

http://stackoverflow.com/q/51005547
has comment: http://stackoverflow.com/comment/89004619
favorite count: 0
tagged with: beautifulsoup
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/html
tagged with: python
score: 2
downvote count: 0
has body: I am trying to parse this html web page and I want specific data within the web page. I am using the findall function on this specific class. The only problem is that it is picking up unnecessary data on the side of the web site due to conflicting classes. I basically want to do a findall on div classes that contain "mainContent" and the item class name. I have only found how to find classes that contain "blank" or "blank". What would be the syntax of trying to find something that had a class name of "blank" and "blank"? Thank you!
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/51005680
answer count: 1
has title: BeautifulSoup finding data with two different div classes

http://stackoverflow.com/comment/88852921
has text: No, sorry, even if I do this: CAM = [] CAM.append({{'camera_id': data.camera_id, 'point':[ {'x':data.x}, {'y':data.y}], 'secs': data.stamp.secs, 'nsecs': data.stamp.nsecs}}) it is printing like [{}][{}][{}][{}][{}] and not [{},{},{},{},{},{},{}]
comment on: http://stackoverflow.com/a/50909847
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/50953092
answer count: 1
downvote count: 0
tagged with: neural-network
favorite count: 0
has body: I was training my network using tf.losses.sparse_softmax_cross_entropy as the classification function in the last layer and everything was working fine. I simply added a L2 regularization over my weights now and my loss is not getting optimized anymore. What can be happening? reg = tf.nn.l2_loss(w1) + tf.nn.l2_loss(w2) loss = tf.reduce_mean(tf.losses.sparse_softmax_cross_entropy(y, logits)) + reg*beta train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss)
has comment: http://stackoverflow.com/comment/88905703
tagged with: python
type: UnansweredQuestion
score: 1
upvote count: 1
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/50955996
tagged with: loss-function
has title: Optimize sparse softmax cross entropy with L2 regularization

http://stackoverflow.com/a/50887849
answers question: http://stackoverflow.com/q/50887493
upvote count: 1
has body: It seems the problem is caused by having string objects in your df["price"]. This can be solved by converting it to float prior to plotting it. plt.plot(df['date'],df['price'].astype('float')) Or even before doing anything with the data: df['price'] = df['price'].astype('float')
score: 1
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50887493

operating-system
tags question: http://stackoverflow.com/q/50929915
tags question: http://stackoverflow.com/q/50875317
tag name: operating-system
tags question: http://stackoverflow.com/q/50996286
tags question: http://stackoverflow.com/q/50880595
type: Tag
tags question: http://stackoverflow.com/q/50888930

http://stackoverflow.com/a/60851814
has comment: http://stackoverflow.com/comment/107675438
score: 4
answers question: http://stackoverflow.com/q/50948314
type: Answer
upvote count: 4
downvote count: 0
has body: It should be pylint issue. You can disable pylint warnings for a specific line by adding a comment "# pylint: disable=maybe-no-member" after the offending statement. see Hide some maybe-no-member Pylint errors http://pylint.pycqa.org/en/latest/#is-it-possible-to-locally-disable-a-particular-message

http://stackoverflow.com/q/50992034
tagged with: python
has answer: http://stackoverflow.com/a/50992087
tagged with: performance
score: 1
has title: How to concatenate a series based on a date index to form a df without losing data
upvote count: 1
type: Question
has body: I'm trying to concatenate a bunch of historical pricing data into a single data frame, but I seem to be randomly dropping portions of data. Here is what I am trying to do: "v" is for value, a float type Series 1: Ticker1 Date1 v1 Date2 v2 Date3 v3 Date4 v4 . . . . Date100 v5 Series 2: Ticker2 Date101 v6 Date102 v7 Date103 v8 Date104 v9 . . . . Date200 v10 Final desired df Ticker1 Ticker2 Date1 v1 np.nan Date2 v2 np.nan Date3 v3 np.nan Date4 v4 . . Date100 v5 Date101 np.nan v6 Date102 np.nan v7 Date103 np.nan v8 Date104 np.nan v9 . . . . Date200 np.nan v10 Here is how I'm doing it: data_dict = {} for ticker in tickers: try: data_dict[ticker] = data.DataReader(ticker,'iex',start_date, end_date) data_dict[ticker] = data_dict[ticker].reset_index() data_dict[ticker]['date'] = pd.to_datetime(data_dict[ticker]['date'], format="%Y-%m-%d") data_dict[ticker]['date'] = data_dict[ticker]['date'].dt.date data_dict[ticker].index = data_dict[ticker]['date'] data_dict[ticker] = data_dict[ticker].drop('date', axis=1) except: pass pricing_df = pd.DataFrame() volume_df = pd.DataFrame() for ticker in data_dict.keys(): temp_series = pd.Series(data = data_dict[ticker]['close'].values, index = data_dict[ticker].index, name = ticker ) pricing_df[ticker] = temp_series temp_series = pd.Series(data = data_dict[ticker]['volume'].values, index = data_dict[ticker].index, name = ticker ) volume_df[ticker] = temp_series What I'm getting in return is essentially what I want, but with an arbitrary amount of dates cut off at the beginning of the dataset. Specifically, I have series with dates going back to 2014, but when I bring into the final dataset, but df starts in mid-2015.... Thanks in advance for all the help!
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/50992256
tagged with: pandas
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/50989048
score: 0
has body: I keep getting NoReverseMatch at /music/2/ error, and it's pointing me to the parent template that i'm inheriting from, base.html, but i can't find anything wrong with it. I know it's probably annoying when someone asks you to search for errors, but maybe someone can easily see what i'm unable to see {% extends "music/base.html" %} {% block content %} Album : {{one_album}} Song list : {% if somethings_wrong %} {{ somethings_wrong }} {% endif %} {% csrf_token %} {% for song in album_entries %} {{ song.song_title }} {% if song.is_favorite %} #afterwards, set this explicitly to true, for learning purposes #check if this slash is necessary later {% endif %} {% endfor %} {% endblock content %} Here's the base.html Link to the homepage {% block content %} {% endblock content %} Here's the Views.py : from django.shortcuts import render from django.http import HttpResponse from .models import Album, Song def index(request): albums = Album.objects.all() context = {'albums': albums} return render(request, 'music/index.html', context) def detail(request, album_id): # show album and every entry in that album. one_album = Album.objects.get(id=album_id) album_entries = one_album.song_set.all() context = {'one_album' : one_album, 'album_entries' : album_entries} return render(request, "music/album.html", context) # Create your views here. def favorite(request, album_id): one_album = Album.objects.get(id=album_id) try: context = {'one_album' : one_album} selected_song = one_album.song_set.get(id=request.POST["song"]) except(KeyError, Song.DoesNotExist): somethings_wrong = "Something's not right with your choice" context = {'one_album' : one_album, 'somethings_wrong' : somethings_wrong} return render(request, "music/album.html", context) else: selected_song.is_favorite = True selected_song.save() return render(request, "music/album.html", context) i think error is somewhere here, urls.py and models.py are pretty simple. I've added is_favorite booleanfield to Song class, which is Fal…
tagged with: django-templates
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/50989364
type: AnsweredQuestion
type: Question
has title: Reverse for 'favorite' with arguments '('',)' not found, following Bucky's Django tutorial on YouTube
accepted answer: http://stackoverflow.com/a/50989364
answer count: 1

http://stackoverflow.com/q/50952159
has comment: http://stackoverflow.com/comment/88903678
tagged with: ssl
linked to: http://stackoverflow.com/q/30405867
has answer: http://stackoverflow.com/a/55459127
has comment: http://stackoverflow.com/comment/88902017
answer count: 1
downvote count: 0
has body: I'm new to Python and have been struggling with this for hours now, so I thought perhaps someone within the community would be able to help. I have a self signed certificate from a 3rd party enterprise who is not a valid CA which is fine. I've created a .p12 and I'm SUCCESSFULLY able to connect to said 3rd party's HTTP server using C# and .net (great). Using the same .p12, I'm able to create a keystore, import the key, and successfully connect to the 3rd party's HTTP server using Java HttpsURLConnection (also great). Unfortunately, it is not trivial at all to do this in Python! I have followed these instructions to split the .p12 into a key.pem and a cert.pem https://www.ibm.com/support/knowledgecenter/en/SSZRJV_10.1.0/admin_guide/pac_x509_web_services_python_convert.html I have tried the following Python http libraries to try to make the connection (as imports below): import requests import http.client.HTTPSConnection import httplib2 Code snippet using requests import requests r = requests.get(url, cert=('crt.pem', 'key_nopass.pem')) print(r.text) Code snippet using httplib2 (and from IBM example) https://www.ibm.com/support/knowledgecenter/SSZRJV_10.1.0/admin_guide/pac_x509_web_services_test.html import httplib2 http = httplib2.Http() http.add_certificate('key_nopass.pem', 'crt.pem', '') response, content = http.request(url, 'GET') print(content) Using any of these libraries, I get the following error: OpenSSL.SSL.Error: [('SSL routines', 'ssl3_get_server_certificate', 'certificate verify failed')] Would appreciate if anyone can point me in right direction or tell me what I'm doing wrong. Quite frustrating since as I mentioned the same simple HTTP calls work from C# and Java without issue (so I know the p12 and certs are valid) I've tried + used many different stackoverflow posts to no avail. Thanks PS @Steffen Ulrich, its not a duplicate at all. The post you linked to says to use the CA file. I wasn't required to use a CA file for Java or C#. So if you can please…
favorite count: 0
has title: Python + self signed cert + HTTP not working but works in C#, Java
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/32194900
score: 2
has comment: http://stackoverflow.com/comment/88902275
upvote count: 2
has comment: http://stackoverflow.com/comment/88902306
type: Question

http://stackoverflow.com/a/50987884
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50986520
score: 2
upvote count: 2
has body: Need to use celery_worker parameter in pair with pytest mark @pytest.mark.django_db(transaction=True).
answers question: http://stackoverflow.com/q/50986520

http://stackoverflow.com/q/50937642
favorite count: 0
type: UnansweredQuestion
tagged with: astronomy
upvote count: 1
tagged with: orbital-mechanics
score: 1
has body: I would like to calculate the position of the five Lagrange points in the sky (L1 - L5) as RA/DEC or AZ/EL when provided with a UTC timestamp and a Lat/Lon/Alt observer location on earth. I was looking at pyephem, pyorbital and skyfield but as far as I could see, they do not support this. If someone could point me towards a reference/code to calculating this in python that would be much appreciated. P.S. If not already a part of pyephem/skyfield/pyorbital, I think this would be an interesting feature to add?
has answer: http://stackoverflow.com/a/51823269
type: Question
answer count: 1
downvote count: 0
tagged with: skyfield
tagged with: pyephem
has title: Calculate RA DEC/AZ EL of Lagrange Points seen from a location on earth
tagged with: python

http://stackoverflow.com/q/50859204
has comment: http://stackoverflow.com/comment/88757228
has comment: http://stackoverflow.com/comment/88756116
type: Question
has body: I have been trying to find and replace across XML text runs using the Python LXML library. My current attempt: v = '' position = -1 positions = [] for cur in root.iter('t'): v = v + cur.text position = position + len(cur.text) positions.append(position) v = v.replace("test string", "this is a test string") i = 0 start = 0 end = positions[0] for cur in root.iter('t'): try: cur.text = v[start:end] print cur.text start = end i = i + 1 end = positions[i] except IndexError: break Simplified Example XML: <t>this is a test</t> <w>asdfasdfsadf</w> <t>test<t> <w>ajsdfkladkjsf</w> <t> string</t> This approach puts the contents of the tags into a string, and keeps track of the indices where the split occurs. It then does the replacements on the string and writes the string back into the XML at roughly the same position. Unfortunately, once I open the file in Word there are random spaces missing and added elsewhere. I know that this method will probably not work, but what is the best way to go about solving this problem with the lxml parser. EDIT: I do not want to read the file in as a string and edit it, I want to edit the file and keep all the formatting.
has comment: http://stackoverflow.com/comment/88721646
tagged with: lxml
has comment: http://stackoverflow.com/comment/88740986
tagged with: http://stackoverflow.com/tag/xml
tagged with: openxml
answer count: 0
type: UnansweredQuestion
score: 0
tagged with: python
has title: Find and replace across text runs in MS Word XML using Python
has comment: http://stackoverflow.com/comment/88721133

http://stackoverflow.com/comment/88737417
comment on: http://stackoverflow.com/a/50866928
has text: I do not understand the behaviour of this loop - what controls it? if user said no you just go to infinity?
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88773787
score: 0
has text: are you using python(just want to confirm) also provide some sample code if possible?
comment on: http://stackoverflow.com/q/50885763
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50858252
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/88720258
has body: You’re running the install command pip install requests in a Python interpreter when you should be running it in a shell. Open a terminal, and then paste that command into it. Then press enter. Then, in your Python interpreter, import the requests module before using it. import requests requests.get('https://www.google.com') # For example.
answers question: http://stackoverflow.com/q/50858199
accepted answer of: http://stackoverflow.com/q/50858199
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88719933
type: Answer

http://stackoverflow.com/comment/88903664
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50952675
has text: yea row 1 and row 2 sorry
score: 0

http://stackoverflow.com/a/50937324
has comment: http://stackoverflow.com/comment/88899906
has comment: http://stackoverflow.com/comment/88884099
has comment: http://stackoverflow.com/comment/88937285
has comment: http://stackoverflow.com/comment/88891808
type: Answer
downvote count: 1
answers question: http://stackoverflow.com/q/50900340
upvote count: 0
has body: I did it by throwing words into a dict based on their timestamp, and them matching them to their speakers: times = {} for r in data['results']: for word in r['alternatives'][0]['timestamps']: times[(word[1], word[2])] = word[0] transcripts = {} for r in data['speaker_labels']: speaker = r['speaker'] if speaker in transcripts: transcripts[speaker].append(times[(r['from'], r['to'])]) else: transcripts[speaker] = [times[(r['from'], r['to'])]] print([{'speaker': k, 'transcript': ' '.join(transcripts[k])} for k in transcripts]) It runs on the example provided 1,000,000 times in ~12.34 seconds, so hopefully it's fast enough for what you want.
has comment: http://stackoverflow.com/comment/88873744
has comment: http://stackoverflow.com/comment/88916285
has comment: http://stackoverflow.com/comment/88873163
has comment: http://stackoverflow.com/comment/88898510
has comment: http://stackoverflow.com/comment/88900175
score: -1

http://stackoverflow.com/q/50871702
accepted answer: http://stackoverflow.com/a/52215825
tagged with: api
answer count: 1
has title: How to pass extra arguments to Google Pagespeed API service object
favorite count: 0
tagged with: google-api
upvote count: 1
tagged with: python
type: AnsweredQuestion
tagged with: pagespeed
score: 1
has answer: http://stackoverflow.com/a/52215825
type: Question
downvote count: 0
has body: I'm using the Google Pagespeed API v4 to extract Pagespeed scores for a large number of URLs. I want to test for both desktop and mobile with the argument strategy within my Pagespeed call. This is possible in the general API call, but I can't find a way to pass these arguments in the batch call. Minimal working example: from apiclient.discovery import build import requests #define Google API key and API call google_api_key = "MyKey" #build service object to call PageSpeed, version 4, with MyKey ps_service = build('pagespeedonline', 'v4', developerKey = google_api_key) list_of_urls = [a list of several URLs] #define function; make list of URLs with column for PageSpeed score def list_websites(request_id, response, exception): if exception is not None: print("This is an exception: " + str(exception) + " " + request_id) else: score = response['ruleGroups']['SPEED']['score'] print(score) #create URL batch ps_batch = ps_service.new_batch_http_request(callback = list_websites) service_list = [] for url in list_of_urls: service_list.append(ps_service.pagespeedapi().runpagespeed(url = url)) for req in service_list: ps_batch.add(req) #execute API call by batch ps_batch.execute() Although this method works fine for doing batch requests to the API, by default it calculates a speed score based on a desktop view of the said URLs (the analysis strategy is set to desktop), whereas I would also like to receive a score for a batch request in which strategy is set to mobile, to get a score based on the mobile view of the URLs. My question is, how do I add an extra argument to the build() function in which I can make a distinction between mobile and desktop?

http://stackoverflow.com/a/50889922
type: Answer
upvote count: 4
downvote count: 0
has body: With the truthiness of a QuerySet Well the truthiness of a QuerySet is whether it contains any elements, so you can check if friends. Like: Friends {% if not friends %} You don't have any friends :( Add one!! {% else %} {% for friend in friends %} {{ friend.username }} Remove Friend {% endfor %} {% endif %} In case the query is not yet made, Django will make the query, so given you want to iterate over the QuerySet, this is more efficient than an exists call, since it loads the results as well, in a single database query. With an EXISTS query If you are however, not interested in using the queryset, but only want to look if the queryset has at least one element, you can use the friends.exists() call. Note that in Django templates, you do not add the brackets: in case an element is callable, Django will automatically call it: Friends {% if not friends.exists %} You don't have any friends :( Add one!! {% else %} {% for friend in friends %} {{ friend.username }} Remove Friend {% endfor %} {% endif %} (This will usually require a second query when you iterate over it, which is the case here). With a for-empty loop Django templates also has a {% for ...%}-{% empty %}-{% endfor %} construct. One can use a {% empty %} template below the body of the for loop, and before the {% endfor %} that contains content that is displayed in case the for loop has no eleemnts, like: Friends {% for friend in friends %} {{ friend.username }} Remove Friend {% empty %} You don't have any friends :( Add one!! {% endfor %}
accepted answer of: http://stackoverflow.com/q/50889874
answers question: http://stackoverflow.com/q/50889874
type: AcceptedAnswer
score: 4

http://stackoverflow.com/comment/89006164
comment on: http://stackoverflow.com/q/51006409
type: Comment
type: QuestionComment
has text: Does the solution to this question require more rows? I would hope the solution can be done on multiple frames with only one row.
score: 0

http://stackoverflow.com/a/50914355
score: 5
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50914252
type: Answer
has body: You have to set the scrollArea to MyScrollWidget using a layout. from PyQt5 import QtWidgets import sys class MyScrollWidget(QtWidgets.QWidget): def __init__(self): super(MyScrollWidget, self).__init__() lay = QtWidgets.QVBoxLayout(self) scrollArea = QtWidgets.QScrollArea() lay.addWidget(scrollArea) top_widget = QtWidgets.QWidget() top_layout = QtWidgets.QVBoxLayout() for i in range(10): group_box = QtWidgets.QGroupBox() group_box.setTitle('GroupBox For Item {0}'.format(i)) layout = QtWidgets.QHBoxLayout(group_box) label = QtWidgets.QLabel() label.setText('Label For Item {0}'.format(i)) layout.addWidget(label) push_button = QtWidgets.QPushButton(group_box) push_button.setText('Run Button') push_button.setFixedSize(100, 32) layout.addWidget(push_button) top_layout.addWidget(group_box) top_widget.setLayout(top_layout) scrollArea.setWidget(top_widget) self.resize(200, 500) if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) widget = MyScrollWidget() widget.show() sys.exit(app.exec_())
upvote count: 5
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50914252

http://stackoverflow.com/q/50885254
has body: How can I rewrite this code, so that it won't display the accumulated value of the time overall, but the accumulated time value for each user for those days which have duplicate logins. for item in x: #x = usage_report.get_login_rec() b = item[14].strip('()') a = time.strptime(b, "%M:%S") c = int(a.tm_sec) b.strip(':') if item[2:5]: test += c d.append(test) f.append(test) t.append([item[0], item[3] , item[4], item[5], str(b) ,test]) print(*t, sep='\n') This is what i get in return: ['root', 'Thu', 'May', '10', '00:10', 2285] ['tom', 'Tue', 'May', '8', '01:00', 2300] ['root', 'Tue', 'May', '8', '00:20', 2400] ['root', 'Tue', 'May', '8', '00:20', 2429] ['root', 'Tue', 'May', '8', '00:20', 2514] ['root', 'Tue', 'May', '8', '00:20', 2552] ['(unknown)', 'Tue', 'May', '8', '00:00', 2552] ['(unknown)', 'Mon', 'May', '7', '00:12', 2564] expected output: ['root', 'Thu', 'May', '10','00:10' , 10] ['root', 'Tue', 'May', '8', '1:20', 120] ['tom', 'Tue', 'May', '8', '00:60', 60] ['(unknown)', 'Tue', 'May', '8', '00:00', 0] ['(unknown)', 'Mon', 'May', '7', '00:12', 12] x = def get_login_rec(): raw_login_rec = [ x.split() for x in os.popen('last -F -i -w').read().split('\n')] login_rec = [] bad_rec = [] for rec in raw_login_rec: if len(rec) == 15: login_rec.append(rec) else: bad_rec.append(rec) return login_rec
has comment: http://stackoverflow.com/comment/88772937
has comment: http://stackoverflow.com/comment/88772449
has answer: http://stackoverflow.com/a/50885604
has comment: http://stackoverflow.com/comment/88780201
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/88772357
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88772830
has comment: http://stackoverflow.com/comment/88772746
tagged with: python
has comment: http://stackoverflow.com/comment/88772619
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88773135
accepted answer: http://stackoverflow.com/a/50885604
upvote count: 2
type: Question
has title: How can I fix my code to accumulate items with same date and username and return time python
has comment: http://stackoverflow.com/comment/88773179

http://stackoverflow.com/comment/88823871
type: QuestionComment
type: Comment
has text: There might be an answer here: https://stackoverflow.com/a/34547262/1530072
comment on: http://stackoverflow.com/q/50911887
score: 0

http://stackoverflow.com/comment/88996100
score: 0
type: AnswerComment
has text: Reading each audio file and its corresponding transcript is not the problem. I am using a convolutional neural network for extracting features from the spectrogram of each audio file and then I feed the extracted features to a recurrent layer using a CTC loss as the criterion. The problem is that I don't know how to pass the spectrograms with variable lengths to this network and how to pass the corresponding transcript to the loss in Pytorch. So the problem is consisting of two parts : first how to give the spectrogram to the network and secondly how to pass corresponding label of it to loss.
type: Comment
comment on: http://stackoverflow.com/a/50995488

http://stackoverflow.com/comment/88877616
comment on: http://stackoverflow.com/q/50939370
has text: What's the rule you need to apply? For example, if the value is "mrs.jay-zee-jz@gmail.com", how do you know it's "jz@gmail.com" and not "zee-jz@gmail.com"? Both are valid email addresses, and presumably both "mrs.jay" and "mrs.jay-zee" are valid names. It seems like you have data that could be impossible to parse correctly.
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/q/50907996
linked to: http://stackoverflow.com/q/50877663
has body: As was proposed in a question I posed last week, a memory efficient way to store a column with values in the range [True, False, NaN] would be to use the int8-datatype to denote True as 1, False as 0 and NaN as -1. If I do this, what would be good practice to "redefine" pandas' isnull() methods to also take into account that, if a column in a dataframe has dtype int8, -1 should be considered a null-value. I could think of defining a new function def isnull(v), that returns if a value is NaN, or -1 in case of dtype int8, but I can imagine this will not be a very fast and efficient solution (given that the dataframe I am working with is multiple gigabytes big, and I want to be able to count the amount of "null"-values in a column/dataframe).
tagged with: python
type: AnsweredQuestion
has title: Checking NaN values in pandas dataframe with int8 columns
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/50908075
tagged with: null
accepted answer: http://stackoverflow.com/a/50908075
tagged with: pandas
answer count: 1
downvote count: 0
score: 1
favorite count: 0

http://stackoverflow.com/q/50999879
accepted answer: http://stackoverflow.com/a/51565770
tagged with: python
has title: pyspeedtest cannot find test server
downvote count: 1
has answer: http://stackoverflow.com/a/50999937
has body: I'm trying to use pyspeedtest to get the upload/download speed of my connecting but I keep getting the following error which I couldn't resolve: import pyspeedtest st = pyspeedtest.SpeedTest() st.download() Exception: Cannot find a test server Any suggestions/insights would be welcome!
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51565770
possible better answer: http://stackoverflow.com/a/50999937
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/75985895
answer count: 3
score: 3
favorite count: 0

http://stackoverflow.com/comment/88967450
type: Comment
type: QuestionComment
has text: thank you I have updated my question with all your suggestions.
score: 0
comment on: http://stackoverflow.com/q/50982326

http://stackoverflow.com/q/50923163
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/88920053
has answer: http://stackoverflow.com/a/50970409
upvote count: 2
downvote count: 3
tagged with: pyqt5
type: Question
has comment: http://stackoverflow.com/comment/88860783
tagged with: pyqt
has body: I have a code that display Items in a QlistWidget that refer to a file path once the user select one of the items the system display its content. The problem is that once the user select one of the item it keep the focus on it and the user can't select other item. the Image below show that both items have focus that mean when i try to select the second Item i must deselect the first and vise versa. How to fix this? example : C:\Users\test\Desktop\New Microsoft Word Document.docx row =>0 C:\Users\test\Desktop\test_arabic.docx row =>1 the displayed result on the console : current row = 0 this is P==>C:\Users\test\Desktop\test_arabic.docx this is oneDir==>C:\Users\test this is the cuurent Item ==C:\Users\test\Desktop\New Microsoft Word Document.docx current row = 1 this is P==>C:\Users\test\Desktop\test_arabic.docx this is oneDir==>C:\Users\test this is the cuurent Item ==C:\Users\test\Desktop\New Microsoft Word Document.docx and if the user select twice the same item the system display this error : mouseHover toolTipResult = self.listWidgetPDFlist.setToolTip(Item) builtins.UnboundLocalError: local variable 'Item' referenced before assignment code: from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtCore import (QMimeData) from PyQt5.QtWidgets import (QApplication, QCheckBox, QColorDialog, QDialog, QErrorMessage, QFileDialog, QFontDialog, QFrame, QGridLayout, QInputDialog, QLabel, QLineEdit, QMessageBox, QPushButton, QMenu,QListWidgetItem) #from PyQt5.QtCore import QDir, Qt from PyQt5.QtWidgets import * import pdfviewer import pathlib from pathlib import Path import os import re from os import path import json,datetime,time from collections import defaultdict import docx import PyPDF2 class pdfViewer(pdfviewer.Ui_PdfPreviewWindow): def __init__(self,PdfPreviewObj): pdfviewer.Ui_PdfPreviewWindow.__init__(self) self.PdfPreviewObj =PdfPreviewObj self.setupUi(PdfPreviewObj) self.PdfPreviewObj.show() ''' buttons status at the init of the program ''' self.pushButtonSearc…
answer count: 1
favorite count: 0
has title: why the Items in QlistWidget keep the focusing on it once the user select one of the Item
tagged with: qlistwidget
type: UnansweredQuestion
tagged with: path

http://stackoverflow.com/comment/88830816
type: QuestionComment
has text: @erip Hi from DC bud! I think lsa_model is an array and it does not have an attribute named "components_"
comment on: http://stackoverflow.com/q/50915223
score: 0
type: Comment

http://stackoverflow.com/comment/88787396
type: QuestionComment
comment on: http://stackoverflow.com/q/50893458
score: 1
has text: try port=3306 without quotes
type: Comment

http://stackoverflow.com/comment/88986719
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50996055
has text: @Arximede yes, the property acts as a method which queries the *current* values at `x` and `y`.

http://stackoverflow.com/comment/88997543
has text: Thanks Ralf. It works. I very appreciate your kind answer.
type: Comment
comment on: http://stackoverflow.com/a/51000934
score: 0
type: AnswerComment

http://stackoverflow.com/q/50920146
type: Question
tagged with: client-server
has comment: http://stackoverflow.com/comment/88873342
has comment: http://stackoverflow.com/comment/88839966
score: 0
type: UnansweredQuestion
tagged with: python
has body: If I were to create a global variable in Python that holds a dictionary for caching data coming from the user, would this data be stored in the user's stack, or would it be stored in the server? So, basically what I am trying to understand here is whether one global instance of a Python dictionary cache the data of all the users using the app or will there be an instance of that dictionary made for each person?
answer count: 0
has comment: http://stackoverflow.com/comment/88839986
tagged with: memory
tagged with: caching
has title: Memory Allocation for Python Datastructures

http://stackoverflow.com/q/50876410
has title: Enriching one dataframe with data from another based on conditions
has comment: http://stackoverflow.com/comment/88755114
type: AnsweredQuestion
upvote count: 0
linked to: http://stackoverflow.com/q/20109391
has comment: http://stackoverflow.com/comment/88755463
has body: I need some help to do some complex lookups and enrichment. I need this working in Python 3.5 Here is the scenario. I have 2 dataframes: dfMaster and dfLookup dfMaster has columns fromDate, toDate, fromLocation, toLocation, LookupKey (This dataframe will get additional rows every day) The data in dfMaster has 2 rows: 1-May-2018, 3-May-2018, Amsterdam, Rotterdam, NaN 2-May-2018, 5-May-2018, Rotterdam, Amsterdam, NaN dfLookup has columns lookupDate, lookupFromLocation, lookupToLocation, someKey (This is a fairly static dataframe) The data in dfLookup has 2 rows: 3-May-2018, Rotterdam, Amsterdam, Key1 5-May-2018, Rotterdam, Amsterdam, Key1 I want to do the following matching on dfMaster: I want to pick dfLookup.lookupDate and check its between dfMaster.fromDate and dfMaster.toDate Next, I want to check the lookupFromLocation matches fromLocation Finally, I want to check the lookupToLocation matches toLocation If all of this matches, I want to pick dfLookup.Key1 and put it into dfMaster.LookupKey The final output should look like this: 1-May-2018, 3-May-2018, Amsterdam, Rotterdam, NaN 2-May-2018, 5-May-2018, Rotterdam, Amsterdam, Key1 Not finding an easy way to do this. I also want the final output to not be only filtered by what I enrich, but also by those rows that are not enriched Thanks
type: Question
accepted answer: http://stackoverflow.com/a/50877130
score: -1
has comment: http://stackoverflow.com/comment/88755561
tagged with: pandas
downvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/88754901
has answer: http://stackoverflow.com/a/50877130
favorite count: 0
tagged with: python-3.x
tagged with: python

http://stackoverflow.com/comment/88836016
type: Comment
comment on: http://stackoverflow.com/a/50917880
score: 0
type: AnswerComment
has text: Glad that I was able to help. Can you please accept the answer

http://stackoverflow.com/q/50893772
has comment: http://stackoverflow.com/comment/88787799
tagged with: thread-safety
has answer: http://stackoverflow.com/a/50893889
score: 0
answer count: 2
tagged with: locking
tagged with: python-multithreading
tagged with: python
possible better answer: http://stackoverflow.com/a/50893889
type: AnsweredQuestion
has body: I have a class which parses a LOT of strings. There are 6 main variables being written into by 6 threads. Total character count of all strings together will cross 500,000 characters. Each thread works independently, ie, all of their strings does not collide with or are referenced by other strings. Meaning all threads work exclusive of each other regarding inputs and when outputting, they only write to their variable in the class. Should I implement a lock mechanism in the class during writing into those variables? EDIT1: Completed the threading. However, to compare speed of execution, I ran all concurrently too. I found it takes 1.44 seconds when run sequentially and takes 2.33 seconds when threaded. What am i doing wrong?
tagged with: multithreading
type: Question
has answer: http://stackoverflow.com/a/50893827
accepted answer: http://stackoverflow.com/a/50893827
has title: Should I use a lock to write to class variables (during threading) even if each variable is not accessed/written into by other threads?

text-classification
tags question: http://stackoverflow.com/q/50949318
tag name: text-classification
type: Tag
tags question: http://stackoverflow.com/q/50986948
tags question: http://stackoverflow.com/q/50870437
tags question: http://stackoverflow.com/q/50999596
tags question: http://stackoverflow.com/q/50907268

lemmatization
type: Tag
tags question: http://stackoverflow.com/q/50860645
tag name: lemmatization

http://stackoverflow.com/comment/88735812
score: 0
has text: So, the faulty line is `iRet=mydll.AXGMB_Nvram_Open()` and it raises an exception (program stops)? Could you share the header file that came with the *.dll*?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50861250

http://stackoverflow.com/a/76646886
has body: Adding my two cents - although @Marco's answer is much more performant than the accepted answer and the suggestion I'm about to make - still, one can also use NumPy's histogram function to sum values given according to some grouping. labels, bin_labels, bin_counts = np.unique(X[:,0], return_inverse=True, return_counts=True) bins = np.arange(len(labels)+1) i = 1 # 1 for the second column, 2 for the next, etc. s = np.histogram(bin_labels, weights=X[:,i], bins=bins)[0] mean = s / bin_counts Now mean stands for the mean of each label mentioned in labels. Again, this is slower than np.add.reduceat but I provide it as an alternative as maybe it can serve other purposes...
type: Answer
score: 1
answers question: http://stackoverflow.com/q/50950231
upvote count: 1
downvote count: 0

http://stackoverflow.com/comment/88886138
has text: same output as cron. `cron.log` is full of with csv data
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50909483

http://stackoverflow.com/comment/115503847
type: AnswerComment
comment on: http://stackoverflow.com/a/52392304
type: Comment
has text: This doesn't really explain what the differences are
score: 21

http://stackoverflow.com/q/50934946
has body: I have a script called "RiskTemplate.py" which generates a pandas dataframe consisting of 156 columns. I created two additional columns which gives me a total count of 158 columns. However, when I run this "RiskTemplate.py" script in another script using the below code, the dataframe only pulls the original 156 columns I had before the two additional columns were added. exec(open("RiskTemplate.py").read()) how can I get the reference script to pull in the revised dataframe from the underlying script "RiskTemplate.py"? here are the lines creating the two additional dataframe columns, they work as intended when I run it directly in the "RiskTemplate.py" script. The original dataframe is pulling from SQL via df = pd.read_sql(query,connection) df['LMV % of NAV'] = df['longmv']/df['End of Month NAV']*100 df['SMV % of NAV'] = df['shortmv']/df['End of Month NAV']*100
answer count: 1
tagged with: reference
type: UnansweredQuestion
tagged with: python
has title: dataframe from underlying script not updating
tagged with: dataframe
has answer: http://stackoverflow.com/a/50935236
type: Question
has comment: http://stackoverflow.com/comment/88868474
score: 0

http://stackoverflow.com/a/51004565
has body: The point of this answer is to show that there is a straight forward way to do this with simple iteration and tools from the standard library. Often times we perform many transformations on a Pandas DataFrame where each transformation invokes the construction of a new Pandas object. At times this can be an intuitive progression and make perfect sense. However, there are times when we forget that we can use simpler tools. I believe this is one of those times. My answer still uses Pandas in that I use the itertuples method. from collections import defaultdict d = defaultdict(dict) for a, b, c in df.itertuples(index=False): d[b][a] = c d = dict(d) d {'t': {'a1': 1, 'a2': 2}, 'd': {'a3': 3, 'a4': 4}} Slight alternative. Since the tuples we are iterating over are named tuples, we can access each element by the name of the column it represents. from collections import defaultdict d = defaultdict(dict) for t in df.itertuples(): d[t.ColB][t.ColA] = t.ColC d = dict(d) d {'t': {'a1': 1, 'a2': 2}, 'd': {'a3': 3, 'a4': 4}}
upvote count: 10
type: Answer
score: 10
answers question: http://stackoverflow.com/q/51004506
downvote count: 0

http://stackoverflow.com/q/50876440
tagged with: jsonschema
has title: How to generate a time string for jsonschema
has comment: http://stackoverflow.com/comment/88773832
has comment: http://stackoverflow.com/comment/88817064
has body: I have a schema like this: "foo": {"type": "string", "format": "time"} I tried new (new Date()).toISOString() it has this format: "2018-06-12T08:59:01.135Z" Error: jsonschema.exceptions.ValidationError: '2018-06-12T08:59:01.135Z' is not a 'time'
has comment: http://stackoverflow.com/comment/88754527
type: Question
score: 0
has comment: http://stackoverflow.com/comment/88754703
answer count: 2
tagged with: javascript
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50876557
has answer: http://stackoverflow.com/a/50890958

http://stackoverflow.com/comment/88962612
has text: The sample input and output is already there I will edit the question a bit
comment on: http://stackoverflow.com/q/50983763
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50923756
tagged with: for-loop
downvote count: 0
accepted answer: http://stackoverflow.com/a/50924036
tagged with: iteration
has answer: http://stackoverflow.com/a/50924167
has body: I am making a simple program where there is a simple for loop. There are two inputs in my program, n and k. k is used to skip numbers over iteration and n is the number of numbers that is to be printed. This is my code: nk = input().split() n = int(nk[0]) k = int(nk[1]) store_1 = [] for x in range(1,n+n,k): store_1.append(x) print(store_1) The only pairs that seems to work is when k is set to 2 and the starting of the range remains 1. But when k is set to any other number and the starting of the range is above 1, it doesn't provide the correct output. For example: #6 and 3, starting range 1 [1,4,7,10] #Correct output: [1,4,7,10,13,16] #4 and 2, starting range 2 [2,4,6] #Correct output: [2,4,6,8] #4 and 2, starting range 1 [1,3,5,7] Only this sort of pair and starting range provides the correct output. How can I fix my Code and get the right output. Note: I can set the starting of the range to any number, Ex: 2,3,4 etc. EDIT: More samples: #5 and 3, starting range 3 Correct output: [3,6,9,12,15] #7 and 7, starting range 1 Correct output: [1, 8, 15, 22, 29, 36, 43] #6 and 8, starting range 5 Correct output: [5,13,21,29,37,45]
has answer: http://stackoverflow.com/a/50924098
answer count: 3
tagged with: python
has answer: http://stackoverflow.com/a/50924036
favorite count: 0
tagged with: python-3.x
upvote count: 2
possible better answer: http://stackoverflow.com/a/50924167
type: AnsweredQuestion
score: 2
has title: How to get the correct results from the for loop in Python 3?
tagged with: loops
type: Question

http://stackoverflow.com/a/50920941
type: Answer
has comment: http://stackoverflow.com/comment/88848142
has body: The error message in your question title is pretty obvious. ap.add_argument("-s", "--source", required=True, help="Path to the source of shapes") You put required=True on this parameter. That means it's required. So, if you try to run this script, and don't put a --source (or -s) argument on the command line, you will get an error. If you don't want it to be required, don't put required=True. The output you show at the end of the question, on the other hand, cannot possibly come from this code. There is no -src or -trg parameter in your argparse spec. Maybe you're running a completely different program? If so, we can't debug that program by seeing the code to this one.
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50920758
answers question: http://stackoverflow.com/q/50920758

http://stackoverflow.com/a/50919930
has body: my_serverside_module.py keep during server lifetime state = [] Ans: This can be implemented using the celery(store state in python variables) and/or redis(store state in memory i.e. in redis). You could use redis and django middleware/from views to update state using celery tasks. called at server start def init_module(): pass Ans: This could also be implemented using celery. Or the ready function of an app in the apps.py file of the main app in the django project. called by framework 1 time per minute def poll(): pass Ans: as far as I know django, i never came across something like this so far. That does not mean it cant be done :P I dont know the answer to this. But using celery you can call a function/task every minute. It wont be called by django, but it will be called every minute. called by myself during http request from Django code def do_something(): pass Ans: this is definitely the middeleware part, See middleware hooks for more info. Write a utility function and call it from middleware hooks. Middleware hooks are useful if you want something to happen before or after the view function is called. If you want a function to be called during the view is being processed, you can use the signals concepts in the django. You can send a signal during the view is being processed using python code.
type: Answer
score: -1
downvote count: 2
upvote count: 1
answers question: http://stackoverflow.com/q/50917614

http://stackoverflow.com/a/50908075
accepted answer of: http://stackoverflow.com/q/50907996
score: 4
type: AcceptedAnswer
downvote count: 0
has body: it should be pretty fast... Timing for 100.000.000 rows series. In [84]: s = pd.Series(np.random.choice([1,0,-1], 10**8), dtype=np.int8) In [85]: s.shape Out[85]: (100000000,) simulating series.isnull(): In [86]: %timeit s==-1 87 ms ± 3.51 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) In [87]: %timeit s.values==-1 84.1 ms ± 2.88 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) In [88]: %timeit np.where(s==-1) 546 ms ± 14.6 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) In [89]: %timeit np.where(s.values==-1) 531 ms ± 2.78 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) simulating: series.isnull().sum(): In [90]: %timeit (s==-1).sum() 1.39 s ± 38.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) In [91]: %timeit (s.values==-1).sum() 181 ms ± 1.88 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) PS please pay attention that for counting (summing) them the difference between (s==-1).sum() and (s.values==-1).sum() is pretty noticeable
type: Answer
has comment: http://stackoverflow.com/comment/88816002
answers question: http://stackoverflow.com/q/50907996
has comment: http://stackoverflow.com/comment/88815958
upvote count: 4

http://stackoverflow.com/q/51007376
has comment: http://stackoverflow.com/comment/89007888
tagged with: python
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/51007414
accepted answer: http://stackoverflow.com/a/51007414
has title: check if all element of multiple lists inside a list is identical
possible better answer: http://stackoverflow.com/a/51007438
linked to: http://stackoverflow.com/q/28597180
has body: How do I check if the elements of multiple lists inside a list are identical? The following code is from Checking if all elements of a List of Lists are in another List of Lists Python but it only counts the number of list in my list, not the elements the lists inside the list. Thanks in advance! x.count(x[0]) == len(x)
upvote count: 2
score: 0
has answer: http://stackoverflow.com/a/51007449
downvote count: 2
has answer: http://stackoverflow.com/a/51007438
answer count: 3
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/q/50977636
has title: passing value from 1 page to another in dash plotly
type: Question
linked to: http://stackoverflow.com/q/63490202
tagged with: plotly
has comment: http://stackoverflow.com/comment/102592819
tagged with: plotly-dash
has answer: http://stackoverflow.com/a/65321162
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/92047594
favorite count: 0
has body: I am trying to pass input value to another with Dash Plot. The main page has a list of strategies : First_page = html.Div([ html.Div([dcc.Dropdown(id='strategy', options=[{'label': i, 'value': i} for i in [strat1, start2]], multi=True)], value = [strat1]), html.Div([dcc.Input(id='date_start', type='text', value='1990-01-01')]), html.Button('Start Calculation', id='button'), ]) And my pages 1 and 2 are the following : for i in range(2) : layout = html.Div([ html.Div([dcc.Dropdown(id='strategy'+str(i), options=[{'label': i, 'value': i} for i in [strat1, start2]]])], value = strat+str(i)), html.Div([dcc.Input(id='date_start'+str(i), type='text', value='1990-01-01')]), html.Button('Start Calculation', id='button'+str(i)), + other options not listed in main page ]) The goal is the following : when the user is on the main page he can choose the list of strategies he want to see, as well as the starting date. Then when he press the button, it should open pages for each strategy selected (In the example we have 2 strategies so I should have 2 pages : localhost:port/page-strat1 and localhost:port/page-strat2) where the graph shown on each page starts with the selected date. I succeed to open the pages localhost:port/strat1 and/or the page localhost:port/strat2 depending on the list of selected strategies. list_event = [Event('button', 'click')] list_state = [State('strategy', 'value')] @app.callback(Output('hidden-div', 'children'),events=list_event, state=list_state) def create_callback_share(datestart, list_strategies_used): for _strat in list_strategies_used: time.sleep(1) webbrowser.open('http://localhost:port/page-'+_strat) But I do not succeed to send the selected date. I try the following callback : for i in range(2) : @app.callback(Output('date_start'+str(i), 'value'),inputs=[Input('date_start', 'value')]) def set_display_children(selected_element): return "{}".format(selected_element) But the page localhost:port/strat1 and localhost:port/strat2 allow open with the d…
tagged with: python
has comment: http://stackoverflow.com/comment/115481054
upvote count: 6
type: UnansweredQuestion
score: 6

http://stackoverflow.com/comment/88854170
score: 0
comment on: http://stackoverflow.com/a/50925393
type: Comment
type: AnswerComment
has text: @NilsWerner In fact, I add a line

http://stackoverflow.com/comment/89010461
type: AnswerComment
has text: Just saw it after posting
score: 0
comment on: http://stackoverflow.com/a/51008835
type: Comment

http://stackoverflow.com/comment/88989046
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50997085
has text: Yes, there is only one type =1
score: 0

http://stackoverflow.com/q/50900153
downvote count: 0
has body: I am looking at my code and see that those two models have multiple similar fields. I was wondering if my ParentProfile model could inherit my User model in order to shorten the code and remove overlap. This is quite a beginner question and would like someone else's opinion on this matter. Thank you! models.py class User(AbstractBaseUser): email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) child_first_name = models.CharField(max_length=255) timestamp = models.DateTimeField(auto_now_add=True) student = models.BooleanField(default=False) parent = models.BooleanField(default=False) teacher = models.BooleanField(default=False) active = models.BooleanField(default=True) # can login staff = models.BooleanField(default=False) # staff user, not superuser admin = models.BooleanField(default=False) # superuser objects = UserManager() # takes email as username | removes email USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] def __str__(self): return self.email def has_perm(self, perm, onj=None): "Does the user have a specific permission?" return True def has_module_perms(self, app_label): "Does the user have permissions to view the app 'app_label'?" return True @property def is_staff(self): return self.staff @property def is_admin(self): return self.admin @property def is_active(self): return self.active class ParentProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) child_first_name = models.CharField(max_length=255) timestamp = models.DateTimeField(auto_now_add=True) student = models.BooleanField(default=False) parent = models.BooleanField(default=False) teacher = models.BooleanField(default=False) active = models.BooleanField(default=True) # can login staff = models.BooleanField(defaul…
has title: Opinion on inheriting a previous model
type: Question
answer count: 1
tagged with: inheritance
favorite count: 0
upvote count: 3
tagged with: model
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/88800766
has comment: http://stackoverflow.com/comment/88800467
has answer: http://stackoverflow.com/a/50900755
score: 3

http://stackoverflow.com/comment/105104376
comment on: http://stackoverflow.com/a/50916186
type: AnswerComment
score: 0
type: Comment
has text: pip3 install jupyter

http://stackoverflow.com/q/50937618
tagged with: api
answer count: 1
has body: I'm trying to crawl down tweets from Netherlands through twitter api, but it returns an empty file and does not show any bug. I know people in Netherlands speak English and use twitter so it does not make sense. Here is my code: The set up part (should be fine): import tweepy import csv import json import pandas as pd from pprint import pprint key_file = 'keys.json' # Loading your keys from keys.json (which you should have filled # in in question 1): with open(key_file) as f: keys = json.load(f) # if you print or view the contents of keys be sure to delete the cell! consumer_key = keys["consumer_key"] consumer_secret = keys["consumer_secret"] access_token = keys["access_token"] access_token_secret = keys["access_token_secret"] auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth, wait_on_rate_limit=True) Here is the function I wrote to get data: def tweet_obtainer(file_name,key_word = None, language = None, tweet_since, tweet_until , geo = None, place = None, tweet_mode = 'extended', retweet = 'false', number_of_tweet = 100): ds_tweets_save_path = file_name + '.json' example_tweets = [t._json for t in tweepy.Cursor(api.search, q= key_word, lang= language, since= tweet_since, until= tweet_until, geocode = geo, place= place, tweet_mode= tweet_mode, retweet = retweet#-filter:nativeretweets ).items(number_of_tweet)]#number of tweets with open(ds_tweets_save_path, "w") as f: json.dump(example_tweets, f) with open(ds_tweets_save_path, "r") as f: example_tweets = json.load(f) return None Here is the line where I implement it on the Netherlands and then I get an empty file which is blizzard: tweet_obtainer("data_netherlands", ["is"],"en","2018-06-01", "2018-06-14",geo = "52.1326, 5.2913, 131km" ) Any English tweet should contain "is" so It should not return empty file!
type: UnansweredQuestion
has title: Why tweepy.Cursor is returning empty file when it should not
tagged with: python
has answer: http://stackoverflow.com/a/50953761
score: 0
tagged with: twitter
tagged with: web-crawler
type: Question

http://stackoverflow.com/a/50864954
answers question: http://stackoverflow.com/q/50864599
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/88733044
upvote count: 1
type: Answer
has body: stack + transpose will get you what you want, with a little of renaming. If index is actually your index, just do df = df.reset_index() import pandas as pd print(df) # index Probability #0 Value1 0.98 #1 Value2 0.90 #2 Value3 0.85 #3 Value4 0.80 df = df.stack().reset_index() # Rename things df.loc[df.level_1 == 'index', 'level_1'] = 'Match' + (df.loc[df.level_1 == 'index', 'level_0']+1).astype('str') df.loc[df.level_1 == 'Probability', 'level_1'] = 'Prob' + (df.loc[df.level_1 == 'Probability', 'level_0']+1).astype('str') df = df.drop(columns='level_0').T.reset_index(drop=True) df is now: 0 1 2 3 4 5 6 7 0 Match1 Prob1 Match2 Prob2 Match3 Prob3 Match4 Prob4 1 Value1 0.98 Value2 0.9 Value3 0.85 Value4 0.8

http://stackoverflow.com/comment/89028408
type: AnswerComment
comment on: http://stackoverflow.com/a/50985990
score: 0
type: Comment
has text: I went though your first varient, and found I could instead return `(result, string)` to backtrack to the input string state, and it works for most cases, but e.g. the `Star` in regex `a*ab` on string `ab` consumes the `a`, so the second `a` can't be matched. Yours works on this, because each repeat of `Star` is a level of recursion that can exit to the next (`cont`) part of the regex. I can't see how to do by returning tuples instead of constructing `cont`s.

openai-gym
tags question: http://stackoverflow.com/q/50978134
type: Tag
tag name: openai-gym

http://stackoverflow.com/comment/88829738
has text: This code looks like it was designed to run on a gray image. You can convert your color image to gray using `skimage.color.rgb2gray`.
type: Comment
comment on: http://stackoverflow.com/q/50909839
type: QuestionComment
score: 2

http://stackoverflow.com/comment/88904559
comment on: http://stackoverflow.com/q/50953131
has text: Not a direct answer to the question, but I will just say that IDLE is not a particularly well-featured editor. You may want to consider installing a dedicated programmer's text editor and configuring it for your Python installation(s). There are many such programs with a wide variety of features and capabilities, and (IMO) IDLE does not compete particularly well with pretty much any of them.
type: QuestionComment
score: 0
type: Comment

http://stackoverflow.com/comment/88878666
type: Comment
type: QuestionComment
score: 0
has text: @zvone If your comment is simply wrong, you should delete it. Saying something is not possible when it is, is harmful. If I just didn't see what you mean, it would be nice if you could clarify the aspect I missed.
comment on: http://stackoverflow.com/q/50936281

http://stackoverflow.com/comment/88800029
has text: What would you recommend me to do in that case? - Because bascially my idea is that etc if there is a password... Just update until the password is gone - then notify for me with a print that there has been removed password. After that update the site and wait until the password is getting changed to password up. Then notify and on and on like that.
comment on: http://stackoverflow.com/a/50899541
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/50924002
has title: Read out subfolder of inbox using exchangelib
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/50927077
tagged with: exchangelib
favorite count: 0
has body: is it possible to read out the body of an email that is in a subfolder of the inbox using exchangelib? If yes, how can I achieve that? I only know that I can get the body of an email which is in the inbox using the following code: for item in account.inbox.all().order_by('-datetime_received')[:1]: print(item.body)
tagged with: python
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/50927077
upvote count: 1
type: Question

http://stackoverflow.com/q/51005282
has answer: http://stackoverflow.com/a/51005632
favorite count: 0
has answer: http://stackoverflow.com/a/51005378
has body: I tried today to make a python discord.py based bot for a bit of fun, and following some random tutorials and copying code it worked great, and I added a few new commands once I'd gotten the hang of it, but apparently randomly most of the commands stopped working, and for some reason now only the bottom most command actually functions in discord, any ideas why this could be? Code: import discord from discord.ext import commands description = 'Tutorial Bot' bot_prefix = '!' client = commands.Bot(description=description, command_prefix=bot_prefix) list_of_strings = ['hello', 'hi'] @client.event async def on_ready(): print('Connected') @client.event async def on_message(message): if message.content.startswith('!what'): await client.send_message(message.channel, 'Huh?') @client.event async def on_message(message): if message.content in list_of_strings: await client.send_message(message.channel, 'Hey there') client.run('*set to code before attempting*') I had set the client.run to the newest code, but whenever I use the bottom list of strings command it works fine, but the !what section doesn't work. I tried reversing them and the same problem persisted, with only the bottom most one working regardless of which order they're in. Is there something obvious I'm probably missing here?
type: UnansweredQuestion
has title: Discord Bot w/ Discord.py skipping lines
tagged with: python
score: 2
tagged with: bots
has comment: http://stackoverflow.com/comment/89004223
upvote count: 3
downvote count: 1
type: Question
tagged with: discord.py
answer count: 2
tagged with: discord

http://stackoverflow.com/q/50875037
possible better answer: http://stackoverflow.com/a/50875299
has comment: http://stackoverflow.com/comment/88751864
score: 0
linked to: http://stackoverflow.com/q/21068454
accepted answer: http://stackoverflow.com/a/50875177
answer count: 2
tagged with: string
has comment: http://stackoverflow.com/comment/88761447
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88751607
tagged with: punctuation
tagged with: python
tagged with: text
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50875177
has answer: http://stackoverflow.com/a/50875299
has title: removing the last punctuation character
type: Question
has body: i know this question is susceptible to be marked as a duplicate, but after searching in the website i didn't find anything that matches what i really want to do. I have a string like this : string = "hey, that's you(this is a test)!" i'm working on a function that removes only the last punctuation mark in any string, not punctuation embedded on a word, nor the leading punctuation signs,this function should also store the word frequencies in a dictionary. This my code so far: def word_counts(string): s = string.lower().split() dic = {} for key in string: key = "".join([l for l in key if l.isalpha()]) if key in dic : dic[key] += 1 else: dic[key] = 1 return dic my code is yelling the following results: {'a': 1, 'hey': 1, 'is': 1, 'test': 1, 'thats': 1, 'youthis': 1} but what i need is: {'a': 1, 'hey': 1, 'is': 1, 'test)': 1, 'that's': 1, 'you': 1, (this': 1} Note that in the word 'test)' the exclamation sign is removed but the parenthesis needs to stay. Any clues about how to do this?? Thank you all in advance EDIT: the comma after "hey" should leave. I should only remove one punctuation sign at a time, so if i find 2 at the end of a word, only one is to be removed.

http://stackoverflow.com/q/50961658
answer count: 1
has answer: http://stackoverflow.com/a/50961890
has comment: http://stackoverflow.com/comment/88920407
linked to: http://stackoverflow.com/q/13187778
tagged with: machine-learning
upvote count: 1
has body: I wanted to implement KNN in python. Till now I have loaded my data into Pandas DataFrame. import pandas as pd from sklearn.neighbors import KNeighborsClassifier train_df = pd.read_csv("creditlimit_train.csv") # train dataset train_df.head() The output of head is SNo Salary LoanAmt Level 101 100000 10000 Low Level 102 108500 11176 Low Level 103 125500 13303 Low Level 104 134000 14606 Low Level 105 142500 15960 Low Level test_df = pd.read_csv("creditlimit_test.csv") test_df.head() The output of head is SNo Salary LoanAmt Level 101 100000 10000 Low Level 102 108500 11176 Low Level 103 125500 13303 Low Level 104 134000 14606 Low Level 105 142500 15960 Low Level neigh = KNeighborsClassifier(n_neighbors=5,algorithm='auto') predictor_features = ['Salary','LoanAmt'] dependent_features = ['Level'] neigh.fit(train_df[predictor_features],train_df[dependent_features]) How do I use the fit function to use salary,loanAmt as predictor to predict the levels for my test_df? Update 1: The levels are 3 : Low, Medium and High
downvote count: 0
accepted answer: http://stackoverflow.com/a/50961890
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/11285613
linked to: http://stackoverflow.com/q/27060098
score: 1
has title: How to implement KNN in python?
favorite count: 0
tagged with: knn
type: Question
tagged with: python

http://stackoverflow.com/comment/88900420
score: 0
has text: in __init__(), add self.cards = []
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50951284

http://stackoverflow.com/q/50889514
has title: Pandas Resampling based on Value exceeding threshold
has answer: http://stackoverflow.com/a/50890696
upvote count: 3
tagged with: pandas
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
downvote count: 0
has body: I have a database with 2 columns. import pandas as pd data = pd.DataFrame({'a':[1,2,1,4,1,1,3,1,4,1,1,1],'b':[5,2,8,3,10,3,5,15,45,41,23,9]}) a b 0 1 5 1 2 2 2 1 8 3 4 3 4 1 10 5 1 3 6 3 5 7 1 15 8 4 45 9 1 41 10 1 23 11 1 9 Is there a pythonic/fastest way to pick out the row indices whenever the cumulative value since the last occurrence exceeds a given threshold for column a? for example, in the above df, if my threshold is like 5, I would get indices 3,6,8. The way I'm currently doing it is loop through every row and then keep track of when values exceed it. I am not enough of a python expert to come up with a potentially (if it exist) better way.. thanks
type: Question
score: 3
tagged with: dataframe

http://stackoverflow.com/q/50894152
score: 1
accepted answer: http://stackoverflow.com/a/50960936
possible better answer: http://stackoverflow.com/a/50894174
type: Question
has answer: http://stackoverflow.com/a/50894174
has title: Pandas Series with different lengths
has comment: http://stackoverflow.com/comment/88788463
has answer: http://stackoverflow.com/a/50894486
downvote count: 0
favorite count: 0
answer count: 3
tagged with: pandas
tagged with: python
has body: Using pandas concat function it is possible to create a series like this: In[230]pd.concat({'One':pd.Series(range(3)), 'Two':pd.Series(range(4))}) Out[230]: One 0 0 1 1 2 2 Two 0 0 1 1 2 2 3 3 dtype: int64 Is it possible to do the same without using concat method? My best approach was: a = pd.Series(range(3),range(3)) b = pd.Series(range(4),range(4)) pd.Series([a,b],index=['One','Two']) But it is not the same, it outputs: One 0 0 1 1 2 2 dtype: int64 Two 0 0 1 1 2 2 3 3 dtype: int64 dtype: object
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50960936
upvote count: 1
type: AnsweredQuestion

http://stackoverflow.com/comment/88863333
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50931843
has text: Thanks for your reply. I have tried changing to the full path which contains the libs and have doubled checked it contains all the .so files, however I still see the error unfortunately
type: AnswerComment

cross-join
type: Tag
tags question: http://stackoverflow.com/q/50960343
tag name: cross-join

http://stackoverflow.com/q/50867244
has answer: http://stackoverflow.com/a/50867314
has comment: http://stackoverflow.com/comment/88736738
has answer: http://stackoverflow.com/a/50867383
accepted answer: http://stackoverflow.com/a/50867383
score: 0
answer count: 2
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88736779
possible better answer: http://stackoverflow.com/a/50867314
has title: Getting specific element(s) from after read from file
tagged with: python
has comment: http://stackoverflow.com/comment/88736869
type: AnsweredQuestion
has body: After I read from file: with open(fileName) as f: for line in f: print(line.split(",")) #split the file into multiple lists How do I get some specific element(s) from those lists? For example, only elements with index[0 to 3], but discard/ignore any elements after that.
has comment: http://stackoverflow.com/comment/88736785
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/88736837
type: Question

http://stackoverflow.com/comment/88913412
score: 0
has text: ... but it is preferable in some way to `print('foooss')` ?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50957744

http://stackoverflow.com/comment/89005040
comment on: http://stackoverflow.com/q/51005796
type: Comment
type: QuestionComment
score: 1
has text: Conda isn't installed via an rpm (witness the `anconda3-5.2.0-Linux-x86_64.sh` in the question).

http://stackoverflow.com/comment/88959886
type: QuestionComment
score: 3
has text: Maybe [`s.split()[5]`](http://rextester.com/DCLK45366)? Well, *the "query[A]" before the link and "from" after the link remains same for every string* means you just want to extract a string between two strings, right? Closing as a dupe.
comment on: http://stackoverflow.com/q/50982397
type: Comment

http://stackoverflow.com/comment/88991077
type: Comment
type: QuestionComment
has text: in list of strings ["james"] is not equal to ['james']
score: 0
comment on: http://stackoverflow.com/q/50998417

http://stackoverflow.com/q/50885861
has comment: http://stackoverflow.com/comment/88788546
score: 0
tagged with: pandas
answer count: 1
tagged with: python
has body: I have a dataframe(df, number of rows: 79446767) like this: Price Volume date 2016-05-01 22:00:00.334338 45.90 20.0 2016-05-01 22:00:00.335312 NaN 1.0 2016-05-01 22:00:00.538377 45.92 1.0 2016-05-01 22:00:00.590386 45.92 1.0 2016-05-01 22:00:00.590493 45.92 1.0 2016-05-01 22:00:00.590493 45.92 1.0 2016-05-01 22:00:00.590493 45.92 1.0 (..omitted rows) I resampled by time(for this: 1 hour) with this dataframe, like: Price Volume close open high low sum date 2016-05-01 22:00:00 45.57 45.90 45.96 45.55 4842.0 2016-05-01 23:00:00 45.66 45.59 45.68 45.56 2009.0 2016-05-02 00:00:00 45.64 45.66 45.68 45.58 1869.0 2016-05-02 01:00:00 45.61 45.64 45.68 45.59 1312.0 2016-05-02 02:00:00 45.58 45.62 45.65 45.55 1504.0 2016-05-02 03:00:00 45.47 45.58 45.61 45.47 1347.0 2016-05-02 04:00:00 45.47 45.48 45.55 45.43 2965.0 (..omitted rows) But it takes about 15 minutes to execute. Is there another way to resample with fast speed? Here is my code: import pandas as pd import numpy as np aggregator = { "Price": ["last", "first", np.max, np.min], "Volume": "sum" } res = df.groupby(pd.Grouper(freq=1H, label='right')).agg(aggregator).dropna(axis=0, how='all')
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50885960
type: Question
tagged with: numpy
has title: Optimizing code resampling with large size tick data
accepted answer: http://stackoverflow.com/a/50885960
tagged with: optimization

http://stackoverflow.com/comment/88861390
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50930916
type: Comment
has text: Assuming the command works, should I be able to see the mounted directory's contents with `ls -la` or something? I tried the command with /c/ and //c/, but neither shows anything. Also where can I find /mnt/temp?

http://stackoverflow.com/a/50923983
type: Answer
has body: a simple query import cx_Oracle con = cx_Oracle.connect('pythonhol/welcome@127.0.0.1/orcl') cur = con.cursor() cur.execute('select * from departments order by department_id') for result in cur: print result cur.close() con.close()
score: 0
answers question: http://stackoverflow.com/q/50923848

http://stackoverflow.com/comment/88939099
type: Comment
type: QuestionComment
has text: show your `settings.py`
comment on: http://stackoverflow.com/q/50971088
score: 0

http://stackoverflow.com/a/50960216
score: 1
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50959926
has body: Try xlsxwriter with pandas. Docs: https://xlsxwriter.readthedocs.io/example_pandas_simple.html import pandas as pd # pip3 install xlsxwriter df = pd.read_csv('http://quickstats.nass.usda.gov/api/api_GET/?key=XXXXXxxxxx&amp;source_desc=CENSUS&amp;short_desc=CORN, GRAIN - PRODUCTION, MEASURED IN BU&amp;year__GE=2012&amp;state_alpha=MN&amp;format=CSV') print("The sum is:",sum(pd.to_numeric(df.Value.replace({',':''},regex=True), errors='coerce').dropna())) # The sum is: 19052800881.0 # Write dataframe to excel writer = pd.ExcelWriter('corn.xlsx', engine='xlsxwriter') df.to_excel(writer, sheet_name='Sheet1') writer.save()
upvote count: 1

http://stackoverflow.com/a/50888351
has comment: http://stackoverflow.com/comment/88778785
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50886428
has body: You just need to add %matplotlib inline at the top of your code if you are running on Jupyter Ipython notebook. You can read more about it here and here. Otherwise, I copied your code and removed matplotlib.use("Agg") , it works for me on Ubuntu 18.04, matplotlib version 2.2.2. Can you specify which version you are using ? Also here is the code, import matplotlib import numpy as np from sklearn.svm import SVR import matplotlib.pyplot as plt #Generate Sample data x = np.sort(5 * np.random.rand(40, 1), axis = 0) y = np.sin(x).ravel() #Add noise to targets y[::5] += 3 * (0.5 - np.random.rand(8)) #create classifier regression model svr_rbf = SVR(kernel="rbf", C=1000, gamma=0.1) svr_lin = SVR(kernel="linear", C=1000, gamma=0.1) svr_poly = SVR(kernel="poly", C=1000, gamma=0.1) #Fit regression model y_rbf = svr_rbf.fit(x,y).predict(x) y_lin = svr_lin.fit(x,y).predict(x) y_poly = svr_poly.fit(x,y).predict(x) #Plotting of results lw = 2 plt.scatter(x, y, color="darkorange", label="data") plt.plot(x, y_rbf, color="navy", lw=lw, label="RBF Model") plt.plot(x, y_lin, color="c", lw=lw, label="Linear Model") plt.plot(x, y_poly, color="cornflowerblue", lw=lw, label="Polynomial Model") plt.xlabel("data") plt.ylabel("target") plt.title("Support Vector Regression") plt.legend() plt.show()
has comment: http://stackoverflow.com/comment/88778558
has comment: http://stackoverflow.com/comment/88779085
type: Answer
has comment: http://stackoverflow.com/comment/88778811
has comment: http://stackoverflow.com/comment/88778213
has comment: http://stackoverflow.com/comment/88778782
has comment: http://stackoverflow.com/comment/88778943
has comment: http://stackoverflow.com/comment/88778229
has comment: http://stackoverflow.com/comment/88778536
has comment: http://stackoverflow.com/comment/88778510
has comment: http://stackoverflow.com/comment/88778699
score: 0
accepted answer of: http://stackoverflow.com/q/50886428

http://stackoverflow.com/comment/88938491
comment on: http://stackoverflow.com/q/50965287
type: Comment
has text: @WiktorStribiżew Do you think you could comment on the edit I made above? Thanks!
score: 0
type: QuestionComment

http://stackoverflow.com/a/50935231
upvote count: 11
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50934156
type: Answer
has comment: http://stackoverflow.com/comment/88871378
answers question: http://stackoverflow.com/q/50934156
has body: Setting the value to readonly is not enough. This only has impact on how the HTML has been rendered. Depending on what the browser does in that case, it is possible that the user can still edit the form field. But nevertheless, even if the user can not edit the form, a person with some knowledge of how HTTP requests work, can still maliciously enter value in the request, and therefore thus change values in the database that are not supposed to get changed. django-1.9 and higher Since djang-1.9, you can alter the .disabled attribute on a form. In that case not only will this render the field as disabled or readonly, it will also prevent a person from maliciously entering values. If the user enters some data, that data is simply ignored (for that specific field). So we can write: def new_issue(request, project_id): if request.method == 'POST': form = IssueForm(request.POST, initial={'project': project_id}) form.fields['project'].disabled = True if form.is_valid(): issue = form.save(commit=False) issue.author = request.user issue.save() return redirect('project:issue_tracker:issue_detail',project_id=project_id,issue_id=issue.id) else: form = IssueForm(initial={'project': project_id}) form.fields['project'].disabled = True template = 'issue_tracker/issue/new_issue.html' context = {'form': form,'project_id':project_id} return render(request, template, context) Note that you will probably need some initial or an instance, since otherwise, there is no data at all to fallback on. Moving this into the form In the above code fragment, we wrote the same expression twice: each time we construct a form. This is against the DRY principle. Typically you specify the field, or - for example in the case the field is not always disabled, you can specify that by overriding the __init__ constructor. For example: class IssueForm(forms.ModelForm): def __int__(self, *args, disabled_project=True, **kwargs): super(IssueForm, self).__init__(*args, **kwargs) self.fields['project'].disabled = d…
downvote count: 0
score: 11
has comment: http://stackoverflow.com/comment/88875070
has comment: http://stackoverflow.com/comment/111597321

http://stackoverflow.com/comment/88919674
comment on: http://stackoverflow.com/a/50961402
type: Comment
has text: I'm getting this error though: `AttributeError: 'DataFrameGroupBy' object has no attribute 'data'`
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88835842
has text: i have a data set that is called by the another function, and in this function the img is called, it works fine without the threshold, but when i add it gives this error.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50917877
score: 1

http://stackoverflow.com/q/50970063
score: 0
answer count: 2
tagged with: pandas
possible better answer: http://stackoverflow.com/a/50971385
has title: Adding Rows in pandas data frame based on multilevel index
has answer: http://stackoverflow.com/a/50971385
tagged with: python-3.x
tagged with: python
has answer: http://stackoverflow.com/a/50971295
accepted answer: http://stackoverflow.com/a/50971295
type: AnsweredQuestion
has body: i have a dataframe like : (multilevel)index aaa,aaa,aaa,bbb,bbb,bbb,ccc,ccc Column 1, 1 , 1 , 0, 1, 0, 1 , 1 i want to add rows based on index so that i get: index aaa, bbb, ccc column 3, 1, 2 is it possible ? any help would be appreciated. Thank you
type: Question

http://stackoverflow.com/q/50982684
tagged with: scikit-learn
score: -7
favorite count: 0
has comment: http://stackoverflow.com/comment/88964157
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88962225
has comment: http://stackoverflow.com/comment/88963250
has answer: http://stackoverflow.com/a/50985638
has comment: http://stackoverflow.com/comment/88964450
has body: I am working on a project, where I have to detect duplicates present in the dataset. Just to create the model, I have taken dataset 20newsgroup from sklearn. from sklearn.datasets import fetch_20newsgroups categories = [ 'alt.atheism', 'talk.religion.misc', 'comp.graphics', 'sci.space', ] print("Loading 20 newsgroups dataset for categories:") data_train = fetch_20newsgroups(subset='train', categories=categories, shuffle=True, random_state=42) data_test = fetch_20newsgroups(subset='test', categories=categories, shuffle=True, random_state=42) print('data loaded') but this dataset has unique entries, so I have to create duplicates by myself. Here data_train is an array of documents randomly selected for training the model. Does anyone know what changes to be made to duplicate these documents randomly so in the end I get a dataset with duplicate entries?
type: Question
has comment: http://stackoverflow.com/comment/88963557
has title: How to randomly duplicate some documents while importing the data set?
has comment: http://stackoverflow.com/comment/88962866
downvote count: 14
upvote count: 7
answer count: 1

http://stackoverflow.com/q/50882720
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50898821
tagged with: flask-wtforms
tagged with: python
has body: I am looking to build a multiple choice quiz using python/flask/flask-wtf. I am successfully able to pull random questions from a database as well as pull random choices as the possible answers. I am using a for loop on the template page that first displays the question and then the possible answers. Here is my template. &lt;div class="quote-block"&gt; {% for quote in quotes %} {{ quote.line_text }} &lt;form method="POST"&gt; {{ form.hidden_tag() }} {{ form.question }} &lt;input type="submit"&gt; &lt;/form&gt; {% endfor %} &lt;/div&gt; My problem is that the possible answers are the same for each question and in the same order. I understand why this is happening. The query into the database for the RadioField choices is only happening once. And then the results of that query are being pulled for each instance of the for loop. Here is my view route. @app.route('/quiz/', methods=['POST', 'GET']) def quiz(): quotes = Quotes.query.order_by(func.rand()).limit(5) form = Quiz() form.question.choices = [(choice.speaker_id, choice.speaker) for choice in Characters.query.order_by(func.rand()).limit(4)] return render_template('television/quiz.html', form=form, quotes=quotes, options=options) And my form. class Quiz(FlaskForm): question = RadioField('Label', choices=[]) Like I said, all of this works. I just can't figure out how to start a new choices query for each question. Any help would be greatly appreciated. Thanks!
type: AnsweredQuestion
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/50995761
accepted answer: http://stackoverflow.com/a/50995761
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/50898821
has title: Python/Flask-WTF - How can I randomize the choices from dynamic RadioField?

http://stackoverflow.com/comment/88900373
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50951284
type: Comment
has text: exactly where definition?

http://stackoverflow.com/a/50933783
has comment: http://stackoverflow.com/comment/88867668
has comment: http://stackoverflow.com/comment/88869470
answers question: http://stackoverflow.com/q/50933647
has body: One solution is to add a global boolean to track whether the user has failed 3 times already or not def main(): notFailedYet = True #miles to kilometers input miles_km = float(input('Please enter how many miles you would like to convert.')) Within each function place an if statement to check if they've failed or not if notFailedYet: tries = 0 while miles &lt;0 and tries &lt;3: print('Error: enter a valid value') miles = float(input('Please enter how many miles you would like to convert.')) tries+=1 if tries ==3 and miles &lt;0: notFailedYet = False #Set this to false so that the other functions don't execute print('Error: valid value not entered.') return miles if tries &lt;=2: km_miles = (miles *1.6) return print(miles, 'miles is equal to', format(km_miles ,',.2f'), 'kilometers.')
type: Answer
score: 0

http://stackoverflow.com/comment/88911113
comment on: http://stackoverflow.com/a/50872819
type: AnswerComment
score: 0
type: Comment
has text: Could you figure it out how to pass the function to single columns?

http://stackoverflow.com/comment/88924074
type: QuestionComment
has text: @Kasramvd you should make that an answer (but extend it with an example or two)
comment on: http://stackoverflow.com/q/50963466
score: 0
type: Comment

http://stackoverflow.com/a/50910026
score: 0
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/50909538
has body: First output crunch to file. This has the side benefit you can actually check what crunch has generated. You might however skip the file. crunch 1 5 &gt;&gt; pas.txt Load the file into environment array (BASH 4 example) readarray pas_a &lt; ./pas.txt Execute once per password for pas in "${pas_a[@]}" do ./python pex.py "$pas" &amp; done &lt; ./pas.txt Remove the &amp; to make it sequential rather than parallel. Clean the array from environment if you like.
answers question: http://stackoverflow.com/q/50909538

http://stackoverflow.com/comment/88895585
comment on: http://stackoverflow.com/q/50947008
score: 0
type: Comment
type: QuestionComment
has text: Sure, but the paginated data is just a list of something (followers?), right? Break the list down into individual rows and insert them individually into a new table with a reference back to the rowid in `twitter_data` that they correspond to. That's the sort of thing databases are made for.

http://stackoverflow.com/comment/88790906
type: QuestionComment
comment on: http://stackoverflow.com/q/50895256
score: 1
has text: `self.gameObject = None` does not cause a memory leak. There is no need to call `del` (and `del` wouldn't help anyway). Python's garbage collector maintains a reference count, so an object which is not referenced gets deleted from memory automatically There are other things which may be wrong: some other object may be holding a reference to `self.gameObject` (that could cause a leak), or you may be detecting memory consumption incorrectly (this is not trivial). BTW it seems wrong to have `self.gameObject = Game()` both in `__init__` and in `method_start`. One of them is probably not needed.
type: Comment

http://stackoverflow.com/a/50897862
has comment: http://stackoverflow.com/comment/88796742
type: AcceptedAnswer
has body: It's not exactly that simple to deal with NaN values. It requires analyses of the data before taking any further step to deal with the NaN values. There are various ways you can deal with these missing values (the following is not an exhaustive list): Ignore missing values altogther : the problem with this approach is that the missing rows might contain important information in other columns and ignoring them would lead to incomplete analyses Replace them with another value : this one of the commonly used approaches, but the choice of the value that you will use to replace will affect your overall analysis. You could replace them with say mean, or say a placeholder value (like -1) which you know never occurs throughout the column. Using regression to substitute the values **Using KNN to substitue values ** You can take a look at the following links, to get a more better idea Handling missing data 7 ways of handling missing data A guide to data exploaration Imputing missing values in Python Additionaly you can take a look at the official sklearn documentation for imputing missing values. Update : You can ignore the NaN values while performing StandardScalar like this import numpy as np import pandas as pd from sklearn.preprocessing import StandardScaler #Create a dataframe df = pd.DataFrame({'col1': [0, np.nan, 2, 3, np.nan, 4, 5, np.nan, 6, 7, np.nan]}) #Get the index of null values null_values = d['col1'].isnull() #Perform standard scalar on only non-NaN values df.loc[~null_values, ['col1']] = StandardScaler().fit_transform(df.loc[~null_values, ['col1']]) Output col1 0 -1.728498 1 NaN 2 -0.832240 3 -0.384111 4 NaN 5 0.064018 6 0.512148 7 NaN 8 0.960277 9 1.408406 10 NaN Then fill nan values using df.fillna df.fillna(-1) outout col1 0 -1.728498 1 -1.000000 2 -0.832240 3 -0.384111 4 -1.000000 5 0.064018 6 0.512148 7 -1.000000 8 0.960277 9 1.408406 10 -1.000000
accepted answer of: http://stackoverflow.com/q/50897516
upvote count: 5
answers question: http://stackoverflow.com/q/50897516
type: Answer
has comment: http://stackoverflow.com/comment/88795404
downvote count: 0
has comment: http://stackoverflow.com/comment/88796869
has comment: http://stackoverflow.com/comment/88796719
score: 5

http://stackoverflow.com/q/50876776
has answer: http://stackoverflow.com/a/50876870
tagged with: string
score: -4
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/50876950
has comment: http://stackoverflow.com/comment/88755453
tagged with: python
has title: How to remove list multiple brackets while reading csv
favorite count: 0
answer count: 5
type: UnansweredQuestion
has body: with open("D:\Vocabulary.csv","r") as CSV_file: csv_reader=csv.reader(CSV_file) for line in csv_reader: print(line) I read a csv file (in the file I just had one column contain all the vocabularies)and print the result which contains multiple brackets like this: ["apple"],["school"],["big"],[list] So how can I get ["apple","school","big","list"]?
has comment: http://stackoverflow.com/comment/88755540
has answer: http://stackoverflow.com/a/50877230
has comment: http://stackoverflow.com/comment/88755514
has answer: http://stackoverflow.com/a/50877221
has answer: http://stackoverflow.com/a/50876903
type: Question
downvote count: 4
upvote count: 0

http://stackoverflow.com/comment/89013959
type: Comment
has text: why is the code you posted not good for you? looks like a fine way to remove all dashes
comment on: http://stackoverflow.com/q/51010647
score: 4
type: QuestionComment

http://stackoverflow.com/q/50867356
tagged with: pandas
has title: Eliminate % Symbol While Using Selenium Scraper (Python)
has body: Below is a selenium web scraper that loops through the different tabs of this website page (https://www.fangraphs.com/leaders.aspx?pos=all&amp;stats=bat&amp;lg=all&amp;qual=y&amp;type=8&amp;season=2018&amp;month=0&amp;season1=2018&amp;ind=0), selects the "export data" button, downloads the data, adds a yearid column, then loads the data into a MySQL table. import sys import pandas as pd import os import time from datetime import datetime from selenium import webdriver from selenium.webdriver.firefox.firefox_profile import FirefoxProfile from sqlalchemy import create_engine button_text_to_url_type = { 'dashboard': 8, 'standard': 0, 'advanced': 1, 'batted_ball': 2, 'win_probability': 3, 'pitch_type': 4, 'pitch_values': 7, 'plate_discipline': 5, 'value': 6 } download_dir = os.getcwd() profile = FirefoxProfile("C:/Users/PATHTOFIREFOX") profile.set_preference("browser.helperApps.neverAsk.saveToDisk", 'text/csv') profile.set_preference("browser.download.manager.showWhenStarting", False) profile.set_preference("browser.download.dir", download_dir) profile.set_preference("browser.download.folderList", 2) driver = webdriver.Firefox(firefox_profile=profile) today = datetime.today() for button_text, url_type in button_text_to_url_type.items(): default_filepath = os.path.join(download_dir, 'Fangraphs Leaderboard.csv') desired_filepath = os.path.join(download_dir, '{}_{}_{}_Leaderboard_{}.csv'.format(today.year, today.month, today.day, button_text)) driver.get( "https://www.fangraphs.com/leaders.aspx?pos=all&amp;stats=bat&amp;lg=all&amp;qual=0&amp;type={}&amp;season=2018&amp;month=0&amp;season1=2018&amp;ind=0&amp;team=&amp;rost=&amp;age=&amp;filter=&amp;players=".format( url_type)) driver.find_element_by_link_text('Export Data').click() if os.path.isfile(default_filepath): os.rename(default_filepath, desired_filepath) print('Renamed file {} to {}'.format(default_filepath, desired_filepath)) else: sys.exit('Error, unable to locate file at {}'.format(default_filepath)) df = pd.rea…
score: 0
type: UnansweredQuestion
tagged with: selenium
tagged with: web-scraping
tagged with: python
has answer: http://stackoverflow.com/a/50869426
has answer: http://stackoverflow.com/a/50867381
tagged with: mysql
type: Question
answer count: 2

http://stackoverflow.com/comment/88735550
score: 0
type: AnswerComment
type: Comment
has text: Does someone know how to add line breaks in comments ?
comment on: http://stackoverflow.com/a/50866513

http://stackoverflow.com/comment/88902872
type: QuestionComment
comment on: http://stackoverflow.com/q/50936222
has text: Hi Andrew, you could check [this](https://plot.ly/python/3d-surface-coloring/). It seems to me that in this example the main problem is to transform the given data in `(x,y,z)` coordinates
score: 1
type: Comment

http://stackoverflow.com/a/50900869
answers question: http://stackoverflow.com/q/50877053
accepted answer of: http://stackoverflow.com/q/50877053
type: AcceptedAnswer
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/88858153
has body: chromdriver is failing to launch your Chrome browser. This is most likely due to using incompatible versions of Chrome browser and Chromedriver. You didn't mention the version of Selenium bindings or Chrome browser you are using, but your stacktrace shows: chromedriver=2.35.528139 Chromedriver 2.35 only supports Chrome versions 62-64. The latest version (currently 2.40), supports Chrome versions 66-68. If you upgrade to that, this should be solved. In general, every time Chrome upgrades itself, you will need to replace Chromedriver with a newer version... or at least check compatibility. You can see which versions a Chromedriver supports by checking the release notes on the Downloads page: http://chromedriver.chromium.org/downloads

http://stackoverflow.com/comment/118716095
type: Comment
type: QuestionComment
has text: [q than a](https://stackoverflow.com/users/3008612) posted an [Answer](https://stackoverflow.com/a/67028851) saying "Sklearn-porter is a partial solution. [https://github.com/nok/sklearn-porter](https://github.com/nok/sklearn-porter)"
comment on: http://stackoverflow.com/q/50897244
score: 0

http://stackoverflow.com/q/50867848
score: 1
has answer: http://stackoverflow.com/a/50868558
type: Question
has answer: http://stackoverflow.com/a/50869314
has title: Class method not finding the argument given
downvote count: 0
linked to: http://stackoverflow.com/q/17134653
has comment: http://stackoverflow.com/comment/88737877
answer count: 3
favorite count: 0
has comment: http://stackoverflow.com/comment/88740413
accepted answer: http://stackoverflow.com/a/50869314
has comment: http://stackoverflow.com/comment/88737835
has body: I just learned how to create Binary Search Trees in C#. I decided to try to code the same thing in Python 3.x. However, when I got to my Print method, this error showed up: Traceback (most recent call last): File "C:\Users\danie\Desktop\Python\BinarySearchTree\BinarySearchTree\BinarySearchTree.py", line 62, in &lt;module&gt; b.BSTprint() File "C:\Users\danie\Desktop\Python\BinarySearchTree\BinarySearchTree\BinarySearchTree.py", line 46, in BSTprint BST.Print(current) TypeError: Print() missing 1 required positional argument: 'cur' The problem, I did put in the required positional argument. I tried fixing it myself and found that if I remove the self parameter, it works. However, I always thought you needed to have that self parameter in all of the class methods. I have no idea what is wrong. Here is the code import random class BST: #Node class class Node: data = None left = None right = None def __init__(self, d): self.data = d first = None #Add method def Add(self, d): #Checks if the Binary Search Tree is empty if(BST.first == None): BST.first = BST.Node(d) #Debugging purposes #print("Added: {}".format(d)) return; else: newNode = BST.Node(d) cur = BST.first while(cur != None): if(cur.data &lt; newNode.data): if(cur.left == None): cur.left = newNode #print("Added: {}".format(newNode.data)) return else: cur = cur.left elif(cur.data &gt; newNode.data): if(cur.right == None): cur.right = newNode #print("Added: {}".format(newNode.data)) return else: cur = cur.right else: print("Value already in BST") return def BSTprint(self): current = BST.first if(current == None): return BST.Print(current) def Print(self, cur): if(cur.left != None): BST.Print(cur.left) print(cur.data) if(cur.right != None): BST.Print(cur.right) b = BST() #Adds values into BST for i in range(10): x = random.randint(1,100) b.Add(x) b.BSTprint()
has comment: http://stackoverflow.com/comment/88738199
upvote count: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/50867931
has answer: http://stackoverflow.com/a/50867931
type: AnsweredQuestion

http://stackoverflow.com/q/50904219
answer count: 3
has answer: http://stackoverflow.com/a/50905206
accepted answer: http://stackoverflow.com/a/50905206
has comment: http://stackoverflow.com/comment/88808449
tagged with: python
has answer: http://stackoverflow.com/a/50904361
has body: The function Capture(filename) reads the output filename.txt and dumps out the necessary stuff into a Data.csv file. But each time I call the Capture function, the data that gets dumped is rewritten in the same row. def Capture(filename): impedance = 0 losses = {} frequencies = {} Xtalk = {} rows = [] with open(PostProcessingFolder + '\Output_' + filename +'_LOG.txt') as f: for l in f: if l.startswith('Impedance = '): v = l[12:-7] impedance = float(v) if l.startswith('Xtalk'): m = f.next() n = f.next() a = m.find('Step response Next') b = m.find('mV', a) frequencies[l + "Step response Next"] = str(m[a+20:b].strip()) c = n.find('Step response Fext peak') d = n.find('@', c) e = n.find('inches', d) g = n.find('mV', e) frequencies[l + "Step response Fext peak @" + str(n[d+1:e].strip()) + "inches"] = str(n[e+7:g].strip()) if l.startswith('Loss per inch'): start = l.find('@') stop1 = l.find('GHz', start) stop2 = l.find('dB', start) frequencies['filename'] = filename frequencies['impedance (Ohms)'] = impedance frequencies["Loss per inch @" + str(float(l[start+1:stop1].strip())) + "GHz"] = float(l[stop1+5:stop2].strip()) rows.append(frequencies) print(rows) df = pd.DataFrame(rows) #df.append(df, ignore_index=True) df.to_csv('Data.csv') Is there a way i can add the data to the next consecutive row each time this function is called?
type: AnsweredQuestion
type: Question
possible better answer: http://stackoverflow.com/a/50904361
score: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/50904619
has title: Append to next row each time function called

http://stackoverflow.com/a/50936312
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50935403
type: AcceptedAnswer
downvote count: 0
has body: A Similar Question is already there: How do you create different variable names while in a loop? In your case, you have to loop through the array of tuples: tables= rec.array([('table1',), ('table2',), ('table3',), ('table4',), ('table5',)], dtype=[('table_name', 'O')]) I used a 'numpy' array for this, but should work on your array too, this is the code I used: import numpy as np tables = np.asarray([('table1',), ('table2',), ('table3',), ('table4',), ('table5',)], dtype=[('table_name', 'O')]) for i in range(len(tables)): globals()[str(tables[i][0])] = [] Output was: print(table1) [] The tables[i][0] part is to accessing the first element of the tuple, which is the first element of the 'i' position of the array globals() is to create it a global variable, otherwise it would just be a string, if you access it with something like tables[i][0] and assigning [] to it would just change the original array
type: Answer
answers question: http://stackoverflow.com/q/50935403
score: 1

http://stackoverflow.com/q/50992617
has answer: http://stackoverflow.com/a/50992864
upvote count: 1
has title: AttributeError: 'NoneType' object has no attribute 'lower' and warning
has comment: http://stackoverflow.com/comment/88979950
score: 0
answer count: 1
downvote count: 1
tagged with: python
favorite count: 0
tagged with: python-3.x
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88980011
accepted answer: http://stackoverflow.com/a/50992864
has body: I was trying to make a simple program to extract words from paragraphs in a web page. my code looks like this - import requests from bs4 import BeautifulSoup import operator def start(url): word_list = [] source_code = requests.get(url).text soup = BeautifulSoup(source_code) for post_text in soup.find_all('p'): cont = post_text.string words = cont.lower().split() for each_word in words: print(each_word) word_list.append(each_word) start('https://lifehacker.com/why-finding-your-passion-isnt-enough-1826996673') First I am getting this warning - UserWarning: No parser was explicitly specified, so I'm using the best available HTML parser for this system ("html.parser"). This usually isn't a problem, but if you run this code on another system, or in a different virtual environment, it may use a different parser and behave differently. The code that caused this warning is on line 17 of the file D:/Projects/Crawler/Main.py. To get rid of this warning, change code that looks like this: BeautifulSoup(YOUR_MARKUP}) to this: BeautifulSoup(YOUR_MARKUP, "html.parser") markup_type=markup_type)) and then there is this error in the end: Traceback (most recent call last): File "D:/Projects/Crawler/Main.py", line 17, in &lt;module&gt; start('https://lifehacker.com/why-finding-your-passion-isnt-enough-1826996673') File "D:/Projects/Crawler/Main.py", line 11, in start words = cont.lower().split() AttributeError: 'NoneType' object has no attribute 'lower' I have tried searching, but not able to resolve or understand the problem.
has comment: http://stackoverflow.com/comment/88979961
type: Question

http://stackoverflow.com/comment/89092090
score: 0
type: Comment
type: QuestionComment
has text: "they even have same ID" - [no they don't](https://stackoverflow.com/questions/3877230/why-does-id-id-and-id-id-in-cpython).
comment on: http://stackoverflow.com/q/51003904

http://stackoverflow.com/q/50883917
type: Question
downvote count: 0
tagged with: keras
answer count: 1
has answer: http://stackoverflow.com/a/50884034
favorite count: 0
type: UnansweredQuestion
tagged with: machine-learning
upvote count: 1
tagged with: python
has body: In an LSTM network I'm passing as feature an array of the form X.shape (350000, 240, 1) With a binary categorical target of the form y.shape (350000, 2) How can I estimate the optimal batch size to minimize learning time without losing accuracy? Here's the setup: model = Sequential() model.add(LSTM(25, input_shape=(240, 1))) model.add(Dropout(0.1)) model.add(Dense(2, activation='softmax')) model.compile(loss="binary_crossentropy", optimizer="rmsprop") model.fit(X_s, y_s, epochs=1000, batch_size=512, verbose=1, shuffle=False, callbacks=[EarlyStopping(patience=10)])
score: 1
has title: Keras - LSTM Optimal Batch Size
tagged with: tensorflow

http://stackoverflow.com/a/51006400
has comment: http://stackoverflow.com/comment/89006187
answers question: http://stackoverflow.com/q/51006347
type: Answer
accepted answer of: http://stackoverflow.com/q/51006347
downvote count: 1
score: 3
upvote count: 4
type: AcceptedAnswer
has body: Use re.sub with a callback that performs the actual replacement: import re list_of_strings = [...] p = re.compile('^ +') for i, l in enumerate(list_of_strings): list_of_strings[i] = p.sub(lambda x: x.group().replace(' ', '&amp;nbsp;'), l) print(list_of_strings) ['&amp;nbsp;1 white space before string', '&amp;nbsp;&amp;nbsp;2 white spaces before string', '&amp;nbsp;&amp;nbsp;&amp;nbsp;3 white spaces before string' ] The pattern used here is '^ +' and will search for, and replace whitespaces as long as they're at the start of your string.

http://stackoverflow.com/comment/89069064
type: Comment
has text: This can be very task-specific, your best bet is to give it a try;) A field that tries to handle very small numbers of training data is called "one-short learning".
comment on: http://stackoverflow.com/a/51022201
type: AnswerComment
score: 0

http://stackoverflow.com/comment/88771889
comment on: http://stackoverflow.com/q/50884989
has text: When you assign a value to a variable in Python, it doesn't copy the value; the variable just becomes a new name for the same value. So, `a` and `df.PercChange` are the exact same `Series`., and a change to one affects the other. If you want to make a copy, you have to say so explicitly. Pandas, Numpy, and other libraries have specific ways to do different kinds of copying, while the `copy` module in the stdlib has the general functions `copy.copy` and `copy.deepcopy`; you have to decide what exactly you want in each case.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/50950553
answers question: http://stackoverflow.com/q/50931988
score: 0
has body: The problem is your vuln_list is only 1 dimensional and in the line vuln_list.append(entry.link + entry.title) you concat the two strings to one, ie. your vuln_list contains 109 entries (each containing a "linktitle"). So I would build a two dimensional list and then either skip your second for loop and use c.executemany. Or keep it but then use c.execute('INSERT...', entry), NOTE: the argument should be entry and not the complete list, cause otherwise all records would be inserted 109 times.
type: Answer

http://stackoverflow.com/q/50925109
answer count: 1
downvote count: 0
has body: I have a my_yaml.yml file with the following content: my_yaml: person: &gt; John|Doe|48, Jack|Black|39 skills: - name: superhero abilities: - swim - run special_chars: - '! | " "' - '+ | " "' - '\ | " "' - 'Á | "A"' - 'É | "E"' - 'Ű | "U"' - 'Û | "U"' I want to load it then dump into a my_yaml_new.yml file having totally the same format &amp; characters as the original input file has. My code is: import yaml my_yaml = yaml.load(open('my_yaml.yml', encoding='utf8')) # without "utf8" encoding I get "'charmap' codec can't decode byte..." error I can dump it into console but 1) order of abilities &amp; name has changed :( yaml.dump(my_yaml, default_flow_style=False, allow_unicode=True) Result is: 'my_yaml:\n person: &gt;\n John|Doe|48, Jack|Black|39\n skills:\n - abilities:\n - swim\n - run\n name: superhero\n special_chars:\n - \'! | " "\'\n - + | " "\n - \\ | " "\n - Á | "A"\n - É | "E"\n - Ű | "U"\n - Û | "U"\n' And when I try to dump into a file: with open('my_yaml_new.yml', 'w') as outfile: yaml.dump(my_yaml, outfile, default_flow_style=False, allow_unicode=True) 2) I get the following error due to character Û: UnicodeEncodeError: 'charmap' codec can't encode character '\xdb' in position 0: character maps to undefined If I delete this line from the input my_yaml.yml file then above dump is successful, but 3) my multiple lines at person string go into one line :( my_yaml: person: &gt; John|Doe|48, Jack|Black|39 skills: - abilities: - swim - run name: superhero special_chars: - '! | " "' - + | " " - \ | " " - Á | "A" - É | "E" - Ű | "U" 4) And also my single quotes (') are disappeared from special_chars :( 5) And also note that elements of skills has no indentation :( I've tried these solutions with no success. And nor import ruamel.yaml as yaml has helped. UPDATE OK, the following great package solves problems 1) &amp; 4), and I can replace &gt; to | at multi line values so 3) is also solved. And maybe 5) is not a huge problem. But I still struggle with special char…
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/51000924
accepted answer: http://stackoverflow.com/a/51000924
upvote count: 1
has title: Python YAML dump special character and multiple lines
tagged with: ruamel.yaml
type: AnsweredQuestion
score: 1
tagged with: pyyaml
type: Question
linked to: http://stackoverflow.com/q/8640959
tagged with: yaml

http://stackoverflow.com/q/50980459
answer count: 1
favorite count: 0
tagged with: python
has body: I have over 100,000 files spread across multiple directories and right now i can read names and path to each file using nested for loop, like this, for root, dirs, files in os.walk('python/Lib/email'): for file in files: # some work here is there anyway to achieve this without using a nested loop? it is taking longer than we expected to read the amount of files we have
type: AnsweredQuestion
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/88956538
has comment: http://stackoverflow.com/comment/88956563
type: Question
has comment: http://stackoverflow.com/comment/88956686
has comment: http://stackoverflow.com/comment/88956667
has title: read file and folders without using a nested loop
has comment: http://stackoverflow.com/comment/88956730
upvote count: 1
has answer: http://stackoverflow.com/a/50980913
accepted answer: http://stackoverflow.com/a/50980913

http://stackoverflow.com/comment/88870273
has text: @Gderu - You might find this interesting: https://stackoverflow.com/a/2862176/8747 Especially, "*Use a buffer large enough to hold the biggest packet that your application-level protocol ever sends*".
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50934884

frameworks
tags question: http://stackoverflow.com/q/50950973
tag name: frameworks
type: Tag
tags question: http://stackoverflow.com/q/50962120

fractions
type: Tag
tags question: http://stackoverflow.com/q/50893482
tag name: fractions

http://stackoverflow.com/q/50995385
type: Question
tagged with: fpdf
possible better answer: http://stackoverflow.com/a/77048187
answer count: 2
has comment: http://stackoverflow.com/comment/89089887
has answer: http://stackoverflow.com/a/77048187
upvote count: 7
tagged with: http://stackoverflow.com/tag/pdf
has answer: http://stackoverflow.com/a/50995571
accepted answer: http://stackoverflow.com/a/50995571
has title: Python: Coloring cells in FPDF is not working?
favorite count: 0
has body: I'm using the FPDF library to create a PDF, and I was looking to color the cells on my document. I looked through the API and found out that this is the way to do it: fpdf.set_fill_color(r: int, g: int = -1, b: int = -1) So I go ahead and do this in my script: pdf = FPDF() pdf.add_page() pdf.set_font('Arial', 'B', 7) pdf.set_fill_color(0, 0, 255) pdf.cell(190, 6, 'Testing...', 1, 1, 'L') pdf.output('Color.pdf', 'F') And the color does not change. Everything else works fine, I just get a white cell instead of one that is colored blue. No errors are thrown either. Am I doing something wrong or is this PyFPDF malfunctioning? EDIT: Added pdf.add_page() and pdf.output('Color.pdf', 'F') to this question (forgot to do it here, had it in my script).
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 7

http://stackoverflow.com/a/50879259
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50878717
answers question: http://stackoverflow.com/q/50878717
type: Answer
upvote count: 2
has comment: http://stackoverflow.com/comment/88807636
has body: You could create a dictionary that maps all of the possible time frequencies to a number, where smaller numbers indicate it's a higher frequency. This allows you to map the same frequency, with a different description to the same number. Then just create a function to compare dct = {'N': 0, 'U': 1, 'us': 1, 'L': 2, 'ms': 2} Then you can use it to map the outputs to compare. dct['us'] &lt; dct['U'] #False dct['us'] = dct['U'] #True
score: 2

http://stackoverflow.com/q/50936400
tagged with: python
type: UnansweredQuestion
type: Question
has body: I am new to Python, so this might seem trivial. I've search all over the place to find an answer to my problem, but I can't seem to find it. I have a script, that is like a mini Hypeshade window and its main function is to create materials and load all the texture files that the user chose in one click. I want to have an option though for when the user wants to connect a noise or a checker for example to one of the file inputs (like bump, normal, etc.). This is done in maya by calling the "createRenderNode" window. Now, I have it workning and it connects to the input that I want to, but I also want to get the name of this file in the corresponding textField in my UI which it doesn't, since, when my function runs, it gets an empty string, as nothing is connected to it yet. Here is the code I have (I have tried so many iterations): # Error: 'NoneType' object is not iterable # Traceback (most recent call last): # File "&lt;maya console&gt;", line 1, in &lt;module&gt; # File "&lt;maya console&gt;", line 49, in brwa # TypeError: 'NoneType' object is not iterable # import maya.cmds as cmds import pymel.core as pm def UI(): if cmds.window("MatWindow", exists = True): cmds.deleteUI("MatWindow") mainwindow = cmds.window("MatWindow", t="Dummy UI", bgc=(0.2,0.2,0.2), mnb = False, mxb = False) cmds.columnLayout() cmds.rowColumnLayout(nr = 1) cmds.textFieldGrp('mtNameTxt', l = "Material Name") cmds.setParent ( '..' ) cmds.columnLayout() cmds.button("createlamb", l = "Create Lambert", c = 'lamb()') cmds.setParent ( '..' ) cmds.rowColumnLayout('albclm', nr = 1) cmds.textFieldGrp('albtxt', l = "Albedo", pht = "Albedo Map") cmds.iconTextButton('conna', w = 25, h = 20, i = "navButtonUnconnected.png", c = 'brwa()') cmds.setParent( '..' ) cmds.separator(h = 20) cmds.text("Insert a name first, then create the lambert, then try to load a texture") cmds.showWindow() cmds.window("MatWindow", e = 1, w=550, h=150, sizeable = 0) UI() #=========== Lambert ===========# def lamb(): matName = cmd…
score: 0
has title: CreateRenderNode in maya and update the custom UI
answer count: 1
tagged with: maya
has answer: http://stackoverflow.com/a/50941626

http://stackoverflow.com/a/62765748
score: 4
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/131426694
answers question: http://stackoverflow.com/q/50876505
type: Answer
upvote count: 4
has comment: http://stackoverflow.com/comment/111917878
accepted answer of: http://stackoverflow.com/q/50876505
downvote count: 0
has body: Solution Pulling arrow &gt;= 0.17.0 should fix your error. Reference PR: https://github.com/apache/arrow/pull/6751

http://stackoverflow.com/comment/88872717
has text: @Behnam, Sorry, I'm not sure what you're looking for. Can you update your question demonstrating how the above solution doesn't work?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50928114
type: Comment

http://stackoverflow.com/q/50986354
type: Question
tagged with: bash
downvote count: 0
accepted answer: http://stackoverflow.com/a/50986737
has answer: http://stackoverflow.com/a/50986459
has comment: http://stackoverflow.com/comment/88967462
has answer: http://stackoverflow.com/a/71834573
tagged with: python
possible better answer: http://stackoverflow.com/a/50986459
has body: I want to execute a python program on a remote server, without creating a script. The remote server does not allow me to create any files anywhere on the file system. The python program has following structure, though the functions are a lot more complicated def test2(): print("test2") def test_func(): test2() print("test_func") test_func() Is there a way to execute this program directly from command line? I have tried these 2 approaches Pass the code using python -c option. Launch python interactive mode, and copy paste the code to run. I get errors in both the cases. However, any code without user defined functions is able to execute with 2nd approach. Is it possible to get the code above working without creating a local script?
answer count: 4
favorite count: 0
score: 8
upvote count: 8
has title: Execute python program from command line without script file
has answer: http://stackoverflow.com/a/50986679
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50986737

http://stackoverflow.com/comment/88877858
type: Comment
comment on: http://stackoverflow.com/q/50939856
has text: (([A-Za-z0-9_])+\.)?key(\.([A-Za-z0-9_])+)?
score: 0
type: QuestionComment

http://stackoverflow.com/comment/88918602
has text: @Shaido Yes That is what I want. I would like to use the same `function` though for all the `3` lists
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50960404

http://stackoverflow.com/q/50893267
has body: id(t+t), id(t*2) (42838592, 42838592) (t+t) is (t*2) False If two variable point to same object 'is' operator will return true.But first line said both have same id but 'is' operator give false value.
has comment: http://stackoverflow.com/comment/88786961
has comment: http://stackoverflow.com/comment/88786973
has comment: http://stackoverflow.com/comment/88786995
has title: How can two Python objects have same id but 'is' operator returns False?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50893268
tagged with: python
has comment: http://stackoverflow.com/comment/91525842
score: 7
favorite count: 0
upvote count: 8
has answer: http://stackoverflow.com/a/50895475
type: Question
tagged with: lifetime
answer count: 2
linked to: http://stackoverflow.com/q/20753364
downvote count: 1
possible better answer: http://stackoverflow.com/a/50895475
tagged with: object
duplicate of: http://stackoverflow.com/q/20753364
duplicate of: http://stackoverflow.com/q/306313
has answer: http://stackoverflow.com/a/50893268

http://stackoverflow.com/comment/88797490
type: AnswerComment
score: 0
type: Comment
has text: if K.image_data_format() == 'channels_first': x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols) x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols) input_shape = (1, img_rows, img_cols) else: x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1) x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1) input_shape = (img_rows, img_cols, 1) x_train = x_train.astype('float32')
comment on: http://stackoverflow.com/a/50872497

http://stackoverflow.com/comment/88859108
has text: What is the problem you're actually trying to solve. In general, you would try to do things like this with objects and not functions. Think of a Box object that gets packed with buttons. in a separate place you would run the tkinter mainloop.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50929677

http://stackoverflow.com/q/50889172
tagged with: memory-address
tagged with: memory
has answer: http://stackoverflow.com/a/50889338
downvote count: 4
possible better answer: http://stackoverflow.com/a/50889338
has comment: http://stackoverflow.com/comment/88779670
has comment: http://stackoverflow.com/comment/88779638
has comment: http://stackoverflow.com/comment/88779669
accepted answer: http://stackoverflow.com/a/50889379
has comment: http://stackoverflow.com/comment/88779613
answer count: 3
has comment: http://stackoverflow.com/comment/88779661
has answer: http://stackoverflow.com/a/50889350
has comment: http://stackoverflow.com/comment/88780008
tagged with: python
favorite count: 0
has title: Python memory aliasing (simple)
score: -3
has body: I wonder how and why this happens. Can someone explain this? Contact is my own class that I made in my editor. What should I do if I want to make them point to the same memory address?
upvote count: 1
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50889379

peewee
tag name: peewee
type: Tag
tags question: http://stackoverflow.com/q/50999447
tags question: http://stackoverflow.com/q/50938499

http://stackoverflow.com/comment/88791434
has text: Thank you very much guys! Once I learnt that this type of operation is called pivot, it became obvious that there are actually many simple ways to this. So I guess my real question was I didn't know the keyword...
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50892796

http://stackoverflow.com/a/52755106
upvote count: 4
score: 3
answers question: http://stackoverflow.com/q/51005891
downvote count: 1
has body: Try this in jupyter cell: !pip install pandas
type: Answer

http://stackoverflow.com/comment/88863763
has text: Edited answer to reassign values to your df which will preserve your ID column. If you don't want to reassign you can always make a `.copy()` of your df.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50931771

http://stackoverflow.com/q/50977130
has answer: http://stackoverflow.com/a/50977205
has body: def generator(dct): for i in range(3): dct['a'] = i yield dct g = generator({'a': None}) next(g) # -&gt; {'a': 0} next(g) # -&gt; {'a': 1} next(g) # -&gt; {'a': 2} g = generator({'a': None}) list(g) # -&gt; [{'a': 2}, {'a': 2}, {'a': 2}] next iterates generator as I expected. However, list iterates unexpectedly. I think it should return [{'a': 0}, {'a': 1}, {'a': 2}] since next iterates without problem. I wonder what makes this difference. (my environment: python 3.6.5, conda 4.5.4, Windows)
upvote count: 1
has comment: http://stackoverflow.com/comment/88950380
has comment: http://stackoverflow.com/comment/88950545
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88950737
has comment: http://stackoverflow.com/comment/88950519
score: 1
has title: Each of next() and list() iterates over generator with mutable object differently
has answer: http://stackoverflow.com/a/50977192
has comment: http://stackoverflow.com/comment/88972013
has answer: http://stackoverflow.com/a/50977226
type: Question
has comment: http://stackoverflow.com/comment/88950408
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/88950392
accepted answer: http://stackoverflow.com/a/50977192
answer count: 3
tagged with: python
possible better answer: http://stackoverflow.com/a/50977205
has comment: http://stackoverflow.com/comment/88950526

http://stackoverflow.com/q/50889916
answer count: 1
downvote count: 1
favorite count: 0
has body: a = 0 dots = [] while True: a = c.find('.', a+1) print(a) dots.append(a) if (a != -1) else break Why does this return an invalid syntax at the break?
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88781125
has comment: http://stackoverflow.com/comment/88781003
has comment: http://stackoverflow.com/comment/88781642
has title: Invalid Syntax at break
type: Question
linked to: http://stackoverflow.com/q/394809
has answer: http://stackoverflow.com/a/50889954
score: 0
upvote count: 1

http://stackoverflow.com/a/50996003
upvote count: 3
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50995969
type: Answer
has body: You keep adding a reference to the same list to permutations. When you call: permutations.append(p) Python doesn't take a copy of the list, it adds a reference. You only have one list. What you want to do is: permutations.append(p[:]) Which will take a copy.
answers question: http://stackoverflow.com/q/50995969
downvote count: 0
score: 3

http://stackoverflow.com/q/50999017
tagged with: regex
type: AnsweredQuestion
has title: String Operation on captured group in re Python
possible better answer: http://stackoverflow.com/a/50999581
type: Question
score: 5
has answer: http://stackoverflow.com/a/50999079
accepted answer: http://stackoverflow.com/a/50999079
upvote count: 6
answer count: 2
has body: I have a string: str1 = "abc = def" I want to convert it to: str2 = "abc = #Abc#" I am trying this: re.sub("(\w+) = (\w+)",r"\1 = %s" % ("#"+str(r"\1").title()+"#"),str1) but it returns: (without the string operation done) "abc = #abc#" What is the possible reason .title() is not working.? How to use string operation on the captured group in python?
downvote count: 1
has answer: http://stackoverflow.com/a/50999581
favorite count: 0
tagged with: python

http://stackoverflow.com/comment/88869911
has text: Cannot reproduce on 2.6.9.
type: QuestionComment
comment on: http://stackoverflow.com/q/50935610
score: 0
type: Comment

http://stackoverflow.com/q/50918382
accepted answer: http://stackoverflow.com/a/50919158
type: Question
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/50919158
has title: How to create new issues without selecting 'project'(manually select project_id)?
has body: I am doing my school project by using Django to create a task management web application. My responsibilities are to create 'issue tracker', something like 'StackOverflow', but I am still at the very early stage of it. So I used crispy form to let the user create their own new issues. Since we use 'project_id' and 'issue_id' as parameters to direct users to different pages, so I encountered this problem, users have to manually choose 'project' when they create a new issue. I do not know how to put the issue which created by the user under right project without having to choose 'project' manually. form.py from django import forms from .models import Comment,Issue class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('body',) class IssueForm(forms.ModelForm): class Meta: model = Issue fields = ('title','content','project','status') class NewIssueForm(forms.ModelForm): class Meta: model = Issue fields = ('title','content','project','status') new_issue.html {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} Add New Issue {% csrf_token %} Submit {% endblock %} models.py class Issue(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) project = models.ForeignKey(Project,on_delete=models.CASCADE) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250) content = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) published = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=9, choices=STATUS_CHOICES, default='draft') def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Issue, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('project:issue_tracker:issue_detail', kwargs={'project_id':self.project_id, 'issue_id':self.id}) def __str__(self): return self.title urls.py urlpatte…
tagged with: django
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/50870611
answers question: http://stackoverflow.com/q/50870437
upvote count: 1
has comment: http://stackoverflow.com/comment/88743219
has body: Stackoverflow is not a place to ask for readily available code. I can, however, point you in a general direction, which should be enough information to get you to some tutorials doing similar (enough) topics. Your problem can certainly be approached in several different ways. As your bag-of-words (which is what your "counting vector" is called) drops any ordering of words, and since your input is effectively the same length, it can be processed with standard techniques like a MLP (Multi Layer Perceptron). A Word2Vec model only makes sense if you have specific one-hot vectors (not indicating the frequency, but what words appear at all). Yet, a simple embedding layer might work just as well; that generally only means that you embed your high-dimensional space (in your case ~20.000), to a lower dimension. There is no general rule of thumb as to how many dimensions will best approximate your problem without being too sparse, but I would say a dimension around 100-150 should work well. In a MLP, you basically only stack non-linear layers one after another. You can follow a basic MNIST example for multiclass classification (note that this is on an older version of TensorFlow, but should still work the same); they even have two different approaches that you can both apply to yours. That should get you on the right path, and you can see whether your problem is getting a somewhat decent solution or remains hard to tackle. Also consider how your classes are distributed; with 300 categories, it still might well be that certain classes are underrepresented, and you run into issues with the training process. Did you do a basic statistical analysis on the distribution yet? Edit: Included comment from below. To add to the MNIST example: Even though you have different data origins, the data can be modeled the same. You have high-dimensional non-binary inputs, and want to get only a few output labels that represent some form of statistical likelihood of being of a certain class.
type: Answer
has comment: http://stackoverflow.com/comment/88743250
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/88742910

http://stackoverflow.com/comment/88794933
type: Comment
comment on: http://stackoverflow.com/a/50897569
has text: x.difference(y). I got it! Thanks. I will edit your answer with all the combinations. So that this post is complete
type: AnswerComment
score: 0

http://stackoverflow.com/a/50900347
answers question: http://stackoverflow.com/q/50900301
has comment: http://stackoverflow.com/comment/88800741
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/88800806
upvote count: 1
type: AcceptedAnswer
has body: Demo: source DF with multi-level columns: In [223]: r Out[223]: year hour windIntensity delay mean mean count 0 1 0 2015 6.0 5 solution: In [224]: r.columns = r.columns.map(lambda c: ('_' if c[1] else '').join(c)) result: In [225]: r Out[225]: year hour windIntensity_mean delay_mean delay_count 0 1 0 2015 6.0 5
accepted answer of: http://stackoverflow.com/q/50900301
type: Answer
has comment: http://stackoverflow.com/comment/88800833

http://stackoverflow.com/comment/100131495
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50865795
score: 0
has text: For me in similar situation helped add of both child and parent to the session

http://stackoverflow.com/q/50890578
type: UnansweredQuestion
score: 1
tagged with: django
has body: I have models like this: class Picture(models.Model): source = models.ImageField(null=True, blank=True) #TODO: check the field type, correct if needed def __str__(self): return "%s" % self.pk class News(models.Model): content = MartorField() title = models.CharField(max_length=512) creation_date = models.DateField(default=timezone.now) publish_date = models.DateField(null=True, blank=True) picture_id = models.ForeignKey('Picture', null=True, blank=True, on_delete=models.CASCADE) class Meta: verbose_name_plural = "News" def __str__(self): return "%s" % self.title And I'm using CreateView and UpdateView. When I use {{ form.as_p }} I have a problem, because picker of image is showing only id - not image. I'm looking for some widget or workaround to fix this problem.
type: Question
has title: Django - form with foreign key to model with gallery
upvote count: 1
favorite count: 0
tagged with: python
answer count: 0
downvote count: 0

http://stackoverflow.com/comment/88836116
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50916452
has text: Probbly the closest possible thing today. Thanks
score: 1

http://stackoverflow.com/a/50886122
score: 2
has body: In this case , you wont have any issues. But is it advisable to use .loc functionality. You can read the difference in detailed here
downvote count: 0
answers question: http://stackoverflow.com/q/50886068
type: Answer
upvote count: 2

http://stackoverflow.com/a/50871541
has comment: http://stackoverflow.com/comment/88744879
type: Answer
has body: This may be out of the box thinking, but if you don't care for semantic/grammatic connection of the words: sort all words from the text by length sort your array by length . Write a for-loop: Call len() (length) on each word from the text. Then only check against those words which have the same length. With some tinkering it might give you a good performance boost instead of the "naive" search. Also look into search algorithms if you want to achieve an additional boost (concerning finding the first word (of the 400) with e.g. 6 letters - then go "down" the list until the first word with 5 letters comes up, then stop. Alternatively you could also build an index array with the indexes of the first and last of all 5-letter words (analog for the rest), assuming your words dont change.
answers question: http://stackoverflow.com/q/50871201
score: 0

http://stackoverflow.com/a/50973978
has comment: http://stackoverflow.com/comment/88946900
answers question: http://stackoverflow.com/q/50973830
score: 0
has comment: http://stackoverflow.com/comment/88946502
has comment: http://stackoverflow.com/comment/88946704
has comment: http://stackoverflow.com/comment/88946739
has body: Probably the fastest and more readable solution is with list comprehension: dictColor = {"o": 4, "b": 2, "g": 7, "r": 5} color = input("Enter 4 characters of colors: ") print(sum((dictColor[c] for c in color)))
type: Answer
has comment: http://stackoverflow.com/comment/88944163

http://stackoverflow.com/comment/88896199
comment on: http://stackoverflow.com/a/50949335
score: 0
type: AnswerComment
has text: Let me reduce it to few lines of code .Will be back in 1 hour.
type: Comment

http://stackoverflow.com/comment/91959533
comment on: http://stackoverflow.com/a/50893928
score: 6
type: AnswerComment
has text: Well, it's not a bug. The problem is that pytorch is distributed as `torch` on `pypi`, and `pytorch` on `conda`, and it's installed as `torch` on the filesystem. So the `skeleton` program couldn't have possibly known about it. I have just went through the same process of not being able to figure out why conda wasn't finding `torch`, until I realized the mismatch between the two distribution names. What a mess. But I'm glad you too have figured it out!
type: Comment

http://stackoverflow.com/comment/88947201
type: Comment
type: QuestionComment
has text: Just to satisfy my curiosity, could you try `y_train = train.iloc[:, -1:]` (adding the colon to the end) so that your Y values are shape (n, 1) rather than just (n,). I don't think that's causing the issue, but I know I've seen sklearn warnings about that before
score: 0
comment on: http://stackoverflow.com/q/50975447

http://stackoverflow.com/a/50994396
has body: This worked in removing the app_list and "for loop" apps = App.objects.filter(menu__name=F('menu')) @bruno desthuilliers, I am still trying to understand prefetch
type: Answer
answers question: http://stackoverflow.com/q/50981884
score: 0

http://stackoverflow.com/comment/88862665
type: Comment
comment on: http://stackoverflow.com/q/50931818
type: QuestionComment
has text: @chepner The OP didn't mean `orange.*` is a regular expression. They meant that they have strings that look like `orange.<something>`, and they wanted to create a regular expression to match that only when `<something>` was a single word.
score: 0

http://stackoverflow.com/a/51192642
accepted answer of: http://stackoverflow.com/q/50878549
type: AcceptedAnswer
type: Answer
has body: For my question, i solved the problem with the following regex, using the following tool indicate for one the users here (https://regex101.com/r/2qxa0y/1/) ((|.|[(]|\s)*)\((\d*)\) Thanks to everyone!!
answers question: http://stackoverflow.com/q/50878549
score: 0

http://stackoverflow.com/q/50865599
type: Question
accepted answer: http://stackoverflow.com/a/50866626
score: 0
has answer: http://stackoverflow.com/a/50866626
answer count: 1
has body: I am trying to create a relationship between an Events table and a Contacts table where an event can have multiple contacts and one can be marked primary. I thought I had it, but I can't seem to figure out how to change the primary field that I have in the association object. Here is the database structure: import sqlalchemy as sa from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.ext.associationproxy import association_proxy from sqlalchemy import orm import uuid Base = declarative_base() Session = orm.sessionmaker() Engine = sa.create_engine('sqlite:///arandomdb', echo=True) Session.configure(bind=Engine) session = Session() class TblEvents(Base): __tablename__ = 'tbl_events' guid = sa.Column(sa.String(36), primary_key=True, nullable=False) name = sa.Column(sa.String) contacts = orm.relationship('TblContacts', secondary='tbl_events_contacts', backref='events') class TblContacts(Base): __tablename__ = 'tbl_contacts' guid = sa.Column(sa.String(36), primary_key=True, nullable=False) name = sa.Column(sa.String) class TblEventsContacts(Base): __tablename__ = 'tbl_events_contacts' event_id = sa.Column(sa.String, sa.ForeignKey(TblEvents.guid), primary_key=True) contact_id = sa.Column(sa.String, sa.ForeignKey(TblContacts.guid), primary_key=True) primary = sa.Column(sa.Boolean) event = orm.relationship('TblEvents', backref=orm.backref('tbl_events_contacts', passive_deletes='all' )) contact = orm.relationship('TblContacts', backref=orm.backref('tbl_events_contacts', passive_deletes='all')) if __name__ == '__main__': Base.metadata.create_all(Engine) ev1 = TblEvents(guid=str(uuid.uuid4()), name='event 1') con1 = TblContacts(guid=str(uuid.uuid4()), name='contact 1') session.add(ev1, con1) session.commit() ev1.contacts.append(con1) session.commit() ev1.contacts[0].primary = True session.commit() It doesn't complain about trying to set ev1.contacts[0].primary = True but it also doesn't seem to do anything. What is the proper way of going about this data stru…
tagged with: python
type: AnsweredQuestion
has title: SqlAlchemy Changing value of field in association object from the parent
tagged with: sqlalchemy

http://stackoverflow.com/comment/88733603
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50865440
has text: By the way is this about list or array? It would be useful to have your input and desired output.
score: 0

http://stackoverflow.com/comment/136555653
type: AnswerComment
has text: Thank you. Sorry I'm not a C programmer but have to extend my colleague's codes. I figured the way to avoid this is to use `malloc`
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50997241

http://stackoverflow.com/a/50984990
answers question: http://stackoverflow.com/q/50982008
has body: To eliminate the spaces, try: s['Product'] = s['Product'].str.replace('\s+','') Once you do that, s[s['Product'] == 'A'] should give you something. Alternatively, if you want to keep the spaces in the original dataframe, you can have another column: s['Product_nospace'] = s['Product'].str.replace('\s+','') and do all filtering from there. Once you're done, you can drop the column: s.drop(columns=['Product_nospace'], inplace=True)
accepted answer of: http://stackoverflow.com/q/50982008
score: 0
has comment: http://stackoverflow.com/comment/88965039
has comment: http://stackoverflow.com/comment/88965401
has comment: http://stackoverflow.com/comment/88965066
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/q/50902416
upvote count: 2
type: UnansweredQuestion
tagged with: python
has body: I want to sum multiple columns of dataframe to a new column. For 2 columns I was using this. import pandas as pd, numpy as np df=pd.read_csv("Calculation_test.csv") #creating new colums df["Test1"] = 0 #sum of 2 columns df["Test1"]= df['col1']+df['col2'] df.to_csv('test_cal.csv', index=False) But, for my project, I need to do sums of around 15-20 columns. Every time I do not want to write df['col1']+df['col2']+...................... I have the list of columns, which I have to add. Like: 'col1'+'col2'+ 'col5'+'col8'+----+'col18' or like this: 'col1', 'col2', 'col5', 'col8',----,'col18' How can I use this list directly to do the sum of columns?
tagged with: sum
linked to: http://stackoverflow.com/q/25748683
tagged with: dataframe
type: Question
duplicate of: http://stackoverflow.com/q/25748683
score: 2
has answer: http://stackoverflow.com/a/50902515
answer count: 1
downvote count: 0
favorite count: 0
tagged with: pandas
has title: Panda: Summing multiple columns in dataframe to a new column

http://stackoverflow.com/comment/88960784
type: Comment
has text: What version of pip are you using?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50982701

http://stackoverflow.com/q/50906372
type: UnansweredQuestion
tagged with: word2vec
type: Question
has answer: http://stackoverflow.com/a/50906648
has body: I am working on text classification task where my dataset contains a lot of abbreviations and proper nouns. For instance: Milka choc. bar. My idea is to use bidirectional LSTM model with word2vec embedding. And here is my problem how to code words, that not appears in the dictionary? I partially solved this problem by merging pre-trained vectors with randomly initialized. Here is my implementation: import gensim from gensim.models import Word2Vec from gensim.utils import simple_preprocess from gensim.models.keyedvectors import KeyedVectors word_vectors = KeyedVectors.load_word2vec_format('ru.vec', binary=False, unicode_errors='ignore') EMBEDDING_DIM=300 vocabulary_size=min(len(word_index)+1,num_words) embedding_matrix = np.zeros((vocabulary_size, EMBEDDING_DIM)) for word, i in word_index.items(): if i&gt;=num_words: continue try: embedding_vector = word_vectors[word] embedding_matrix[i] = embedding_vector except KeyError: embedding_matrix[i]=np.random.normal(0,np.sqrt(0.25),EMBEDDING_DIM) def LSTMModel(X,words_nb, embed_dim, num_classes): _input = Input(shape=(X.shape[1],)) X = embedding_layer = Embedding(words_nb, embed_dim, weights=[embedding_matrix], trainable=True)(_input) X = The_rest_of__the_LSTM_model()(X) Do you think, that allowing the model to adjust the embedding weights is a good idea? Could you please tell me, how can I encode words like choc? Obviously, this abbreviation stands for chocolate.
answer count: 2
tagged with: keras
score: 0
has title: word2Vec and abbreviations
tagged with: python
tagged with: nlp
has answer: http://stackoverflow.com/a/50906634

http://stackoverflow.com/comment/88949461
has text: Note: You should never call methods whose names start with `__`. Instead of `my_iter.__next___()`, call `next(my_iter)`.
score: 4
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50976550

http://stackoverflow.com/q/50934201
has answer: http://stackoverflow.com/a/50934862
has comment: http://stackoverflow.com/comment/88867149
has comment: http://stackoverflow.com/comment/88867112
tagged with: python-3.x
tagged with: tkinter
has comment: http://stackoverflow.com/comment/88867477
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88867430
type: Question
has comment: http://stackoverflow.com/comment/88867332
has comment: http://stackoverflow.com/comment/88866979
tagged with: canvas
answer count: 1
score: 0
has body: I am making a chess game with an ai in tkinter. While the ai evaluates the position, I want a Canvas to be updated with the current percentage of the maximum time that the ai is allowed to take elapsed. Is there a way to do this? Edit: Here is a basic example of what my code looks like: def find_move(): piece, old_x, old_y, new_x, new_y = self.ai.make_move(args) This calls a separate ai class which finds the best move. How can I get a canvas to be updated with the current percentage of a variable self?maximum_time_for_ai that has been elapsed. This should run until the maximum time has elapsed or the ai has finished evaluating.
has title: Is there a way in tkinter to update a canvas every second until a certain time has elapsed whilst running other functions?
has comment: http://stackoverflow.com/comment/88867386
tagged with: python

http://stackoverflow.com/a/50951263
accepted answer of: http://stackoverflow.com/q/50951076
downvote count: 2
answers question: http://stackoverflow.com/q/50951076
score: 40
has body: The bytecode shows that two comparisons are being performed here with the middle being duplicated: &gt;&gt;&gt; import dis &gt;&gt;&gt; def a(): ... return None is None is None ... &gt;&gt;&gt; dis.dis(a) 2 0 LOAD_CONST 0 (None) 3 LOAD_CONST 0 (None) 6 DUP_TOP 7 ROT_THREE 8 COMPARE_OP 8 (is) 11 JUMP_IF_FALSE_OR_POP 21 14 LOAD_CONST 0 (None) 17 COMPARE_OP 8 (is) 20 RETURN_VALUE &gt;&gt; 21 ROT_TWO 22 POP_TOP 23 RETURN_VALUE As stated in the docs for comparisons this is because these operators chain together. a op b op c will be translated to a op b and b op c (note b is duplicated in the bytecode as shown above)
upvote count: 42
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/88957065
has text: We can't really respond to your question since we don't know the layout of the site nor the site to check it out.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50979121

http://stackoverflow.com/q/50956836
has comment: http://stackoverflow.com/comment/88912754
has body: Why does df = pd.DataFrame({1 : np.random.randn(5), 2 : np.random.randn(5), 3 : np.random.randn(5)}, index=[1, 1, 2, 2, 2]) a = np.array([3.1, 3.14, 3.1415]) df.loc[2, 2] = a Work but df = pd.DataFrame({1 : np.random.randn(5), 2 : np.random.randn(5), 3 : np.random.randn(5)}, index=[1, 2, 1, 2, 2]) a = np.array([3.1, 3.14, 3.1415]) df.loc[2, 2] = a not? As you can tell, the only difference is the index.
has title: DataFrame Slice Assignment inconsistency
score: 0
has comment: http://stackoverflow.com/comment/88911120
tagged with: pandas
tagged with: python
answer count: 0
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/88911914

google-api
tags question: http://stackoverflow.com/q/50932363
tags question: http://stackoverflow.com/q/51005416
tags question: http://stackoverflow.com/q/50931858
tags question: http://stackoverflow.com/q/50966253
tags question: http://stackoverflow.com/q/50913206
tags question: http://stackoverflow.com/q/50987584
tags question: http://stackoverflow.com/q/50976129
tags question: http://stackoverflow.com/q/50871702
tags question: http://stackoverflow.com/q/50960753
tags question: http://stackoverflow.com/q/50948314
tag name: google-api
tags question: http://stackoverflow.com/q/50874265
tags question: http://stackoverflow.com/q/50865584
type: Tag
tags question: http://stackoverflow.com/q/50959061

http://stackoverflow.com/q/50989035
answer count: 1
downvote count: 0
tagged with: discord
favorite count: 0
upvote count: 1
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50989562
score: 1
type: Question
has body: I have a bunch of commands in my discord bot and what I am trying to do is to make the bot listen to some commands ONLY if they come from a specific channel. Here is an example of a command: @bot.command(name='bitcoin', brief="Shows bitcoin price for nerds.") async def bitcoin(pass_context=True): url = 'https://api.coindesk.com/v1/bpi/currentprice/BTC.json' response = requests.get(url) value = response.json()['bpi']['USD']['rate'] await bot.send_message(discord.Object(id='&lt;channel id is inserted here&gt;'), "Bitcoin price is: " + value) # await bot.say("Bitcoin price is: " + value) I can give the answer in a specific channel that I want, but I want the bot to only reply if the command is triggered in a specific channel, not everywhere. I tried a if/else with if message.channel.id = 'id' but it doesn't work.
tagged with: discord.py
accepted answer: http://stackoverflow.com/a/50989562
has title: Discord bot listen to commands on specific channel

http://stackoverflow.com/comment/88887484
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/50944469
has text: Global variables are a widely used construct. In your case one is used without convincing need. I find the expectation somewhat debatable, that this should be detected by the Python interpreter (or any other dynamic language). For that kind of strictness other languages are better suited.
type: Comment

http://stackoverflow.com/comment/88953438
type: Comment
type: QuestionComment
has text: Is there a BOM in the (included) file?
comment on: http://stackoverflow.com/q/50978342
score: 0

http://stackoverflow.com/q/50890381
score: 0
has comment: http://stackoverflow.com/comment/88787248
linked to: http://stackoverflow.com/q/23294658
has comment: http://stackoverflow.com/comment/88781954
has comment: http://stackoverflow.com/comment/88782076
favorite count: 0
tagged with: python-3.x
has body: I am currently writing a ferry ticket reservation program that has a function to view the seatings (I'm using a list). The code below is going to be a function in my program. When running the code, when I input 1 it prints my list but if I input any other value it asks for another input. For example if I input 2, the program asks for another input and if I input the same value (2) it will print what I want. But if I input a different value such as 3 when it asks the second time, it will ask for a third input. If my third input is the same as my second input, it will print what I want BUT if I input a different value, it will start to print and reach an error. I have all 3 ferry seatings in one list so I wrote ferry1, ferry2, etc. just for testing purposes. Bellow is my whole code. Sorry for the poor formatting of this post as it is my first complex program as well as my first time using a forum. Why is this happening and how can I solve this problem? Thanks in advance! seatings = [ ["ferry1", "B2", "B3", "B4", "B5"], ["B6", "B7", "B8", "B9", "B10"], ["E1", "E2", "E3", "E4", "E5"], ["E6", "E7", "E8", "E9", "E10"], ["E11", "E12", "E13", "E14", "E15"], ["E16", "E17", "E18", "E19", "E20"], ["E21", "E22", "E23", "E24", "E25"], ["E26", "E27", "E28", "E29", "E30"], ["E31", "E32", "E33", "E34", "E35"], ["E36", "E37", "E38", "E39", "E40"], ["ferry2", "B2", "B3", "B4", "B5"], ["B6", "B7", "B8", "B9", "B10"], ["E1", "E2", "E3", "E4", "E5"], ["E6", "E7", "E8", "E9", "E10"], ["E11", "E12", "E13", "E14", "E15"], ["E16", "E17", "E18", "E19", "E20"], ["E21", "E22", "E23", "E24", "E25"], ["E26", "E27", "E28", "E29", "E30"], ["E31", "E32", "E33", "E34", "E35"], ["E36", "E37", "E38", "E39", "E40"], ["ferry3", "B2", "B3", "B4", "B5"], ["B6", "B7", "B8", "B9", "B10"], ["E1", "E2", "E3", "E4", "E5"], ["E6", "E7", "E8", "E9", "E10"], ["E11", "E12", "E13", "E14", "E15"], ["E16", "E17", "E18", "E19", "E20"], ["E21", "E22", "E23", "E24", "E25"], ["E26", "E27", "E28", "E29", "E30"], ["E31", "…
type: UnansweredQuestion
tagged with: python
downvote count: 1
answer count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/88781804
type: Question
has title: Input command in function is getting called again after inputing some but not all value
has comment: http://stackoverflow.com/comment/88782263

http://stackoverflow.com/a/77297326
score: -1
answers question: http://stackoverflow.com/q/50855199
downvote count: 1
type: Answer
upvote count: 0
has body: Or, you could use web scraping. Here's a quick overview of web scraping vs. a POST/GET request: Web Scraping: Gets the HTML that's sent to the client from the page POST/GET: Asks the page for some content following a protocol and with headers/parameters: this is what's used with APIs, but we don't know if ColorHunt provides them Here's a good introduction to Python web scraping: https://realpython.com/python-web-scraping-practical-introduction/

http://stackoverflow.com/a/50966490
upvote count: 2
has body: UPDATE: In [136]: df.applymap(lambda x: x if isinstance(x, list) else []) Out[136]: A B E F 0 [1, 2, 3, 4] [1, 2, 3, 4] [] [2, 2] 1 [4, 5, 6, 7, 8] [4, 5, 6, 7, 8] [] [4, 4] 2 [7, 6, 4] [3, 7, 9] [] [] 3 [] [] [] [78, 90] 4 [1, 2] [4, 5] [] [] or: In [152]: df = df.applymap(lambda x: x if isinstance(x, list) else [np.nan]) In [153]: df Out[153]: A B E F 0 [1, 2, 3, 4] [1, 2, 3, 4] [nan] [2, 2] 1 [4, 5, 6, 7, 8] [4, 5, 6, 7, 8] [nan] [4, 4] 2 [7, 6, 4] [3, 7, 9] [nan] [nan] 3 [nan] [nan] [nan] [78, 90] 4 [1, 2] [4, 5] [nan] [nan] NOTE: please pay attention at @jpp's comment - storing non-scalar values in cells destroys 90% of Pandas/Numpy magic, as most of fast internal vectorized methods expect scalar values in cells - they will not work or won't work as expected. Answer for the data set before the question has been updated: you can do it: In [120]: df = df.fillna('') In [121]: df Out[121]: A B C D E F 0 zero one 0.226100 1.764036 2 1 one one -1.672476 -0.867188 2 2 two 0.671258 0.125589 4 3 three three 1.135731 0.080577 4 4 four two -1.711692 0.735028 67 5 two 0.608488 1.012977 6 six one -1.233979 -0.623781 78 7 seven three 0.256893 -0.546639 90 but all columns containing at least one NaN value will be converted to strings, because an empty string '' will always have a string (object) dtype: In [122]: df.dtypes Out[122]: A object B object C float64 D float64 E object F object dtype: object
has comment: http://stackoverflow.com/comment/88929333
has comment: http://stackoverflow.com/comment/88931095
has comment: http://stackoverflow.com/comment/88929352
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88929411
has comment: http://stackoverflow.com/comment/88929994
has comment: http://stackoverflow.com/comment/88931148
has comment: http://stackoverflow.com/comment/88930966
type: Answer
accepted answer of: http://stackoverflow.com/q/50966435
has comment: http://stackoverflow.com/comment/88930434
score: 2
answers question: http://stackoverflow.com/q/50966435
has comment: http://stackoverflow.com/comment/88929848

http://stackoverflow.com/a/50960287
answers question: http://stackoverflow.com/q/50960258
has comment: http://stackoverflow.com/comment/88917719
score: 1
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88917450
has body: As always, when dealing with reserved keywords wrap it in backticks like you did for sys_location: INSERT INTO `sys_location` (`rank`) VALUES (13000) You can escape everything if you want, but it's often not necessary. Keywords are a case where it might be necessary because these keywords do change, if infrequently.
type: Answer
has comment: http://stackoverflow.com/comment/88917493
accepted answer of: http://stackoverflow.com/q/50960258
downvote count: 0

http://stackoverflow.com/comment/88832978
type: Comment
comment on: http://stackoverflow.com/q/50916382
score: 0
has text: @kindall beat me to it. Read about variable scope: it's a very common problem that tricks up new programmers all the time. There are many tutorials on this, and the following question might help if you want a lot of detail: https://stackoverflow.com/questions/291978/short-description-of-the-scoping-rules
type: QuestionComment

http://stackoverflow.com/comment/88983007
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50994051
type: QuestionComment
has text: Can parentheses be nested?

http://stackoverflow.com/q/50907206
accepted answer: http://stackoverflow.com/a/50912141
has comment: http://stackoverflow.com/comment/88814844
has comment: http://stackoverflow.com/comment/88815541
has comment: http://stackoverflow.com/comment/88814650
type: Question
answer count: 2
tagged with: automation
downvote count: 0
has comment: http://stackoverflow.com/comment/88814403
possible better answer: http://stackoverflow.com/a/50907645
has comment: http://stackoverflow.com/comment/88814787
has comment: http://stackoverflow.com/comment/88814530
has answer: http://stackoverflow.com/a/50907645
has comment: http://stackoverflow.com/comment/88815414
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/88815344
has answer: http://stackoverflow.com/a/50912141
has comment: http://stackoverflow.com/comment/88814715
has comment: http://stackoverflow.com/comment/88815477
favorite count: 0
has body: I want to assign the value of the variable game_type to excel cell but i am unable to do so: import openpyxl wb = openpyxl.load_workbook('Table1.xlsx') Card13 = wb.active print Card13 class private_table(): def __init__(self, game): if game == 13: game_type = game Card13['A2'] = game_type wb.save('Table1.xlsx') print(game_type) elif game == '21': game_type = int(game) print(game_type) elif game == '27': game_type = int(game) print(game_type) else: print("Enter correct game type") def noc(self, cards): if cards == 13: game_type = Card13['A2'].value if game_type == '13': num_of_cards = cards print num_of_cards return num_of_cards else: print ("Please select the correct number of cards") return("Please select the correct number of cards") elif cards == '21': game_type = Card13['B1'].value if game_type == '21': num_of_cards = cards print num_of_cards return num_of_cards else: print ("Please select the correct number of cards") return("Please select the correct number of cards") elif cards == '27': game_type = Card13['B1'].value if game_type == '27': num_of_cards = cards print num_of_cards return num_of_cards else: print ("Please select the correct number of cards") return("Please select the correct number of cards")
has title: How to Assign Value From a Variable to an Excel Cell with Python
upvote count: 2
tagged with: python
linked to: http://stackoverflow.com/q/31395058
tagged with: excel
tagged with: worksheet
has comment: http://stackoverflow.com/comment/88815236
score: 2
type: AnsweredQuestion

http://stackoverflow.com/comment/88881293
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/50941482
type: Comment
has text: No, you shouldn't use `regex` for parsing html. Use `bs4` as explained by @wp78de.

http://stackoverflow.com/comment/88913113
comment on: http://stackoverflow.com/a/50935756
score: 0
type: AnswerComment
has text: Examples helped. Option 2 is effectively what I was looking for. (My class is indeed immutable). Though I had dismissed it earlier, I now see the merits of Option 1 as well. Thanks.
type: Comment

http://stackoverflow.com/q/51010644
tagged with: pdftotext
downvote count: 3
has comment: http://stackoverflow.com/comment/89029351
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89017961
has answer: http://stackoverflow.com/a/51013499
has comment: http://stackoverflow.com/comment/89018230
has comment: http://stackoverflow.com/comment/89014736
accepted answer: http://stackoverflow.com/a/51013499
has comment: http://stackoverflow.com/comment/89018033
tagged with: python
has comment: http://stackoverflow.com/comment/89014975
has comment: http://stackoverflow.com/comment/89014645
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89014659
tagged with: pypdf
tagged with: java
has title: Is it possible to extract text from PDF, whose "Page Extraction" is not allowed?
tagged with: itext
has comment: http://stackoverflow.com/comment/89014409
has body: I am able to extract text from PDF's which doesn't have any security restrictions. I just want to know if it is possible to extract text from PDF which has restrictions UPDATE: Thanks to all for your comments. I appreciate your concern. Please understand the question. I did not ask how to do it. I just want to know if it is possible. I have created a PDF with these restrictions. I do not want my information to be extracted from my document. There are many developers who can achieve any task. I want to know if this task can be done. If this can be done, then I will investigate further to overcome this issue.
has comment: http://stackoverflow.com/comment/89018154
type: Question
has comment: http://stackoverflow.com/comment/89017904
has comment: http://stackoverflow.com/comment/89017971
upvote count: 3
score: 0

http://stackoverflow.com/q/50881264
has answer: http://stackoverflow.com/a/78425310
answer count: 2
linked to: http://stackoverflow.com/q/72747398
tagged with: counting
favorite count: 0
upvote count: 3
has answer: http://stackoverflow.com/a/50881301
tagged with: pandas
tagged with: python
has body: What is the easiest way to create an output table that summarizes the count and percentages together? So far I'm only able to write separate queries to pull either total count and percentage, but not able to show both results at the same time. import pandas as pd d = { 'color': ['RED', 'WHITE', 'RED', 'BLUE', 'BLUE'], 'count': ['1', '1', '3', '2', '3']} df = pd.DataFrame(d) df.color.value_counts() df.color.value_counts() / len(df)
downvote count: 0
type: UnansweredQuestion
has title: How to show aggregate counts and percentage together in one table
type: Question
score: 3
tagged with: dataframe

http://stackoverflow.com/q/50899076
score: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/50899165
upvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/17622419
tagged with: namedtuple
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/17622419
has title: Create named tuple from subset of dict keys
type: Question
has body: What is the most pythonic way to make the following test pass: def test_named_tuple_from_map(): from collections import namedtuple NT = namedtuple('nt', ['a', 'b', 'c']) source = {'a': 1, 'b': 2, 'd': 4, 'c': 3} new = NT(**source) assert new == NT(a=1,b=2,c=3) The reason I want this is so that I can pick out subsets of dict data and pass on as immutable data.
has answer: http://stackoverflow.com/a/50899165
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/89012993
score: 2
has text: Table name cannot be parametrized. You need to use string concatenation or interpolation (both potentially dangerous - SQL Injection).
comment on: http://stackoverflow.com/q/51010048
type: Comment
type: QuestionComment

combinatorics
tags question: http://stackoverflow.com/q/50976550
tags question: http://stackoverflow.com/q/50929904
type: Tag
tags question: http://stackoverflow.com/q/50955583
tag name: combinatorics

http://stackoverflow.com/comment/88799749
comment on: http://stackoverflow.com/q/50899417
score: 0
type: Comment
type: QuestionComment
has text: @Mihai Chelaru I can't, I'm doing stuff afterwards

http://stackoverflow.com/comment/88835995
type: QuestionComment
has text: Sorry. When I say it doesn't work I mean to say that nothing happens. The program doesn't run for a sufficiently large value of "composite."
score: 0
comment on: http://stackoverflow.com/q/50917912
type: Comment

http://stackoverflow.com/a/50983880
has comment: http://stackoverflow.com/comment/88962971
score: 1
has body: You need to upgrade rest_framework_docs as well.
has comment: http://stackoverflow.com/comment/88963371
upvote count: 1
answers question: http://stackoverflow.com/q/50983848
type: Answer
downvote count: 0

http://stackoverflow.com/a/50992786
accepted answer of: http://stackoverflow.com/q/50987069
answers question: http://stackoverflow.com/q/50987069
upvote count: 4
type: AcceptedAnswer
downvote count: 0
score: 4
has body: When you create an account on your node (which w3.personal.newAccount() does), the node hosts the private key; direct access to it is not intended. If you must have local access to the private key, you can either: Generate a new one with w3.eth.account.create(extra_entropy) Extract the existing key from your node's keyfile. If the node is geth, extracting the key looks like: with open('~/.ethereum/keystore/UTC--...4909639D2D17A3F753ce7d93fa0b9aB12E') as keyfile: encrypted_key = keyfile.read() private_key = w3.eth.account.decrypt(encrypted_key, 'correcthorsebatterystaple') Security tip -- Do not save the key or password anywhere, especially into a shared source file
has comment: http://stackoverflow.com/comment/89024186
type: Answer
has comment: http://stackoverflow.com/comment/89051295

http://stackoverflow.com/q/50998798
answer count: 2
upvote count: 1
favorite count: 0
has title: I have my pseudocode but I can't write one of the loop in python
linked to: http://stackoverflow.com/q/23294658
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88991664
tagged with: python
has answer: http://stackoverflow.com/a/50998833
downvote count: 0
has body: Hi I am bit new to python coding and I have prepared a pseudo code but I can't write my python code properly. This are my pseudo code: Input(Item) Item = Item.split() numberOfItem = count(Item) until numberOfItem == 2: output("Please select two Item") input(Item) itemCostDic = {"wood":200, "paper":100, "pen":10, "eraser":5} specificItemCost = {} for value in Item: specificItemCost[value] = itemCostDic[value] totalItemCost = sum(specificItemCost.value) print(totalItemCost) I am not sure how to loop the "until" in my python codes.
score: 1
type: Question
has comment: http://stackoverflow.com/comment/88991619
has comment: http://stackoverflow.com/comment/88991620
has answer: http://stackoverflow.com/a/50998992

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

http://stackoverflow.com/q/50933454
has comment: http://stackoverflow.com/comment/88865577
has comment: http://stackoverflow.com/comment/88865668
has answer: http://stackoverflow.com/a/50933622
has comment: http://stackoverflow.com/comment/88865483
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/88865540
has comment: http://stackoverflow.com/comment/88865489
has comment: http://stackoverflow.com/comment/88865726
has comment: http://stackoverflow.com/comment/88870085
type: Question
tagged with: python-3.5
has comment: http://stackoverflow.com/comment/88865648
has comment: http://stackoverflow.com/comment/88865753
has comment: http://stackoverflow.com/comment/88870182
has comment: http://stackoverflow.com/comment/88865504
has title: Get IP address from last line of log file using Regex
has comment: http://stackoverflow.com/comment/88865575
has body: I am trying to use Python Regex to get the IP address from the last line of a log. I can get an IP if I search through the entire log. For example: with open("read.log", "r+") as log: for line in log: address = "^\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}$" match = re.match(address, line) But when I try to just read the last line and get an IP address, I do not get any results. How do I fix this? import re def run(): try: logfile = open('read.log', 'r') # print ('First line in log: ',logfile.readline()) for line in logfile: x = line for ip in x: address = "^\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}$" match = re.match(address, ip) logfile.close print ('Last Line: ', match) except OSError as e: print (e) run() My read.log looks like this... 10.1.177.198 Tue Jun 19 09:25:16 CDT 2018 10.1.160.198 Tue Jun 19 09:25:38 CDT 2018 10.1.177.198 Tue Jun 19 09:25:36 CDT 2018 10.1.177.198 Tue Jun 19 09:26:38 CDT 2018 10.1.177.198 Tue Jun 19 09:27:16 CDT 2018 10.1.177.198 Tue Jun 19 09:28:38 CDT 2018
upvote count: 1
has comment: http://stackoverflow.com/comment/88866215
answer count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/37227909
type: UnansweredQuestion
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/88865531

http://stackoverflow.com/comment/88884303
type: Comment
has text: Like i say, still getting adjusted to programming
comment on: http://stackoverflow.com/a/50934377
score: 0
type: AnswerComment

http://stackoverflow.com/q/50898218
type: Question
upvote count: 1
favorite count: 0
tagged with: pandas
answer count: 1
has body: I'm working on a data set where I unstack the data, and get the first and last rows. &gt;&gt;&gt; print df.iloc[[(0), (-1)]] Distance Node 0 1 2 Time 0 27.0 54.0 97.0 60 22.0 49.0 92.0 then I use df1 = (df.loc[0] - df.iloc[(-1)]).unstack() to get the difference of the two rows Node 0 1 2 Distance 5.0 5.0 5.0 And finally, I want to concatenate/combine the two data sets (df and df1). &gt;&gt;&gt; print pd.concat([df, df1], axis=1) (Distance, 0) (Distance, 1) (Distance, 2) 0 27.0 54.0 NaN 60 22.0 49.0 92.0 Distance NaN NaN NaN but I'm getting NaN. Does anyone know what I'm doing wrong? I want my output to look like this Distance Node 0 1 2 Time 0 27.0 54.0 97.0 60 22.0 49.0 92.0 Difference 5.0 5.0 5.0
tagged with: python
type: AnsweredQuestion
has title: Pandas - combine two unstacked data frames
downvote count: 0
has answer: http://stackoverflow.com/a/50900269
accepted answer: http://stackoverflow.com/a/50900269
score: 1
tagged with: dataframe

http://stackoverflow.com/q/51007775
accepted answer: http://stackoverflow.com/a/51007831
tagged with: python
tagged with: regex
upvote count: 3
answer count: 3
possible better answer: http://stackoverflow.com/a/51007842
downvote count: 1
has answer: http://stackoverflow.com/a/51007842
has answer: http://stackoverflow.com/a/51007855
has answer: http://stackoverflow.com/a/51007831
linked to: http://stackoverflow.com/q/31915018
tagged with: search
tagged with: python-2.7
has title: Strange regex issue using findall() and search()
duplicate of: http://stackoverflow.com/q/31915018
type: AnsweredQuestion
score: 2
tagged with: findall
has body: I'm trying to use \w{2}\d/\d{1,2}(/\d{1,2})? in order to match the following two interfaces on a Cisco switch: Gi1/0/1 Fa0/1 When I use re.search(), it returns the desired output. import re port = "Gi1/0/1 Fa0/1" search = re.search(r'\w{2}\d/\d{1,2}(/\d{1,2})?', port) print search.group() I get "Gi1/0/1" as the output. When I use re.findall() import re port = "Gi1/0/1 Fa0/1" search = re.findall(r'\w{2}\d/\d{1,2}(/\d{1,2})?', port) print search I get "['/1', '']" which is undesired. Why does't findall() return ['Gi1/0/1','Fa0/1']? Is that because I used (/\d{1,2})?, and findall() is supposed to return this part? Why is that? How do we get ['Gi1/0/1','Fa0/1'] using findall()?
favorite count: 0
type: Question

http://stackoverflow.com/a/50882310
has comment: http://stackoverflow.com/comment/88766997
has body: A dataframe should be thought of in columns. Each column must have a single data type. When you transpose, you are changing which cells are now associated with each other in the new columns. Prior to transpose, you had an string column and a timedelta column. After transpose, each column had a string and a timedelta. Pandas has to decide how to cast the new columns. It decided to go with timedelta. It is my opinion that this is a goofy choice. You can change this behavior by changing the dtype on a newly constructed dataframe. pd.DataFrame(df.values.T, df.columns, df.index, dtype=object) 0 1 2 id 00115 01222 32333 val 365 days 05:49:12 426 days 02:47:24 5174 days 06:27:00
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50882090
score: 6
has comment: http://stackoverflow.com/comment/88767054
type: Answer
has comment: http://stackoverflow.com/comment/88767100
upvote count: 6
answers question: http://stackoverflow.com/q/50882090
has comment: http://stackoverflow.com/comment/88766944

http://stackoverflow.com/a/50980913
has body: if problem is the additional loop after opening for then: import os for fpath in (os.path.join(root, fname) for root, dirs, files in os.walk(R"python/Lib/email") for fname in files): pass # do something with the path Execution time can be reduced in many ways that depend on what you are doing in the "some work" block. If you do a lot of additional filesystem checks, you could, for example, wrap fpath in pathlib.Path(). I suggest using cProfile module to find out what is slowing your code down.
type: Answer
accepted answer of: http://stackoverflow.com/q/50980459
downvote count: 0
answers question: http://stackoverflow.com/q/50980459
score: 1
type: AcceptedAnswer
upvote count: 1

http://stackoverflow.com/comment/89010569
has text: Thanks Andreas and to datasailor below - how might I change the above code in order to have it successfully reduce the dimensions to 200?
score: 0
comment on: http://stackoverflow.com/q/51008752
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50978353
tagged with: dataframe
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/50978510
answer count: 2
downvote count: 0
has body: I am trying to create a pandas dataframe where each row is filled with the same set of values but the starting column for each row increases by 1 for every row iterating down the dataframe. Here is my current approach, and an example of the dataframe I was hoping to get. What am I doing wrong here? Thanks! import pandas as pd import numpy as np df_to_fill = pd.DataFrame(data=np.zeros((4,6)),columns=[1,2,3,4,5,6]) values_to_fill = pd.Series(np.arange(1,4)) # vars to iterate over dataframe num_rows = len(df_to_fill) # counter to keep track of how many columns to offset from to fill dataframe in loop below col_offset = 0 for row in range(0,num_rows): # Fill the first row from first column onwards, 2nd from 2nd column onwards,... df_to_fill.iloc[row,col_offset:] = values_to_fill # Fill the remaining columns in the row with the last value from the values to fill series df_to_fill.iloc[row,:].fillna(values_to_fill.values[-1],inplace=True) col_offset += 1 offset_array = np.array([[1,2,3,3,3,3],[0,1,2,3,3,3],[0,0,1,2,3,3]]) desired_df = pd.DataFrame(data=offset_array,columns=[1,2,3,4,5,6])
has title: Filling a pandas dataframe with an increasing column offset for each row
tagged with: pandas
has answer: http://stackoverflow.com/a/50978648
tagged with: python
favorite count: 0
possible better answer: http://stackoverflow.com/a/50978648
has answer: http://stackoverflow.com/a/50978510
upvote count: 1
has comment: http://stackoverflow.com/comment/88955679
has comment: http://stackoverflow.com/comment/88952900
type: AnsweredQuestion
score: 1

http://stackoverflow.com/a/50862816
type: Answer
accepted answer of: http://stackoverflow.com/q/50862793
answers question: http://stackoverflow.com/q/50862793
score: 1
has body: df['pct'] = 100 * df['value'] / df['value'].max()
upvote count: 2
has comment: http://stackoverflow.com/comment/88728263
type: AcceptedAnswer
downvote count: 1

http://stackoverflow.com/comment/88895774
type: QuestionComment
has text: In case we move down in the hierarchy (a model that inherits from a group), then it would probably be a good idea to use things like derived fields, that first inspect if values are set for the object, and if not, fallback on the group.
comment on: http://stackoverflow.com/q/50948848
score: 0
type: Comment

http://stackoverflow.com/comment/88857839
has text: @AmiHollander After getting response, encoding of response is 'ISO-8859-1'. Due to this, I am not geting actual data
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50902846

http://stackoverflow.com/a/50946773
score: 1
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/88914580
has body: You can specify a format parameter to the joined_date in the output format. class UserSerializer(serializers.ModelSerializer): date_joined = serializers.DateTimeField(format="&lt;Your format&gt;") class Meta: model = User fields = ('username', 'email', 'first_name', 'last_name', 'is_superuser', 'is_staff', 'is_active','get_absolute_url')
answers question: http://stackoverflow.com/q/50938688
downvote count: 0

http://stackoverflow.com/comment/88719992
has text: @ shmee: perhaps it is less striking that `bool(np.array(True)) is True`? hard to expect `False` here, right? this is a step in the middle in evaluating `3.3 == np.array([3.3])`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50857927
score: 0

http://stackoverflow.com/comment/88984881
has text: @Messa..please elaborate your regex
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50990661
type: Comment

http://stackoverflow.com/comment/132279296
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51003172
has text: @Pawel: Did you get around to knowing how to rewrite this type of superclass and subclass? In a way that can show the relationship of the superclass and subclass & subclass method `deliver` could have a different signature.

apache
tag name: apache
tags question: http://stackoverflow.com/q/50982146
tags question: http://stackoverflow.com/q/50964954
tags question: http://stackoverflow.com/q/50944442
tags question: http://stackoverflow.com/q/50860537
tags question: http://stackoverflow.com/q/50883456
type: Tag

http://stackoverflow.com/q/50939526
answer count: 1
tagged with: conv-neural-network
score: 0
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/88877162
has answer: http://stackoverflow.com/a/50995304
has comment: http://stackoverflow.com/comment/88877290
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88878137
tagged with: image-recognition
has comment: http://stackoverflow.com/comment/88877238
type: Question
has title: Image classifier does not generalize well to slight image perturbations
has body: I am training a CNN to classify a 28x28 rgb image into 200 categories. The classifier reaches ~95% accuracy on the train set. The test images are obtained by taking a screenshot, cropping and resizing the roi to 28x28. This image processing causes a slight difference in the train and test images (example attached). Even though the difference is almost imperceptible to the human eye it causes a huge drop in accuracy for my classifier. My classifier reaches up to 95% accuracy on the train set but only ~10% on the test set. I started applying random perturbations to the training images (blur, pixelation, noise, translation, scaling) and started blurring the test images but test accuracy only barely improved. How can I make my classifier robust so that it generalizes over slight pixel differences? Here is my network network = input_data(shape=[None, img_size[0], img_size[1], 3], name='input') conv1 = relu(batch_normalization( conv_2d(network, 16, 3, bias=False, activation=None, regularizer="L2"), trainable=is_training)) conv2 = relu(batch_normalization( conv_2d(conv1, 32, 3, bias=False, activation=None, regularizer="L2"), trainable=is_training)) conv3 = relu(batch_normalization( conv_2d(conv2, 64, 3, bias=False, activation=None, regularizer="L2"), trainable=is_training)) net = fully_connected(conv3, 128, activation='relu', regularizer="L2") net = fully_connected(net, num_elements, activation='softmax') return regression(net, optimizer='adam', learning_rate=learning_rate, loss='categorical_crossentropy', name='target') Train image: Test image
tagged with: python
tagged with: computer-vision

http://stackoverflow.com/q/50886890
has body: I am using Approach 5: Merge with Divide And Conquer to solve the merge K sorted problem in leetcode. The algorithm is very fast and takes around 100ms. However, I don't understand why the reduce approach takes much slower runtime (4000+ms). Here is the code diff: # reduce import functools return functools.reduce(_mergeTwoLists, lists) # divide and conquer step = 1 while step &lt; num: for i in range(0, num - step, step * 2): lists[i] = _mergeTwoLists(lists[i], lists[i + step]) step *= 2 return lists[0] If the divide and conquer is running in parallel, I can understand why divide and conquer is faster, but I thought it should be still running linear, right ? I also write another expensive version of merge to test the diff: def add(a, b): tmp = 0 for i in range(1, 5000): tmp += i return a + b This version running time of reduce and divide and conquer is almost identical. Is there a merge K sorted list test case that reduce can't handle ? Is there something I am missing in divide and conquer ?
score: 0
tagged with: python
has title: Why divide and conquer is fast over reduce to solve merge K sorted list
type: UnansweredQuestion
tagged with: fold
tagged with: algorithm
type: Question
tagged with: divide-and-conquer
answer count: 1
has answer: http://stackoverflow.com/a/50887088

http://stackoverflow.com/a/51020111
answers question: http://stackoverflow.com/q/51003667
downvote count: 0
type: Answer
has body: For att change wx.StaticText label you can use SetLabel. For att call vValue and cValue from another def in same Class you should rename them to self.vValue and self.cValue. def basicGUI(self): V = input('Enter V: ') C = input('Enter C: ') panel = wx.Panel(self) self.Voltage = wx.StaticText(panel, -1, "Voltage: ", (3, 3)) self.Current = wx.StaticText(panel, -1, "Current: ", (3, 23)) self.vValue = wx.StaticText(panel, -1, str(V), (70, 3)) self.cValue = wx.StaticText(panel, -1, str(C), (70, 23)) #delete inputed values and set new ex. 66,77 self.update(66,77) def update(self,V,C): self.vValue.SetLabel(str(V)) self.cValue.SetLabel(str(C)) Setlabel values should be str.
score: 1
has comment: http://stackoverflow.com/comment/89176523
has comment: http://stackoverflow.com/comment/89181707
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51003667

http://stackoverflow.com/q/50927581
has comment: http://stackoverflow.com/comment/88854804
has comment: http://stackoverflow.com/comment/88854643
upvote count: 0
duplicate of: http://stackoverflow.com/q/549674
has comment: http://stackoverflow.com/comment/88854569
has comment: http://stackoverflow.com/comment/88854268
type: Question
has comment: http://stackoverflow.com/comment/88854308
duplicate of: http://stackoverflow.com/q/8003293
linked to: http://stackoverflow.com/q/8003293
answer count: 3
downvote count: 3
has comment: http://stackoverflow.com/comment/88854939
has answer: http://stackoverflow.com/a/50927664
has comment: http://stackoverflow.com/comment/88854876
tagged with: python
has answer: http://stackoverflow.com/a/50927637
has comment: http://stackoverflow.com/comment/88854125
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88854503
has comment: http://stackoverflow.com/comment/88854424
type: UnansweredQuestion
has body: When I read a file line by line, I want to skip the first line that starts with ; after if condition[ word ] but my code gives the error below. How can I fix this error? AttributeError: '_io.TextIOWrapper' object has no attribute 'next' Code: for line in open(inputfile, "r").readlines(): if "[ word ]" in line: line = open(inputfile, "r").next()
has answer: http://stackoverflow.com/a/50927630
score: -3
has comment: http://stackoverflow.com/comment/88855097
has title: skip the first line after if condition

http://stackoverflow.com/comment/88986696
type: QuestionComment
comment on: http://stackoverflow.com/q/50996134
has text: you should post your code. Hence the downvote. Also, I haven't worked with log files, but I'm pretty they must contain some form of timestamp.
score: 0
type: Comment

http://stackoverflow.com/a/50993849
score: 1
answers question: http://stackoverflow.com/q/50993568
upvote count: 1
has comment: http://stackoverflow.com/comment/88982498
has body: Do you really need a class for this? You can use df.itertuples to create a list of "Person" namedtuples: &gt;&gt;&gt; list(df.itertuples(index=False, name='Person')) [Person(id=1, first_name='John', last_name='Doe', age=18), Person(id=2, first_name='Joe', last_name='Shmuck', age=21) ] A namedtuple behaves a lot like a class in the sense that you can access its attributes (p.age, p.id, and so on). for p in df.itertuples(index=False, name='Person'): print(p.first_name) John Joe
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88982412
type: Answer
accepted answer of: http://stackoverflow.com/q/50993568

http://stackoverflow.com/q/50991123
tagged with: python-3.x
has body: I have difficulties splitting a string into specific parts in Python 3. The string is basically a list with a colon (:) as a delimiter. Only when the colon (:) is prefixed with a backslash (\), it does not count as a delimiter but part of the list item. Example: String --&gt; I:would:like:to:find\:out:how:this\:works Converted List --&gt; ['I', 'would', 'like', 'to', 'find\:out', 'how', 'this\:works'] Any idea how this could work? @Bertrand I was trying to give you some code and I was able to figure out a workaround but this is probably not the most beautiful solution text = "I:would:like:to:find\:out:how:this\:works" values = text.split(":") new = [] concat = False temp = None for element in values: # when one element ends with \\ if element.endswith("\\"): temp = element concat = True # when the following element ends with \\ # concatenate both before appending them to new list elif element.endswith("\\") and temp is not None: temp = temp + ":" + element concat = True # when the following element does not end with \\ # append and set concat to False and temp to None elif concat is True: new.append(temp + ":" + element) concat = False temp = None # Append element to new list else: new.append(element) print(new) Output: ['I', 'would', 'like', 'to', 'find\\:out', 'how', 'this\\:works']
has comment: http://stackoverflow.com/comment/88977879
has comment: http://stackoverflow.com/comment/88977629
tagged with: python
possible better answer: http://stackoverflow.com/a/50991639
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/50991639
has answer: http://stackoverflow.com/a/50991273
upvote count: 3
has comment: http://stackoverflow.com/comment/88977847
has answer: http://stackoverflow.com/a/50991218
type: Question
tagged with: split
downvote count: 0
has comment: http://stackoverflow.com/comment/88977816
tagged with: string
favorite count: 0
has comment: http://stackoverflow.com/comment/88976936
has comment: http://stackoverflow.com/comment/88977958
accepted answer: http://stackoverflow.com/a/50991273
answer count: 3
has title: Python 3: Split string under certain condition
has comment: http://stackoverflow.com/comment/88977685
tagged with: delimiter

http://stackoverflow.com/q/50979582
type: Question
answer count: 2
downvote count: 0
has title: Issues in compiling grpc python code from protos
tagged with: proto
favorite count: 0
has body: I am using python version 2.7.6 and grpcio version 1.12.0. I have a proto with message definition containing a enum something like this enum Test { first 0; reserved 1; second 2; } Now when I try to compile using command python -m grpc_tools.protoc -I./ --python_out=. --grpc_python_out=. mydata.proto I get an error message something like this Missing numeric value for enum constant Is it because of the python and grpcio version?
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 2
has answer: http://stackoverflow.com/a/72191884
has answer: http://stackoverflow.com/a/50989879
tagged with: grpc

http://stackoverflow.com/comment/88738418
has text: @christifati that fixed it
comment on: http://stackoverflow.com/q/50868046
score: 0
type: Comment
type: QuestionComment

amazon-web-services
tags question: http://stackoverflow.com/q/50984277
tags question: http://stackoverflow.com/q/50895760
tags question: http://stackoverflow.com/q/51005511
tags question: http://stackoverflow.com/q/50975869
tags question: http://stackoverflow.com/q/50962412
tags question: http://stackoverflow.com/q/50915931
tags question: http://stackoverflow.com/q/50984887
tags question: http://stackoverflow.com/q/50885173
tags question: http://stackoverflow.com/q/50920360
tags question: http://stackoverflow.com/q/50925083
tags question: http://stackoverflow.com/q/50937959
tags question: http://stackoverflow.com/q/50901280
tags question: http://stackoverflow.com/q/50934373
type: Tag
tags question: http://stackoverflow.com/q/50978361
tag name: amazon-web-services
tags question: http://stackoverflow.com/q/50992156
tags question: http://stackoverflow.com/q/50903697
tags question: http://stackoverflow.com/q/50897984
tags question: http://stackoverflow.com/q/50980884
tags question: http://stackoverflow.com/q/50874626
tags question: http://stackoverflow.com/q/50917962
tags question: http://stackoverflow.com/q/50892938
tags question: http://stackoverflow.com/q/50970308
tags question: http://stackoverflow.com/q/50909824
tags question: http://stackoverflow.com/q/50931337
tags question: http://stackoverflow.com/q/50986575
tags question: http://stackoverflow.com/q/50871184

http://stackoverflow.com/comment/88999830
type: QuestionComment
comment on: http://stackoverflow.com/q/50972464
score: 0
type: Comment
has text: In that case we need the first ten lines of the ontology with mongodb data

http://stackoverflow.com/q/50927525
has body: I am trying to install some modules within python, they either say that the module is installed in the directory: python36-32\lib\site-packages or the directory: python\python36\site-packages
has comment: http://stackoverflow.com/comment/88855091
linked to: http://stackoverflow.com/q/647515
type: Question
has comment: http://stackoverflow.com/comment/88854325
has title: Why do I have two different python directories, python36-32 and python36?
score: 0
has comment: http://stackoverflow.com/comment/88853946
answer count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/51868655
upvote count: 1
has body: The answer is already provided in this link. Hope this helps. This will retain the style and formatting for a paragraph when you replace it with some other text.
answers question: http://stackoverflow.com/q/50963613
downvote count: 0
type: Answer
score: 1

http://stackoverflow.com/q/50923981
linked to: http://stackoverflow.com/q/8584981
upvote count: 3
has body: So I want to substitude dots in string when there is no space after of before the dots. I have thought this could be easily done with a regular expression but I haven't been able to do it. I have patterns and I want them to be: h.e.ll.o w.o.r.l.d: hello world h.e.ll.o w.o.r.l.d: hello world hello. world: hello. world I have tried the following patterns: \w+(\.)+\w+ \w+(\.+\w+) \w+\.+\w+ I always get something like: he.ll.o wo.rl.d I am using python's re module to match and replace with the following code: &gt;&gt;&gt; re.sub(r'\w+\.+\w+', lambda x: x.group(0).replace('.', ''), 'h.e.ll.o w.o.r.l.d') 'he.llo wo.rl.d'
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88847634
score: 3
possible better answer: http://stackoverflow.com/a/50924227
type: Question
has title: Replaceing dots between characters
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/50924227
favorite count: 0
accepted answer: http://stackoverflow.com/a/50924066
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/50924066

http://stackoverflow.com/comment/88763239
score: 1
has text: What you have so far?
comment on: http://stackoverflow.com/q/50880487
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88772810
type: AnswerComment
has text: @Roushan Do you understand how a list of tuples is sorted if you don't supply a key function?
type: Comment
comment on: http://stackoverflow.com/a/50885479
score: 0

http://stackoverflow.com/comment/89010735
has text: Thanks. I had already gone through that link, I just thought that is meant for AWS shell, within the cloud. Should work, will let you know.
type: AnswerComment
comment on: http://stackoverflow.com/a/51008944
score: 0
type: Comment

http://stackoverflow.com/a/50926381
answers question: http://stackoverflow.com/q/50926084
has body: try this, res= df['A'].apply(lambda x:pd.Series(list(x))) out=pd.concat([df,res],axis=1) res will contains new dataframe which is splitted by character. then merge with your old dataframe. rename the columns as your wish. It will work even dynamic range of characters. What will happend if i have seperator? just slight modification required, res= df['A'].str.split(';',expand=True) Input: A split 0 wez [w,e] 1 xy [x,y] 2 ad [a,d] 3 cf [c,f] 4 de [d,e] 5 tt [t,t] Output: A split 0 1 2 0 wez [w,e] w e z 1 xy [x,y] x y NaN 2 ad [a,d] a d NaN 3 cf [c,f] c f NaN 4 de [d,e] d e NaN 5 tt [t,t] t t NaN
accepted answer of: http://stackoverflow.com/q/50926084
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88851996
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/comment/88718090
type: Comment
has text: @DanielRoseman Oh, the url can not pass list, alright?
comment on: http://stackoverflow.com/q/50857551
score: 0
type: QuestionComment

http://stackoverflow.com/comment/88841210
type: Comment
comment on: http://stackoverflow.com/q/50920787
score: 0
has text: Meanwhile, your second question is a completely different question, so ask it separately.
type: QuestionComment

http://stackoverflow.com/a/50936394
type: Answer
has body: driver.execute_script("return $.active == 0") should help you. $.active returns the number of active Ajax requests. Link
score: 0
has comment: http://stackoverflow.com/comment/88877147
answers question: http://stackoverflow.com/q/50936242

http://stackoverflow.com/comment/88751831
type: Comment
score: 2
comment on: http://stackoverflow.com/a/50875177
type: AnswerComment
has text: The last character check could be done without a loop: `if s[-1] in string.punctuation: ...`

http://stackoverflow.com/q/50978625
tagged with: python
has body: I am trying to run one sample application with uWSGI file directive using two files for it testService.ini(config file) &amp; testService.py (application file). **testService.ini** [uwsgi] wsgi-file = '/opt/testService/testService.py' callable = app **testService.py** def application(env, start_response): start_response('200 OK', [('Content-Type','text/html')]) return [b"Hello World"] running the above file using : uwsgi --http :9090 --wsgi-file testService.ini Output: Starting uWSGI 2.0.17 (64bit) on [Thu Jun 21 15:52:33 2018] compiled with version: 5.4.0 20160609 on 14 June 2018 10:09:32 os: Linux-4.13.0-45-generic #50~16.04.1-Ubuntu SMP Wed May 30 11:18:27 UTC 2018 nodename: ubuntu machine: x86_64 clock source: unix detected number of CPU cores: 8 current working directory: /opt/testService detected binary path: /home/jmallick/.local/bin/uwsgi !!! no internal routing support, rebuild with pcre support !!! *** WARNING: you are running uWSGI without its master process manager *** your processes number limit is 15481 your memory page size is 4096 bytes detected max file descriptor number: 1024 lock engine: pthread robust mutexes thunder lock: disabled (you can enable it with --thunder-lock) uWSGI http bound on :9090 fd 4 spawned uWSGI http 1 (pid: 7848) uwsgi socket 0 bound to TCP address 127.0.0.1:45781 (port auto-assigned) fd 3 Python version: 2.7.12 (default, Dec 4 2017, 14:50:18) [GCC 5.4.0 20160609] Python threads support is disabled. You can enable it with --enable-threads Python main interpreter initialized at 0x824400 your server socket listen backlog is limited to 100 connections your mercy for graceful operations on workers is 60 seconds mapped 72920 bytes (71 KB) for 1 cores Operational MODE: single process File "testService.ini", line 2 **wsgi-file = '/opt/testService/testService.py' SyntaxError: can't assign to operator failed to compile python file testService.ini** unable to load app 0 (mountpoint='') (callable not found or import error) no app loaded…
answer count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/124499538
type: Question
has title: Syntax error while running application with uwsgi file directive for sample application
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/88953139
type: UnansweredQuestion

http://stackoverflow.com/q/50961341
has answer: http://stackoverflow.com/a/50961402
upvote count: 5
tagged with: pandas
type: AnsweredQuestion
downvote count: 0
accepted answer: http://stackoverflow.com/a/50961402
favorite count: 0
linked to: http://stackoverflow.com/q/22219004
type: Question
score: 5
tagged with: python
duplicate of: http://stackoverflow.com/q/22219004
has title: Convert groupby values into list of arrays
answer count: 1
has body: Here's a sample dataframe: label data a 1.09 b 2.1 a 5.0 b 2.0 c 1.9 What I want is arr = [[1.09, 5.0], [2.1, 2.0],[1.9]] preferably as a list of numpy arrays. I know that df.groupby.groups.keys() gives me the list ['a','b','c'], and df.groupby.groups.values() gives me something like arr, but as an Int64Index object. However, I tried df.loc[df.groupby.groups.values()]['label'] and it isn't getting the desired result. How do I accomplish this? Thanks!

http://stackoverflow.com/q/50963629
tagged with: indexing
tagged with: dataframe
type: Question
has comment: http://stackoverflow.com/comment/88924122
tagged with: pandas
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/50963796
favorite count: 0
has body: I have dataframe as follows: A B 1 2 3 4 5 4 5 6 7 8 I am trying to fetch data from this dataframe in following ways: print (file_dataframe.columns) Index(['A', 'B', 'Unnamed: 2'], dtype='object') file_dataframe_values = [cell for column in file_dataframe.columns for cell in file_dataframe[column].values.tolist()] print (file_dataframe_values ) ['3', '6', '4', '7', '5', '8'] Why it is starting dataframe from first values in first row? When I am using following dataframe: A 1 2 3 4 5 4 5 6 7 8 print (file_dataframe.columns) Index(['A', 'Unnamed: 1', 'Unnamed: 2','Unnamed: 3'], dtype='object') file_dataframe_values = [cell for column in file_dataframe.columns for cell in file_dataframe[column].values.tolist()] print (file_dataframe_values ) ['2','5','3', '6', '4', '7', '5', '8'] When I am using following data frame as first row is empty: 1 2 3 4 5 4 5 6 7 8 print (file_dataframe.columns) Index(['Unnamed: 0', 'Unnamed: 1', 'Unnamed: 2','Unnamed: 3','Unnamed: 4'], dtype='object') file_dataframe_values = [cell for column in file_dataframe.columns for cell in file_dataframe[column].values.tolist()] print (file_dataframe_values ) ['1','4','2','5','3', '6', '4', '7', '5', '8'] Can anyone please explain this behavior?
tagged with: python
score: 2
upvote count: 2
type: UnansweredQuestion
has title: Fetch values in dataframe

http://stackoverflow.com/comment/89020042
has text: Move `from types import MethodType` from inside your method, and this is a fine solution.
comment on: http://stackoverflow.com/a/51006675
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88764749
type: Comment
type: QuestionComment
has text: I want the number of consecutive non-scoring matches per team.
comment on: http://stackoverflow.com/q/50875234
score: 0

http://stackoverflow.com/q/50858871
type: UnansweredQuestion
has title: Error when checking target: expected dense_1 to have shape (257, 257) but got array with shape (257, 1)
linked to: http://stackoverflow.com/q/50848107
type: Question
has comment: http://stackoverflow.com/comment/88720975
tagged with: dimensions
has comment: http://stackoverflow.com/comment/88720486
has comment: http://stackoverflow.com/comment/88720390
tagged with: neural-network
tagged with: lstm
has comment: http://stackoverflow.com/comment/88731148
score: 0
tagged with: keras
has comment: http://stackoverflow.com/comment/88720840
tagged with: python
has body: print(X.shape,Y.shape) #(5877, 257, 1) (5877, 257, 1) model = Sequential() model.add(LSTM(257, input_shape=(257,1),stateful=False,return_sequences=True)) model.add(Dense(257, activation='sigmoid')) model.compile(loss=losses.mean_squared_error, optimizer='adam', metrics=['accuracy']) model.fit(x=X,y=Y,epochs=100,shuffle=False) Error when checking target: expected dense_1 to have shape (257, 257) but got array with shape (257, 1) I should give 5877 frames of size 257 to lstm layer. The output has the same format. Where I was mistaken?
answer count: 0

http://stackoverflow.com/comment/89014585
type: Comment
comment on: http://stackoverflow.com/a/51010827
has text: When I read and replace, all good ( it does work, I can read the file and it does replace), but when I write it back to file (file is empty) with no error. The issue with writing the data to the same file ( as if I write to different one, it does work.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/89009696
has text: Keep in mind, that this would work if such values as zeroes, empty collections and other stuff which evaluate to False is NOT a valid value for y.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51008347

http://stackoverflow.com/a/50988132
downvote count: 0
has body: Your training and testing data are rescaled by factor of 1/255. But at prediction time you are not rescaling the image. try rescaling the image as follows. test_image *= (1/255.0) result = classifier.predict(test_image) EDIT: If the training and test dataset have single class then there is no way the model is going to classify input into two classes. Your prediction should be based on the training and test data classes(Your dataset for prediction should come from distribution which is similar to train and test dataset distribution). If you have two classes in train and test dataset then try to assign 0 for one of(first) the classes and 1 for other(second). Then when predicting the classes if the model predicts number less than 0.5 then it is predicting the first class, if the model predicts number greater than or equals to 0.5 then the model is predicting the second class
accepted answer of: http://stackoverflow.com/q/50988050
type: AcceptedAnswer
score: 1
answers question: http://stackoverflow.com/q/50988050
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/88971804

http://stackoverflow.com/comment/88860955
type: QuestionComment
comment on: http://stackoverflow.com/q/50930900
has text: this might help: https://github.com/esc/git-big-picture
score: 2
type: Comment

http://stackoverflow.com/q/50861003
answer count: 4
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/75903398
accepted answer: http://stackoverflow.com/a/50861145
type: Question
tagged with: numpy
tagged with: performance
score: 10
possible better answer: http://stackoverflow.com/a/50861623
has answer: http://stackoverflow.com/a/50861145
has answer: http://stackoverflow.com/a/50861266
has title: Applying last valid index mask to dataframe to get last valid values
tagged with: pandas
has body: I have a dataframe that looks like the following: s1 s2 s3 s4 0 v1 v2 v3 v4 0 v5 v6 v7 np.nan 0 v8 np.nan v9 np.nan 0 v10 np.nan np.nan np.nan Essentially from top down there are numerical values and across columns at some random index values will switch to np.nan only. I've used .apply(pd.Series.last_valid_index) to get the indexes for which the values are still numerical, however, I'm not sure of the most efficient way to retrieve a series for which I have the actual value at the last valid index. Ideally I'd be able to derive a series that looks like: value s1 v10 s2 v6 s3 v9 s4 v4 or as a dataframe that looks like s1 s2 s3 s4 0 v10 v6 v9 v4 Many thanks!
favorite count: 0
upvote count: 10
has answer: http://stackoverflow.com/a/50861623
tagged with: python

http://stackoverflow.com/comment/88992773
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50999309
type: Comment
has text: @abarnert for the second comment, I think my explanation is reasonable. The OP didn't say what they expected in that case, I just gave an example of how one might go about handling something they may not have even considered. But I will have a think how to coherently change (2) to fit with the narrative I had in my head.

http://stackoverflow.com/q/50856449
has body: So basically I have a WSI (Whole slide image) which looks like this: And I have a png mask which looks like this: along with its position on the WSI (x: 1098,y: 2116, width: 167, height: 378) Now what I want to do is to take the WSI, create patches of dimension 96x96 out of the WSI and for each of these patches I want to check if the white area under the mask file is present in at least 2/3 of the created patch. For instance here is my pseudo code to create the patches: self.crop_size = 96 is_fit = False while True: patch_x = 0 while True: patches.append((patch_x, patch_y, self.crop_size, self.crop_size, is_fit)) if patch_x + self.crop_size &gt; width: patch_x = width - self.crop_size patches.append((patch_x, patch_y, self.crop_size, self.crop_size, is_fit)) break else: patch_x += self.crop_size if patch_y + self.crop_size &gt; height: patch_y = height - self.crop_size patches.append((patch_x, patch_y, self.crop_size, self.crop_size, is_fit)) break else: patch_y += self.crop_size Now for each patch (I consider a patch the tuple I insert in patches.append()) I want to be able to set True to is_fit if at least 2/3 of the white area of the mask is present in the patch. Note that here I'm authorized to open the mask file from the code but not the WSI as it will eat up too much memory. Any ideas? Thank you.
answer count: 1
has answer: http://stackoverflow.com/a/50857333
tagged with: python
tagged with: opencv
type: AnsweredQuestion
tagged with: python-imaging-library
score: 0
has title: Get area between pixel wise masks and WSI patches
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/50857333

http://stackoverflow.com/a/50893357
has body: May be you can have two list of month and year since, these will be fixed. Then, you can randomly choose between each and make a date to return. That way I think then no need to generate all different dates and no need to store in large list: from random import choice def get_month(): months = list(range(1, 13)) # 12 months list year = list(range(2016, 2019)) # years list here val = '{}-{:02d}'.format(choice(year), choice(months)) return val get_month() Result: '2017-05' Update Just in case if there is limitation on not exceeding current month if the year selected is current year then, you may need if condition for generating list of months as below: from random import choice from datetime import datetime def get_month(): today = datetime.today() # get current date year = list(range(2016, today.year+1)) # list till current date year # randomly select year and create list of month based on year random_year = choice(year) # if current year then do not exceed than current month if random_year == today.year: months = list(range(1, today.month+1)) else: # if year is not current year then it is less so can create 12 months list months = list(range(1, 13)) val = '{}-{:02d}'.format(random_year, choice(months)) return val
score: 5
has comment: http://stackoverflow.com/comment/88787519
has comment: http://stackoverflow.com/comment/88787358
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88787366
has comment: http://stackoverflow.com/comment/88787421
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/88788258
accepted answer of: http://stackoverflow.com/q/50893325
answers question: http://stackoverflow.com/q/50893325

http://stackoverflow.com/comment/88787519
has text: It depends on what distribution OP really is looking for here. (For what purpose/application?) My point was that for proper uniformity in date, February should have (on average) a `~28.25/365.25` chance of being chosen. This percentage depends on the year (among possibly other factors).
type: Comment
score: 1
comment on: http://stackoverflow.com/a/50893357
type: AnswerComment

airflow
tags question: http://stackoverflow.com/q/50952568
tags question: http://stackoverflow.com/q/50934266
tag name: airflow
type: Tag

http://stackoverflow.com/q/50956897
has comment: http://stackoverflow.com/comment/88911402
type: UnansweredQuestion
tagged with: python
tagged with: pygame
has answer: http://stackoverflow.com/a/50959769
has body: I have a single battery image appearing once here and it moves from right to left then goes away. I want batteries constantly coming and going until the player hits one of them. My question is how do I get the batteries to keep on coming until a player hits it? I want them to appear maybe 100 units apart. from pygame import * import os import random os.environ['SDL_VIDEO_WINDOW_POS'] = "%d, %d" %(0, 0) init() #set screen size size = width, height = 800, 600 screen = display.set_mode(size) #set fonts fontGame=font.SysFont("Times New Roman", 30) fontBack=font.SysFont("Ariel", 30) fontTitle=font.SysFont("Ariel", 100) fontResearch=font.SysFont ("Times New Roman", 18) #set button and page to 0 button = 0 page=0 #setting colours BLACK = (0, 0, 0) RED = (255,0,0) GREEN = (0, 255, 0) BLUE = (106,186,232) #loading image backgroundPic=image.load("Background.jpg") backgroundGame=image.load("gameBackground.jpg") backgroundGame=transform.scale(backgroundGame,(800,600)) battery=image.load("Battery.png") battery=transform.scale(battery,(100,100)) backgroundx=0 playerPic=image.load("player.png") playerPic=transform.scale(playerPic,(70,70)) batteryx=[] #defining what is going to be shown on the screen def drawScene(screen, button,page,locationx,locationy): global batteryx mx, my = mouse.get_pos() #will get where the mouse is #if the user does nothing if page==0: draw.rect(screen, BLACK, (0,0, width, height)) screen.fill(BLACK) rel_backgroundx= backgroundx % backgroundGame.get_rect().width screen.blit(backgroundGame, (rel_backgroundx - backgroundGame.get_rect().width,0)) if rel_backgroundx &lt; width: screen.blit (backgroundGame, (rel_backgroundx,0)) screen.blit(playerPic,(locationx,locationy)) screen.blit(battery,(batteryx,420)) batteryx-=1 display.flip() return page #def collision (battery, playerPic): #if battery.colliderect(playerPic): #return True #return False running = True myClock = time.Clock() KEY_LEFT= False KEY_RIGHT= False KEY_UP= False KEY_DOWN= False locationx=0 jumpin…
has comment: http://stackoverflow.com/comment/88914269
type: Question
downvote count: 2
has title: Having an image appear multiple times Pygame
score: -1
upvote count: 1
has comment: http://stackoverflow.com/comment/88916156
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/88896996
score: 0
type: Comment
type: QuestionComment
has text: Also a (500, 500, 3000000) bool matrix is almost 700 GiB. A bitwise representation reduces that to under 90 GiB, but means you can't use basic Numpy matrices.
comment on: http://stackoverflow.com/q/50943043

http://stackoverflow.com/comment/125627927
type: Comment
has text: After following these instructions, I had to restart my ipython shell for matplotlib to find the font.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52527960

http://stackoverflow.com/comment/135683763
type: AnswerComment
comment on: http://stackoverflow.com/a/73634275
has text: complex number is not a standard feature of JSON, so you might have to take some extra care to make sure that the deserializer understands your chosen format
type: Comment
score: 0

http://stackoverflow.com/comment/88927515
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50965291
type: Comment
has text: GPU execution time varies according to system configurations. Are you sure, you are using your GPU while executing the program? what's the output of `torch.cuda.is_available()`?

http://stackoverflow.com/comment/111677845
comment on: http://stackoverflow.com/a/50891011
score: 0
type: Comment
has text: in my case this quoting=csv.QUOTE_NONNUMERIC was causing the quoting of the NULL
type: AnswerComment

http://stackoverflow.com/comment/88937645
has text: The extra tables originate from many-to-many relations, and from some default apps that ship with Django (for example for authentication).
type: Comment
comment on: http://stackoverflow.com/q/50970582
type: QuestionComment
score: 2

http://stackoverflow.com/comment/115674389
type: AnswerComment
comment on: http://stackoverflow.com/a/50918585
score: 0
type: Comment
has text: @NazimKerimbekov I might have misunderstood OP's intentions. The question explicitly asks for "form data", has the tag "forms", and the given code example describes the key-value-pairs commonly found in `multipart/form-data` [encoding type](https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/enctype). "Use JSON" may be a good advice, but OP does not seem to have the option of changing the server's interface to JSON.

http://stackoverflow.com/comment/88755186
score: 0
type: Comment
type: QuestionComment
has text: Huh? You only get one command line -- you have to exit, not loop, to get another. If you want to prompt for input on stdin, that's doable, but a different thing from the command-line argument list.
comment on: http://stackoverflow.com/q/50876568

http://stackoverflow.com/q/50957080
tagged with: python
has title: In Github, can I run a python script from a different repo than where it's stored?
downvote count: 0
type: UnansweredQuestion
score: 1
has answer: http://stackoverflow.com/a/50957239
has comment: http://stackoverflow.com/comment/88935115
has answer: http://stackoverflow.com/a/50957137
has comment: http://stackoverflow.com/comment/88911642
has body: Let's say I have a a repo that has a python script stored in it, then another repo where I want to run that script, such as below within repo1. sh "python repo2/src/python.py --arg value --arg2 value2" I'm sorry. I know this seems like a simple question, but I either don't know how to phrase my question or else it's just not possible. Thank you. More info: The script is part of a repo and this is where it needs to live, especially to stay modular. The other repo is a for a pipeline and it has a groovy Jenkinsfile. This is where I want to pull that script and run in within the Jenkinsfile
type: Question
answer count: 2
upvote count: 1
tagged with: github
favorite count: 0

http://stackoverflow.com/comment/88873415
has text: Where are those frequencies coming from? How are those values selected?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50937231

http://stackoverflow.com/a/50989023
type: Answer
has body: Seems like google-gax is deprecated (https://pypi.org/project/google-gax/) it has been wholly replaced by google-api-core (https://pypi.org/project/google-api-core/).
has comment: http://stackoverflow.com/comment/88974986
answers question: http://stackoverflow.com/q/50977476
score: 0

http://stackoverflow.com/a/50975491
downvote count: 0
has body: As @abarnert mentioned, the solution here is not to write better loops, but (since you're using Numpy) to not loop in Python at all by understanding how to use Numpy in more advanced ways. What you have is a matrix like [ [idx, v0a, v0b, v1a, v1b, ... ], ... ] And you want a matrix that's basically [ [idx, 1 if v0a &lt; 0 else 0, 1 if v0b &gt; 0 else 0, ... ], ... ] We're going to do this in two steps: first, we'll transform the matrix slightly so that the comparisons are all the same; second, we'll apply the comparison in-place. The only difference between how we handle "even" and "odd" columns is that one is being checked for &lt;0, the other >0. If we modify the second group of columns by multiplying them by -1, then these comparisons both become simply &lt;0: datain[:, 2::2] *= -1 Now we just want to know, for every value (besides the first column), is that value &lt;0. This is super easy: datain[:, 1:] &lt; 0 This returns a matrix of boolean values, where each value represents whether or not the corresponding cell in datain[:, 1:] was less than 0. You want these as integers, 1 for True and 0 for False; it turns out, when we assign these boolean values back into our original array (which contains floats), numpy will cast the bools into floats automatically; True will get cast to 1.0, and False will get cast to 0.0. If you don't want to throw away your original data, simply copy it off first. Here's the complete code: # If you want to preserve your old data, create a copy for us to modify dataout = np.array(datain) # Now assign your integer values into your data array dataout[:, 2::2] *= -1 dataout[:, 1:] = datain[:, 1:] &lt; 0 For the sample input you provided: array([[ 0. , 72.25 , 158.622, 86.575, 151.153, 85.807, 149.803, 84.285, 143.701, 77.723, 160.471, 96.587, 144.02 , 75.827, 157.071, 87.629, 148.856, 100.814, 140.488], [ 10. , 56.224, 174.351, 108.309, 154.148, 68.564, 155.721, 83.634, 132.836, 75.03 , 177.971, 100.623, 146.616, 61.856, 150.885, 92.147, …
type: Answer
has comment: http://stackoverflow.com/comment/88947522
answers question: http://stackoverflow.com/q/50974924
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/88947082

python-imaging-library
tags question: http://stackoverflow.com/q/51007035
tags question: http://stackoverflow.com/q/50924974
tags question: http://stackoverflow.com/q/50883894
tags question: http://stackoverflow.com/q/50963537
tags question: http://stackoverflow.com/q/50880843
tags question: http://stackoverflow.com/q/50888786
tags question: http://stackoverflow.com/q/50861142
tags question: http://stackoverflow.com/q/50871340
tags question: http://stackoverflow.com/q/50906964
tags question: http://stackoverflow.com/q/51010315
tags question: http://stackoverflow.com/q/50989759
tags question: http://stackoverflow.com/q/50889958
tag name: python-imaging-library
tags question: http://stackoverflow.com/q/50944106
tags question: http://stackoverflow.com/q/50927972
type: Tag
tags question: http://stackoverflow.com/q/50912978
tags question: http://stackoverflow.com/q/50880443
tags question: http://stackoverflow.com/q/50958972
tags question: http://stackoverflow.com/q/50859188
tags question: http://stackoverflow.com/q/50881318
tags question: http://stackoverflow.com/q/50892479
tags question: http://stackoverflow.com/q/50898034
tags question: http://stackoverflow.com/q/50870189
tags question: http://stackoverflow.com/q/50902087
tags question: http://stackoverflow.com/q/50892064
tags question: http://stackoverflow.com/q/50960316
tags question: http://stackoverflow.com/q/50856449
tags question: http://stackoverflow.com/q/50916291
tags question: http://stackoverflow.com/q/50869559

http://stackoverflow.com/q/50860645
has comment: http://stackoverflow.com/comment/88743880
has comment: http://stackoverflow.com/comment/88805275
has comment: http://stackoverflow.com/comment/88751095
type: Question
has comment: http://stackoverflow.com/comment/88739507
tagged with: nltk
has body: Was trying to write a small program on sentiment analysis in python3. But while working with word lemmatizer saw strange conversion of "was" to "wa" which was completely unexpected. Below is my pre-process code - please help me to understand how can i avoid these issues. Also if POS tagging is must to get correct lemmatizer how do I include it correctly and efficiently in my preprocess function wordnet_lemmatizer = WordNetLemmatizer() stoplist = stopwords.words('english') + list(string.punctuation) def preprocess(text): return [wordnet_lemmatizer.lemmatize(word) for word in word_tokenize(text) if wordnet_lemmatizer.lemmatize(word.lower()) not in stoplist and not word.isdigit() and len(word)&gt;2] The input text was basically the corpora from Multi-Domain Sentiment Dataset (version 2.0) and the line which caught my attention was below &lt;review_text&gt; I just recieved my HDMI cable and am very impressed. The price is just what it should be about $5 and makes me wonder how somebody would spend over $100 for this cable at a store. The service was excellent and the cable arrived in 4 days! I highly recommend this cable. I just plugged it into my cable box and the other end into the TV and WOW what a great picture all around. The color is just so much more vivid using HDMI compared to component 3 wire connectors. Get this cable for your system and stay away from those high priced others &lt;/review_text&gt; And the output of the function after lemmatizer is ['recieved', 'HDMI', 'cable', 'impressed', 'price', 'make', 'wonder', 'somebody', 'would', 'spend', 'cable', 'store', 'service', 'wa', 'excellent', 'cable', 'arrived', 'day', 'highly', 'recommend', 'cable', 'plugged', 'cable', 'box', 'end', 'WOW', 'great', 'picture', 'around', 'color', 'much', 'vivid', 'using', 'HDMI', 'compared', 'component', 'wire', 'connector', 'Get', 'cable', 'system', 'stay', 'away', 'high', 'priced', 'others'] What got me bowled out completely is how "was" converts into "wa" ?? There are other…
tagged with: lemmatization
tagged with: sentiment-analysis
downvote count: 0
favorite count: 0
tagged with: python-3.x
linked to: http://stackoverflow.com/q/15586721
tagged with: python
duplicate of: http://stackoverflow.com/q/15586721
has title: NLTK word Lemmatizer strange behavior - help in POS tagging - Python 3
has comment: http://stackoverflow.com/comment/88740310
answer count: 0
type: UnansweredQuestion
score: 1
upvote count: 1

http://stackoverflow.com/comment/88867200
has text: Could you please post any error messages while using VS, we need those to help.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50934333

http://stackoverflow.com/a/51027370
answers question: http://stackoverflow.com/q/50975447
score: 2
has body: I've been running into the same issue. Be sure you're dealing with a Classification problem and not a Regression problem. If your target column is continuous, you might want to use http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestRegressor.html instead of RandomForestClassifier.
type: AcceptedAnswer
downvote count: 0
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50975447
type: Answer

setter
tags question: http://stackoverflow.com/q/50935795
type: Tag
tag name: setter

http://stackoverflow.com/comment/88936599
type: Comment
score: 1
comment on: http://stackoverflow.com/a/50969983
type: AnswerComment
has text: it will - unless you specify `print( ... stuff ... , sep="")`

http://stackoverflow.com/a/51125594
has body: Quick working solution for you: #!/usr/bin/python3 from telegram.ext import Updater, MessageHandler, Filters from telegram.ext import RegexHandler from string import ascii_lowercase from string import digits from random import choice from sys import exc_info as error token = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' def start(bot, update): username = update.message.from_user.first_name update.message.reply_text(greeting(username), parse_mode='Markdown') message = genre_head() for genre in genres: message += genre_list(genre['name'], genre['id']) update.message.reply_text(message, parse_mode='Markdown') def artist(bot, update): genre_id = update.message.text.replace('/dl_', '') for genre in genres: if genre['id'] == genre_id: message = artist_head(genre['name']) for artist in artists: message += artist_list(artist['id'], artist['name'], genre_id) message += artist_list_end() update.message.reply_text(message, parse_mode='Markdown') def download(bot, update): file = update.message.text.replace('/dl_', '') update.message.reply_text(u'\U0001F3BC\nhttp://music.com/{}.mp3'.format(file), parse_mode='Markdown') try: updater = Updater(token) dp = updater.dispatcher dp.add_handler(RegexHandler('/start', start)) dp.add_handler(RegexHandler('^(/dl_[\d]+)$', artist)) dp.add_handler(RegexHandler('^(/dl_[\d]+[\w]+)$', download)) dp.add_handler(MessageHandler(Filters.text, start)) updater.start_polling() except: print(error()) updater.stop() ################################################################################ # Messeges def greeting(first_name): return '*Hello and welcome, {}!*\n'.format(first_name) def genre_head(): return '*What your favorite genre?*\n' def genre_list(genre_name, genre_id): return '\n{}*{}*\n[ Choose {} /dl_{} ]\n'.format(u'\U0001F3B6', genre_name, u'\U0001F449', genre_id) def artist_head(genre_name): return 'What artist in {}*{}* you are looking for?\n'.format(u'\U0001F3B6', genre_name) def artist_list(artist_id, artist_name, genre_id): retu…
type: Answer
upvote count: 6
answers question: http://stackoverflow.com/q/50960420
score: 6
accepted answer of: http://stackoverflow.com/q/50960420
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/50971832
has comment: http://stackoverflow.com/comment/88940182
downvote count: 2
has comment: http://stackoverflow.com/comment/88940642
upvote count: 7
answer count: 1
tagged with: python-typing
favorite count: 0
has body: I was reading here, but it's about type hinting for namedtuples. Is it possible to create a type hint for a List that contains a namedtuple? For example: firefoxprofile = namedtuple("Profile", ["Name", "Path", "isRelative", "Default"]) # Will contain a list of tuples that represent the firefox profiles. ffprofiles = [] # -- how would I write the type hint? ffprofiles.append(Profile(Name='Jason', Path='Profiles/er5rtak4.Jason', isRelative='1', Default=None)) ffprofiles.append(Profile(Name='Sarah', Path='Profiles/23mvfqcj.Sarah', isRelative='1', Default=None)) I tried: ffprofiles = List[namedtuple("Profile", ["Name", "Path", "isRelative", "Default"])] but that doesn't work, when I try to update the ffprofiles = [] line with that syntax, I get an exception: TypeError: descriptor 'append' requires a 'list' object but received a 'Profile'
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88940556
has answer: http://stackoverflow.com/a/50974180
accepted answer: http://stackoverflow.com/a/50974180
has comment: http://stackoverflow.com/comment/88940681
type: Question
score: 5
has title: Type hint for List that contains a namedtuple
linked to: http://stackoverflow.com/q/34269772
has comment: http://stackoverflow.com/comment/88940509

http://stackoverflow.com/comment/88826349
has text: Thanks for a hint. Indeed, it is possible to import robot resource using robot.libraries.BuiltIn import BuiltIn BuiltIn().import_resource('${EXECDIR}/resource.robot') . However, how can I access any keyword from imported Robot resource inside Python script?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50871611
type: QuestionComment

http://stackoverflow.com/comment/88855847
has text: @nonamelowlife: I also double-checked the [ECMA standard documentation](https://www.ecma-international.org/publications/standards/Ecma-376.htm) on where tables can be defined; the above loop is guaranteed to find all paragraphs and tables in a word document.
comment on: http://stackoverflow.com/a/50857274
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/50955963
upvote count: 1
has comment: http://stackoverflow.com/comment/88909840
type: Question
has comment: http://stackoverflow.com/comment/88909446
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88910083
has comment: http://stackoverflow.com/comment/88909478
has answer: http://stackoverflow.com/a/50956107
score: -2
has comment: http://stackoverflow.com/comment/88910148
has body: I need to call a function, exactly 08:00, 18:00, 22:00 hours. I've created a example to test the comparison between hours. When the current time reaches one of those horary. Put in inside a While loop thinking this example would work as a stopwatch, but I think I'm wrong. How is the best way to compare those values? currentH= dt.datetime.now().strftime("%H:%M:%S") h = "16:15:10" while True: if(currentH==h): print 'Ok' print 'The current Hour is: '+h
answer count: 2
has comment: http://stackoverflow.com/comment/88909854
favorite count: 0
accepted answer: http://stackoverflow.com/a/50956107
possible better answer: http://stackoverflow.com/a/50956277
tagged with: python
has title: Python: How to compare two hours
has answer: http://stackoverflow.com/a/50956277
downvote count: 3

http://stackoverflow.com/q/50939381
score: 1
tagged with: file
has body: I have a file (rawbytes.data). It contains raw bytes as YUV NV12 format. It contains one frame of a grayscale image(640x480). How would i parse this data file and present a png? The .data file looks as follows in Sublime Text: 0000 0000 0000 0000 6c05 0000 8002 0000 e001 0000 0707 0807 0808 0a0b 0e0f 1112 1515 1512 120f 0f0d 0c0e 0e10 1011 1110 0f0d 0e0b 0b0c 0e0e 0f0d 0c0e 0c0c 0b0a 0908 0a0a 0a0a 0908 0a08 0808 0708 0809 0809 0b09 0b09 0b0f 1214 1416 1413 1112 0f09 0809 0c0e 1010 1111 1110 0e0e 0d0c 0a08 0807 0708 0708 0707 0708 0606 0707 0707 0807 0708 0708 0807 0707 0708 0807 0808 0707 0707 0807 0808 0706 0707 0807 0807 0807 0707 0807 0707 0808 0808 0708 0706 0707 0807 0708 0808 0808 0808 0708 0808 0807 0808 0708 0807 0809 0707 0908 0808 0808 0908 0708 0707 0807 0808 0708 0707 0808 0708 0809 0808 0708 0708 0707 0808 0808 0707 0707 0708 0807 0809 0708 0808 0809 0908 0807 0809 0908 0808 0808 0808 0808 0809 0808 0809 0808 0808 0808 0908 0808 0908 0908 0909 0809 0908 0808 0708 0809 0909 0909 0809 0908 0908 0809 0909 0809 0909 0808 0808 0809 0808 0909 0808 0709 0808 0808 0809 0809 0809 0808 I tried to use python to open file in 'rb' mode and write it in 'wb' to a png file but doesn't work. with open('rawbytes.data', 'rb') as f: data = f.read() with open('picture_out.png', 'wb') as f: f.write(data)
type: Question
has title: Parse data and present PNG image
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/88877427
downvote count: 0
tagged with: yuv
favorite count: 0
tagged with: python
tagged with: computer-vision
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50941698
accepted answer: http://stackoverflow.com/a/50941698

http://stackoverflow.com/comment/135549244
score: 0
type: Comment
has text: @user3754136, I've added another similar method that might help you.
type: AnswerComment
comment on: http://stackoverflow.com/a/67794630

http://stackoverflow.com/comment/89007593
type: QuestionComment
comment on: http://stackoverflow.com/q/50999495
has text: Within the while loop, you don't have to run the for loop.
score: 0
type: Comment

http://stackoverflow.com/q/51006743
downvote count: 0
answer count: 1
has title: django; Cannot upload image and form data is invalid
favorite count: 0
tagged with: django
tagged with: python
type: AnsweredQuestion
has body: I'm new to django and I am practicing with it now. I am creating image uploading system, but I cannot upload image uisng form even though I can post and save data through admin. Here is my code. models.py class Item(models.Model): title = models.CharField(max_length=50) image = models.ImageField(upload_to='item', max_length=255) price = models.DecimalField(max_digits=4, decimal_places=1) description = models.TextField() created = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(settings.AUTH_USER_MODEL , on_delete=models.CASCADE) forms.py class ItemForm(forms.ModelForm): class Meta: model = Item fields = ['title', 'image', 'price', 'description'] widgets = {'text': forms.Textarea(attrs={'cols': 80})} views.py def sell_item(request): if request.method != 'POST': form = ItemForm() else: form = ItemForm(data=request.POST) if not form.is_valid(): raise ValueError('invalid form') new_item = form.save(commit=False) new_item.user = request.user new_item.save() return HttpResponseRedirect('mainapp:index') return render(request, 'mainapp/sell.html', {'form': form}) here is html code of the part. {% csrf_token %} {{ form.as_p }} submit When I fill out the data and submit them, it raises ValueError. form looks good so I guess there is a problem with how to save the image data or html code but I cannot understande how to fix this. Please help.
score: 1
has answer: http://stackoverflow.com/a/51006773
accepted answer: http://stackoverflow.com/a/51006773
type: Question
upvote count: 1

azure-iot-hub
type: Tag
tags question: http://stackoverflow.com/q/50986361
tag name: azure-iot-hub

http://stackoverflow.com/a/50934739
answers question: http://stackoverflow.com/q/50934086
score: 0
type: Answer
has body: The following solution should solve your problem in a single pass - a single run through of the array. Much more performing than the solution by Ajax1234, austin and taras . Of course you can compress this code even more. count = -1 newList = [] for indx,ele in enumerate(List1): if indx == 0: continue if List1[indx]==List1[indx-1]: count+=1 newList.append(List1[indx-1]+str(chr(97+count))) elif count == -1: newList.append(List1[indx-1]) else: count+=1 newList.append(List1[indx-1]+str(chr(97+count))) count = -1 if count == -1: newList.append(List1[indx]) else: count +=1 newList.append(List1[indx]+str(chr(97+count)))

http://stackoverflow.com/a/50888568
has comment: http://stackoverflow.com/comment/88778533
answers question: http://stackoverflow.com/q/50888178
type: Answer
has body: The problem with your code is the fact that you call your date_range variable range...range is a reserved word in Python and thus you must definitely avoid giving such a name to a user-defined variable. Actually, changing range to range_b or something else will make your code run perfectly ! import pandas as pd df_b = pd.DataFrame([["18.09.2017 07:27:03", 14.4, 23333.222334], ["18.09.2017 07:29:33", 13.1, 23562.233223], ["18.09.2017 07:32:03", 12.5, 23234.244644], ["18.09.2017 07:34:33", 13.5, 23111.373561], ["18.09.2017 07:37:03", 13.1 ,12311.373633]], columns = ["datetimecolumn","data1", "data2"]) range_b =pd.date_range(start='2017-10-01',end='2017-10-31',freq='2.5min') df_b['t_index']=pd.to_datetime(df_b['datetimecolumn']) df_b.set_index('t_index', inplace=True) df_b=df_b.reindex(range_b, method='nearest') df_b datetimecolumn data1 data2 2017-10-01 00:00:00 18.09.2017 07:37:03 13.1 12311.373633 2017-10-01 00:02:30 18.09.2017 07:37:03 13.1 12311.373633 2017-10-01 00:05:00 18.09.2017 07:37:03 13.1 12311.373633 2017-10-01 00:07:30 18.09.2017 07:37:03 13.1 12311.373633 2017-10-01 00:10:00 18.09.2017 07:37:03 13.1 12311.373633 2017-10-01 00:12:30 18.09.2017 07:37:03 13.1 12311.373633 2017-10-01 00:15:00 18.09.2017 07:37:03 13.1 12311.373633 2017-10-01 00:17:30 18.09.2017 07:37:03 13.1 12311.373633 2017-10-01 00:20:00 18.09.2017 07:37:03 13.1 12311.373633 2017-10-01 00:22:30 18.09.2017 07:37:03 13.1 12311.373633
has comment: http://stackoverflow.com/comment/88779517
score: 0
has comment: http://stackoverflow.com/comment/88778812
has comment: http://stackoverflow.com/comment/88778675
has comment: http://stackoverflow.com/comment/88779041

http://stackoverflow.com/comment/88820573
has text: @Georgy: I have other zones in the image that might have long contours (btw, what do you consider the "biggest"? is it perimeter? area?). Could you post an answer with it? Thank you in advance (I have already read the doc about it, but everytimes I use opencv and image processing, the devil is in the details ;) to get a usable/good precision).
type: Comment
comment on: http://stackoverflow.com/q/50909993
score: 0
type: QuestionComment

http://stackoverflow.com/q/50910828
type: AnsweredQuestion
tagged with: classification
has title: Keras model doesn't seem to work
type: Question
accepted answer: http://stackoverflow.com/a/50929803
has comment: http://stackoverflow.com/comment/88829666
score: 0
has body: I have the following keras model and when I train the model, it doesn't seem to learn from it. I asked around and got different suggestions like weights are not initialised properly or back-propogation is not happening. The model is: model.add(Conv2D(32, (3, 3), kernel_initializer='random_uniform', activation='relu', input_shape=(x1, x2, depth))) model.add(MaxPool2D(pool_size=(2, 2))) model.add(Conv2D(64, (3, 3), activation='relu')) model.add(MaxPool2D(pool_size=(2, 2))) model.add(Flatten()) model.add(Dense(128, activation='relu')) model.add(Dense(3, activation='softmax')) I even looked at this solution but I don't seem to have done that. I have softmax in the end. For your reference, I have the output of the training process: Epoch 1/10 283/283 [==============================] - 1s 2ms/step - loss: 5.1041 - acc: 0.6254 - val_loss: 9.0664 - val_acc: 0.4375 Epoch 2/10 283/283 [==============================] - 0s 696us/step - loss: 4.9550 - acc: 0.6926 - val_loss: 9.0664 - val_acc: 0.4375 Epoch 3/10 283/283 [==============================] - 0s 717us/step - loss: 4.9550 - acc: 0.6926 - val_loss: 9.0664 - val_acc: 0.4375 Epoch 4/10 283/283 [==============================] - 0s 692us/step - loss: 4.9550 - acc: 0.6926 - val_loss: 9.0664 - val_acc: 0.4375 Epoch 5/10 283/283 [==============================] - 0s 701us/step - loss: 4.9550 - acc: 0.6926 - val_loss: 9.0664 - val_acc: 0.4375 Epoch 6/10 283/283 [==============================] - 0s 711us/step - loss: 4.9550 - acc: 0.6926 - val_loss: 9.0664 - val_acc: 0.4375 Epoch 7/10 283/283 [==============================] - 0s 707us/step - loss: 4.9550 - acc: 0.6926 - val_loss: 9.0664 - val_acc: 0.4375 Epoch 8/10 283/283 [==============================] - 0s 708us/step - loss: 4.9550 - acc: 0.6926 - val_loss: 9.0664 - val_acc: 0.4375 Epoch 9/10 283/283 [==============================] - 0s 703us/step - loss: 4.9550 - acc: 0.6926 - val_loss: 9.0664 - val_acc: 0.4375 Epoch 10/10 283/283 [==============================] - 0s 7…
tagged with: deep-learning
has answer: http://stackoverflow.com/a/50929803
upvote count: 1
answer count: 1
downvote count: 1
tagged with: keras
favorite count: 0
has comment: http://stackoverflow.com/comment/88828388
tagged with: python
linked to: http://stackoverflow.com/q/46247619

http://stackoverflow.com/q/50937075
upvote count: 4
score: 3
has answer: http://stackoverflow.com/a/50937154
tagged with: pytest
has comment: http://stackoverflow.com/comment/88872750
type: Question
has comment: http://stackoverflow.com/comment/104453632
answer count: 2
downvote count: 1
has title: Possible to skip a test depending on fixture value?
has answer: http://stackoverflow.com/a/59111261
favorite count: 0
type: UnansweredQuestion
has body: I have a lot of tests broken into many different files. In my conftest.py I have something like this: @pytest.fixture(scope="session", params=["foo", "bar", "baz"]) def special_param(request): return request.param While the majority of the tests work with all values, some only work with foo and baz. This means I have this in several of my tests: def test_example(special_param): if special_param == "bar": pytest.skip("Test doesn't work with bar") I find this a little ugly and was hoping for a better way to do it. Is there anyway to use the skip decorator to achieve this? If not, is it possible to right my own decorator that can do this?
tagged with: python

http://stackoverflow.com/comment/89449475
score: 0
type: AnswerComment
type: Comment
has text: Sorry for the delay : Thank you very very very much! I managed to implement it just perfect! master's thesis saved!
comment on: http://stackoverflow.com/a/51000051

http://stackoverflow.com/q/51000165
has body: I'm trying to create blocks for a platform game with pygame I'm working on, but can't figure out how to do it. I tried making it so that you could easily just write a "B" in the level list to create a block and in that way build the game's structure. So what I'm basically wondering is how do you find each B:s x and y coordinates, put those in a list and get that to show up on the screen. I have already gotten the player to work how I want it to, so the blocks are the main missing piece now. The code for the platforms(aka blocks) is shown below: class Platform(pygame.sprite.Sprite): def __init__(self, x, y): pygame.sprite.Sprite.__init__(self) self.image = Surface((25, 25)) self.image.fill(red) self.rect = self.image.get_rect() def update(self): x = y = 0 platforms = [] level = [ "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB", "B B", "B B", "B BBBB B", "B B", "B BBBB B", "B B", "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB",] for row in level: for colum in row: if colum == "B": Block = x = y platforms.append(Block) all_sprites.add(Block) x += 25 y += 25 After all of the code that is shown above I say: platform = Platform() all_sprites.add(platform) #all_sprites is the group I made for all sprites And then in the game's main while loop I wrote: all_sprites.update() Any help or other ideas would be greatly appreciated. If you have any links to someone who has done a similar thing that would also be great.
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51000544
downvote count: 0
score: 1
favorite count: 0
type: Question
has title: How to add "blocks" to a platform game in Python using pygame?
tagged with: python
tagged with: pygame
upvote count: 1
has comment: http://stackoverflow.com/comment/88994408
answer count: 1

http://stackoverflow.com/comment/88909486
has text: Typically one line is as follows: CD.FW.003121|CF|USD|FO|OBROTFB|20170929|SEP17|20170102|171500|515.239644335|515.239644335|515.239644335|Source|Passed
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50955265
type: Comment

http://stackoverflow.com/q/50950574
answer count: 2
has comment: http://stackoverflow.com/comment/88907014
downvote count: 0
has answer: http://stackoverflow.com/a/50950747
favorite count: 0
has comment: http://stackoverflow.com/comment/88903971
possible better answer: http://stackoverflow.com/a/50950996
has answer: http://stackoverflow.com/a/50950996
has comment: http://stackoverflow.com/comment/88898924
has comment: http://stackoverflow.com/comment/88899422
has comment: http://stackoverflow.com/comment/88898918
tagged with: python
has title: Class Variable NameError not defined python
has comment: http://stackoverflow.com/comment/88904403
accepted answer: http://stackoverflow.com/a/50950747
tagged with: class-variables
upvote count: 1
type: Question
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/88901550
has body: In this example, it's working hotels as a class variable no NameError class Hotel(): """"""""" this is hotel class file """ hotels = [] def __init__(self,number,hotel_name,city,total_number,empty_rooms): self.number = number self.hotel_name = hotel_name self.city = city self.total_number = total_number self.empty_rooms = empty_rooms Hotel.hotels.append([number,hotel_name,city,total_number,empty_rooms]) def list_hotels_in_city(self,city): for i in hotels: if city in i: print "In ",city,": ",i[1],"hotel, available rooms :",i[4] In the following example its not working from twilio.rest import Client class Notifications(): customers = [] def __init__(self,customer_name,number,message): self.customer_name = customer_name self.number = number self.message = message Notifications.customers.append([customer_name,number,message]) def send_text_message(self,customer_name): for i in customers: print "triggeredb" inst = Notifications("ahmed","+00000000000","messagesample") print "instance : ",inst.customers inst.send_text_message("ahmed") NameError: global name 'customers' is not defined Update for first example nothing called to show error but issue solved for second example Thanks Tom Dalton , scharette and James

dialogflow-es
tag name: dialogflow-es
tags question: http://stackoverflow.com/q/50905320
tags question: http://stackoverflow.com/q/50903189
type: Tag
tags question: http://stackoverflow.com/q/50921502

http://stackoverflow.com/comment/88970069
type: AnswerComment
comment on: http://stackoverflow.com/a/50986578
type: Comment
score: 1
has text: @Kwikerr in this case the augmented assignment operator is overriden to also execute a `list.extend()` operation and return the LHS list - so you actually have both a rebind operation (that by itself doesn't change `L`) AND a mutation of the list `i` is pointing to. Replace `i += [1]` with `i.extend([1])` and you'll have the real behaviour. If you really want to understand python's "variables" you have to totally forget the traditional C/Pascal/etc definition of "variable" (where a variable is a memory address) and think in terms of "names" and "bindings".

http://stackoverflow.com/comment/88778971
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50888651
has text: No, you can't pass a secondary key to `get`. But you could do something like `d = dicto.get('user')` `if d: loc = d['location']`, assuming that if `dicto['user']` exists it always has a 'location' key.

http://stackoverflow.com/q/50898521
duplicate of: http://stackoverflow.com/q/40811628
has comment: http://stackoverflow.com/comment/88796950
type: Question
tagged with: matplotlib
duplicate of: http://stackoverflow.com/q/45306099
linked to: http://stackoverflow.com/q/43463431
tagged with: python-2.7
linked to: http://stackoverflow.com/q/32185411
score: 0
has body: I want to plot a graph using pyplot with different spacing for different intervals. I want to zoom in specific parts of the interval without another floating box. For example: Consider the graph and scaling as below: | 30- | 20- - - - - | / 10- / | / 2- / | / 1- / |- - - 0-,__,__,___,___,___, 0 1 2 20 30 40 I have tried looking up online but I am unable to find the resource. It will be really great if someone can help me.
linked to: http://stackoverflow.com/q/40811628
has comment: http://stackoverflow.com/comment/88797485
linked to: http://stackoverflow.com/q/45306099
type: UnansweredQuestion
has title: Different Spacing for same axes in Matplotlib
has comment: http://stackoverflow.com/comment/88797519
tagged with: python
answer count: 0
duplicate of: http://stackoverflow.com/q/43463431
tagged with: plot

http://stackoverflow.com/comment/88798769
type: Comment
has text: I've briefly described the problem.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50899233

http://stackoverflow.com/a/50965480
upvote count: 1
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/50964011
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/50964011
has body: Since your question is unclear whether you want to remove brackets after collecting in list or before collecting and other users already answered for after, I will answer for while data is still a rdd. It is pretty straight forward, spams = spams.map(lambda x:x[0]) print spams.take(3) This will remove the inner "brackets".

http://stackoverflow.com/comment/88795803
comment on: http://stackoverflow.com/a/50896545
score: 0
type: AnswerComment
has text: i actually found the solution(just a simple one line arithmetic formula using sum()), but i really wanted to know the solution , if 'n' is not fixed (or not given) !!!!
type: Comment

http://stackoverflow.com/a/50924125
downvote count: 0
type: Answer
has body: So your code is nearly there but there are three things missing: You need to use a 'polar' projection. This tells pyplot that you are using polar co-ordinates, so it will create a circular plot like in the image you have linked. Your theta array needs to be in radians, not degrees. Your arrays containing values for r and theta need to be 2D, not 1D. I have created a working version of your code and included it below: import matplotlib.pyplot as plt import numpy as np # number of bins in r and theta dimensions N_bins_theta = 36 N_bins_r = 10 # limits in r dimension rmin = 6 rmax = 12 # setting up 1D arrays in r and theta r = np.linspace(rmin, rmax, N_bins_r) theta = np.linspace(0, 2*np.pi, N_bins_theta) # N.B. radians not degrees # 'gridding' the 1D arrays into 2D arrays so they can be used by pcolor theta, r = np.meshgrid(theta, r) # generating random data; note shape of array C = np.random.rand(N_bins_r, N_bins_theta) # setting up 'polar' projection and plotting ax = plt.subplot(111, projection='polar') plt.pcolor(theta, r, C) plt.show() Here is the image output:
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/50921345

http://stackoverflow.com/q/50994346
has comment: http://stackoverflow.com/comment/88991291
has comment: http://stackoverflow.com/comment/88983629
score: -1
type: Question
tagged with: python-2.7
answer count: 1
has body: I need to run this bash command using subprocess through some substitution. server.txt has list of server name, this script has to run on multiple servers and output should be redirected to a file as in the bash command. Pls help. BASH Command: ssh server1 "cat /home/pxh07/python/list| tail -n +2" #!/usr/bin/env python import subprocess import commands import sys import os from subprocess import Popen, PIPE, STDOUT cmd = "cat /home/user1/python/list| tail -n +2 &gt; data.out" SSH = "ssh " fh = open('server.txt') for server_name in fh: subprocess.call(SSH + server_name + cmd,shell=True) fh.close()
has comment: http://stackoverflow.com/comment/88983584
has comment: http://stackoverflow.com/comment/88985282
has answer: http://stackoverflow.com/a/50995511
downvote count: 1
has comment: http://stackoverflow.com/comment/88983665
tagged with: python
favorite count: 0
has title: Variable substitution in subprocess call
upvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/88793608
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50896869
has text: You should replace `res = requests.get(link)` by `res = requests.get(url)`. It currently uses the global link instead of the url provided as argument
type: Comment

http://stackoverflow.com/a/50960136
has comment: http://stackoverflow.com/comment/88917960
has comment: http://stackoverflow.com/comment/88917806
answers question: http://stackoverflow.com/q/50959180
has body: We can do this quite fast using np.lexsort and some masking def lex(arr): tmp = arr[np.lexsort(arr.T),:] tmp = tmp[np.append([True],np.any(np.diff(tmp,axis=0),1))] return tmp[np.lexsort((tmp[:, 1], tmp[:, 0]), axis=0)] L = np.array(L) lex(L) # Output: [[300. 400. ] [349.9 486.6] [350. 313.3] [450. 313.3] [450. 486.6] [500. 400. ]] Performance Functions def chrisz(arr): tmp = arr[np.lexsort(arr.T),:] tmp = tmp[np.append([True],np.any(np.diff(tmp,axis=0),1))] return tmp[np.lexsort((tmp[:, 1], tmp[:, 0]), axis=0)] def pp(data): return [k for k, g in itertools.groupby(sorted(data))] def gazer(data): return np.unique(data, axis=0) def wim(L): return sorted({tuple(x): x for x in L}.values()) def jpp(L): return sorted(unique(L, key=tuple)) Setup res = pd.DataFrame( index=['chrisz', 'pp', 'gazer', 'wim', 'jpp'], columns=[10, 50, 100, 500, 1000, 5000, 10000, 50000, 100000], dtype=float ) for f in res.index: for c in res.columns: npL = np.random.randint(1,1000,(c,2)) + np.random.choice(np.random.random(1000), (c, 2)) L = npL.tolist() stmt = '{}(npL)'.format(f) if f in {'chrisz', 'gazer'} else '{}(L)'.format(f) setp = 'from __main__ import L, npL, {}'.format(f) res.at[f, c] = timeit(stmt, setp, number=50) ax = res.div(res.min()).T.plot(loglog=True) ax.set_xlabel("N"); ax.set_ylabel("time (relative)"); plt.show() Validation npL = np.random.randint(1,1000,(100000,2)) + np.random.choice(np.random.random(1000), (100000, 2)) L = npL.tolist() chrisz(npL).tolist() == pp(L) == gazer(npL).tolist() == wim(L) == jpp(L) True
upvote count: 2
downvote count: 0
type: Answer
score: 2

http://stackoverflow.com/comment/117283174
has text: UPDATE: If you have Linux/Mac: Please open the /usr/local/bin/mysql_config.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50975651
type: AnswerComment

http://stackoverflow.com/a/50901551
has body: Here's one possible solution using a nested for loop: # Iterate over all GeneSet files for f in *.GeneSet; do # Figure out the cell type by removing "Genes.GeneSet" from the end of the filename cell_type=${f%Genes.GeneSet} # Process the file echo "Processing file: $f with cell type $cell_type" for i in {1..22}; do python make_annot.py --gene-set-file "$f" --bimfile ../../1000G_EUR_Phase3_plink/1000G.EUR.QC.${i}.bim --annot-file ${cell_type}.${i}.annot.gz done done
type: Answer
has comment: http://stackoverflow.com/comment/88836523
accepted answer of: http://stackoverflow.com/q/50901491
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/88836353
answers question: http://stackoverflow.com/q/50901491
has comment: http://stackoverflow.com/comment/88822346
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/88727015
has text: @Prune Ok, I'll get my MCVE code and edit the post. Thanks
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50861659
score: 0

http://stackoverflow.com/comment/88837460
has text: I think it is only recognizing the if score_earned>100 because that is the only time my program is correct. Otherwise, it just sets score_earned=0
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50918660

http://stackoverflow.com/q/50923672
answer count: 1
has comment: http://stackoverflow.com/comment/88846565
tagged with: shell
has answer: http://stackoverflow.com/a/50923894
type: UnansweredQuestion
tagged with: python
has body: My requirement is to delete the previous day directory and create a new directory in the format like as given in the below screen. We generally make a directory in a below format taking into account the day and the date. For example: TP1_&lt;TODAY_DAY&gt;_&lt;TODAY_DATE&gt; TP1_TUE_19JUN2018. How can this be achieved?
has title: Shell Script to Delete Selected Directory based on Changing date
type: Question
score: 0

http://stackoverflow.com/q/50967332
score: 0
has body: queryset (views) def coin_profile(request, user, coin): test = Transaction.objects.filter(user = user, coin = coin) I call coin_profile by clicking a link. Urls: urlpatterns = [ path('', views.index, name = 'index'), path('add_transaction/', views.add_transaction, name = 'add_transaction'), path('<user>/<coin>', views.coin_profile, name = 'coin_profile'), ] links in template: {% for coin in portfolio_list %} {{coin.coin}} {{coin.amount}} {{coin.price}} {{coin.value}} {{coin.daily_change}}% Sell Delete {% endfor %} model field class Transaction(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE) Returns this error. That means that the queryset is expecting an integer when I use user = user, but why? And how can I pass my user names to this query?
tagged with: python
possible better answer: http://stackoverflow.com/a/50967576
tagged with: django
accepted answer: http://stackoverflow.com/a/50967446
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50967446
has comment: http://stackoverflow.com/comment/88931251
has title: Django, invalid literal for int() with base 10: 'user'
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/50967576

http://stackoverflow.com/a/50991820
answers question: http://stackoverflow.com/q/50991736
upvote count: 2
has body: All you wanna do is to change the zeros in second array to items in same index in first array. You can do the following: mask = arr2 == 0 arr2[mask] = arr1[mask] Demo: In [7]: arr1 = np.array([[0,9],[2,0]]) In [8]: arr2 = np.array([[0,0],[2,2]]) In [9]: mask = arr2 == 0 In [10]: arr2[mask] = arr1[mask] In [11]: arr2 Out[11]: array([[0, 9], [2, 2]])
has comment: http://stackoverflow.com/comment/88978310
has comment: http://stackoverflow.com/comment/88978348
score: 2
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50991736

http://stackoverflow.com/comment/88800973
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50899417
has text: Don't close the browser in your script.

http://stackoverflow.com/q/51003567
has title: Tkinter button that shows status
upvote count: 2
favorite count: 0
tagged with: python-3.x
tagged with: tkinter
answer count: 0
type: UnansweredQuestion
tagged with: arduino
tagged with: python
score: 2
downvote count: 0
has body: My vision was to build a mailbox that counts the letters and determines if the mailbox is open or not. I have a Python GUI connected with an Arduino and a wifi shield. The mailbox can already count how many times a letter was dropped into the mailbox, but I need a button or an entry field that checks whether my mailbox is open. The Arduino program for the check whether my mailbox is open prints X &amp; Y. How do I install a button that checks if there is a X or a Y? Here is my code: import tkinter as tk import socket as so class Arduino(object): def __init__(self, window, host, port, on_received): self.window= window self.on_received= on_received # Open socket and connect to the Arduino self.socket= so.socket() self.socket.connect((host, port)) self.socket.setblocking(False) self.rd_buff= bytes() self._periodic_socket_check() def send_command(self, command): 'Send a message to the Arduino' self.socket.send(command.encode('utf-8') + b'\n') def close(self): 'Cleanly close the connection' self.socket.close() self.window.after_cancel(self.after_event) def _periodic_socket_check(self): try: msg= self.socket.recv(1024) if not msg: raise(IOError('Connection closed')) self.rd_buff+= msg except so.error: # In non-blocking mode an exception is thrown # whenever no data is available. # Which error is OS-dependant so we have to catch # the generic socket.error exception. pass while b'\n' in self.rd_buff: line, self.rd_buff= self.rd_buff.split(b'\n') line= line.decode('utf-8').strip() self.on_received(line) # Tkinter should call the function again # in 100ms self.after_event= self.window.after( 100, self._periodic_socket_check ) class ResetButton(object): def __init__(self, window, arduino): self.button= tk.Button( window, text='Reset', fg="red", command= self.on_pressed ) self.button.pack() self.arduino= arduino self.set_state(False) def set_state(self, state): if state: self.arduino.send_command('on') self.state= True else: self.arduino.send_command('off') self.state= False de…
type: Question

http://stackoverflow.com/q/50882838
type: AnsweredQuestion
score: 3
has title: Python VADER lexicon Structure for sentiment analysis
upvote count: 3
has answer: http://stackoverflow.com/a/50892404
type: Question
answer count: 2
tagged with: nltk
downvote count: 0
tagged with: lexicon
accepted answer: http://stackoverflow.com/a/50892404
has answer: http://stackoverflow.com/a/54122776
favorite count: 0
possible better answer: http://stackoverflow.com/a/54122776
tagged with: vader
tagged with: python
has body: I am using the VADER sentiment lexicon in Python's nltk library to analyze text sentiment. This lexicon does not suit my domain well, and so I wanted to add my own sentiment scores to various words. So, I got my hands on the lexicon text file (vader_lexicon.txt) to do just that. However, I do not understand the architecture of this file well. For example, a word like obliterate will have the following data in the text file: obliterate -2.9 0.83066 [-3, -4, -3, -3, -3, -3, -2, -1, -4, -3] Clearly the -2.9 is the average of sentiment scores in the list. But what does the 0.83066 represent? Thanks!

http://stackoverflow.com/comment/88841688
type: Comment
comment on: http://stackoverflow.com/a/50915214
type: AnswerComment
score: 0
has text: `single insert statement and commit`, millions of row with `copy` import, you will take almost same time, Adding to what @rvd said, you could even parallel, using `menifest` file option.

size
type: Tag
tags question: http://stackoverflow.com/q/50875019
tag name: size

http://stackoverflow.com/comment/88782041
comment on: http://stackoverflow.com/q/50890500
type: Comment
type: QuestionComment
has text: counter & encoding, they both're integers?
score: 0

http://stackoverflow.com/q/50935345
has answer: http://stackoverflow.com/a/51027227
type: Question
accepted answer: http://stackoverflow.com/a/51027227
has answer: http://stackoverflow.com/a/77058113
has body: How does torch.nn.Parameter() work?
possible better answer: http://stackoverflow.com/a/57304186
tagged with: class
answer count: 3
downvote count: 1
score: 133
favorite count: 0
tagged with: pytorch
has answer: http://stackoverflow.com/a/57304186
upvote count: 134
tagged with: python
type: AnsweredQuestion
has title: Understanding `torch.nn.Parameter()`

http://stackoverflow.com/q/50926669
score: 0
tagged with: pyqt5
type: Question
tagged with: for-loop
has body: I have a code that display Items in a QlistWidget that refer to a file path once the user select any file the system return the last Item only. What i need is to return the selected item only. so that the user will be able to select any item no matter where it exist. example : C:\Users\test\Desktop\New Microsoft Word Document.docx row =>0 C:\Users\test\Desktop\test_arabic.docx row =>1 In the function below i am trying to iterate over the items in the QlistWidget Get the full path of the file (from root) Split the path Add the rest of the path based on the index but this did not work because sometimes the displayed files in the list are from different folder therefor have different path. code: def FileListSelected(self): # Function to select the desired file from the list in the left pane ListIterator=range(self.listWidgetPDFlist.count()) try: index = 0 for index in ListIterator: p = pathlib.Path(self.fullPath) print("this is P==&gt;{}".format(p)) oneDir = os.path.join(*p.parts[:-2]) print("this is oneDir==&gt;{}".format(oneDir)) Item= oneDir + "\\" + self.listWidgetPDFlist.selectedItems()[index].text() print("this is the cuurent Item =={}".format(Item)) ppp=os.path.join(os.path.expanduser("~"), Item) print("this is ppp==&gt;{}".format(ppp)) print("===============================================") index =+1 print("index =&gt;".format(index)) self.mouseHover() return ppp except Exception as e: print(e)
answer count: 1
has title: how to return the selected Item in the list and not the last Item in the list using Pyqt5 in python
tagged with: qlistwidget
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50931229
tagged with: list

http://stackoverflow.com/a/51012645
downvote count: 0
type: Answer
score: 1
upvote count: 1
has body: You have to install anaconda package like following: conda create -n myEnv anaconda when you add anaconda to your command you tell conda to install all package thats come with anaconda
answers question: http://stackoverflow.com/q/51010361
has comment: http://stackoverflow.com/comment/94933791

http://stackoverflow.com/q/50883655
tagged with: gpio
upvote count: 1
score: 1
type: Question
tagged with: led
downvote count: 0
tagged with: raspberry-pi3
has title: Controlling RGB LED Light with Raspberry Pi and Python
favorite count: 0
has body: I bought this LED light on ebay. The model is CJMCU-KZQ. My question is, how can I get it to work on a raspberry pi and python? I have looked everywhere but cannot find any documentation for it. Also, keep in mind that this light uses SDA/SCL I2C bus.
has answer: http://stackoverflow.com/a/50884344
answer count: 1
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/q/50898870
has answer: http://stackoverflow.com/a/50909098
accepted answer: http://stackoverflow.com/a/50909098
type: Question
upvote count: 2
answer count: 1
has body: I am looking for an alternative to redis that has pub sub persisted messages. So I can get the last message published through the service. And a key value store. There are so many services out there I'm not sure which has these functions. I'm using it with python.
favorite count: 0
tagged with: redis
has title: Alternative to redis with pub sub persisted messages and key value store?
tagged with: python
score: 2
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/comment/96802589
has text: Removing pytest-allure-adaptor module solves the problem. Thanks for the justification.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50936600

http://stackoverflow.com/comment/88903776
comment on: http://stackoverflow.com/q/50952675
score: 0
type: Comment
type: QuestionComment
has text: not really. i will check it

http://stackoverflow.com/comment/88806320
comment on: http://stackoverflow.com/a/50892244
type: AnswerComment
has text: I tried it out but then I can't stream dates outside the last 30 days in the past and 5 days in the future relative to the current date. All the tables are partitioned by date. And I have dates that go back to years ago.
score: 0
type: Comment

http://stackoverflow.com/comment/106720808
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50917584
type: AnswerComment
has text: Also, what version of OpenCV are you using?

http://stackoverflow.com/comment/88726627
type: Comment
type: QuestionComment
has text: @Srinidhi-patil I have an answer... If you care to repost the question with all of your edits I can answer it
comment on: http://stackoverflow.com/q/50861380
score: 0

http://stackoverflow.com/a/50855386
score: 1
answers question: http://stackoverflow.com/q/50855188
accepted answer of: http://stackoverflow.com/q/50855188
upvote count: 1
type: AcceptedAnswer
type: Answer
downvote count: 0
has body: In opencv image[i] is is row of the image. So in first case instead of ... image[i][j] you'd, probably, want ... image[j][i] Otherwise you, obviously, get an error as you index rows (of range 0-1023) with columns indices (of range 0-1279).

http://stackoverflow.com/a/50939106
answers question: http://stackoverflow.com/q/50939068
has comment: http://stackoverflow.com/comment/88891602
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/88876396
score: 1
has body: Your replace is backwards: Instead of: r = r.replace("true", "True") Try: r = r.replace("True", "true")
downvote count: 0

http://stackoverflow.com/comment/88898732
comment on: http://stackoverflow.com/q/50950426
type: Comment
score: 1
has text: Could you have not chosen a more 'child friendly' word for your example? SO is for all people of all ages and backgrounds you know
type: QuestionComment

http://stackoverflow.com/q/50983655
score: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/50983726
type: AnsweredQuestion
favorite count: 0
has body: I'm a beginner. My system is win10 Pro,and I use python3.X. I use this code to test function "os.path.join()" and "os.path.dirname()". import os print(os.path.join(os.path.dirname(__file__), "dateConfig.ini")) The output is: E:/test_opencv\dateConfig.ini I found os.path.join() use "/",but os.path.dirname() use "\",why? If I want to use the same separator,all is '/' or '\',what should I do?
tagged with: python-3.x
has title: Why "os.path.join" and "os.path.dirname(__file__)" return different separator?
type: Question
upvote count: 2
tagged with: python
answer count: 1
has answer: http://stackoverflow.com/a/50983726

http://stackoverflow.com/q/50971042
tagged with: tornado
type: Question
has body: I'm trying to make a long async http request using Python Tornado AsyncHTTPClient: url = 'http://do_something_for_more_than_20_seconds.com/ client = httpclient.AsyncHTTPClient() response = await client.fetch(url, method='GET') But, after 20 seconds, I get this error: tornado.httpclient.HTTPError: HTTP 599: Timeout during request How can I configure the client in order to allow long requests? I have tried to add this configuration row after the initialization of the client, but still it doesn't work: client.configure(None, defaults=dict(connect_timeout=60, request_timeout=120))
tagged with: http-error
upvote count: 1
answer count: 1
tagged with: asynchronous
has answer: http://stackoverflow.com/a/50971420
favorite count: 0
accepted answer: http://stackoverflow.com/a/50971420
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
has title: tornado.httpclient.HTTPError: HTTP 599: Timeout during request

http://stackoverflow.com/comment/96172101
has text: Do you mean if your X is not sampled propperly ? Like sparse x values ? Then you might have reconstruction problems ( See Nyquist Theorem) . But that is independent of the (or any) integration solution. Thus a different issue .It also does not to see the issue with the shown plot.
type: AnswerComment
comment on: http://stackoverflow.com/a/50866635
score: 0
type: Comment

http://stackoverflow.com/q/50980660
type: AnsweredQuestion
upvote count: 9
score: 6
has title: difference between URL and path in Django?
answer count: 3
has answer: http://stackoverflow.com/a/50980955
has answer: http://stackoverflow.com/a/50980760
favorite count: 0
has comment: http://stackoverflow.com/comment/88957082
has comment: http://stackoverflow.com/comment/88957372
has comment: http://stackoverflow.com/comment/88957263
tagged with: python
possible better answer: http://stackoverflow.com/a/69890081
has body: I just started learning Django, and not able to understand that what is the actual difference between URL and path in Django.
has answer: http://stackoverflow.com/a/69890081
accepted answer: http://stackoverflow.com/a/50980955
downvote count: 3
has comment: http://stackoverflow.com/comment/88956996
tagged with: django
has comment: http://stackoverflow.com/comment/88956887
type: Question
has comment: http://stackoverflow.com/comment/88997985

http://stackoverflow.com/q/50932804
has body: Need the most simplest and easiest way to do the following work i have a file like this containing product name with prices. blackberry 23 100 Black shirt with hoody (small) 4 800 Pastel Paint (red) (oil) 2 600 how can i format these into a list like this lst=[['blackberry' ,23 ,100],['Black shirt with hoody (small)' ,4 ,800],['Pastel Paint (red) (oil)' ,2 ,600]] I am trying with split its working when the product name only contain one word for example Blackberry but if more words include it don't work anymore as i am splitting with space.
has answer: http://stackoverflow.com/a/50932874
tagged with: python
has answer: http://stackoverflow.com/a/50932961
has title: Formatting file into list with price , product name and quantity
upvote count: 1
has answer: http://stackoverflow.com/a/50932910
accepted answer: http://stackoverflow.com/a/50932874
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50932884
has answer: http://stackoverflow.com/a/50933099
score: 1
has answer: http://stackoverflow.com/a/50932884
answer count: 6
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/50932896
tagged with: string
favorite count: 0

http://stackoverflow.com/q/50982028
tagged with: pytest
accepted answer: http://stackoverflow.com/a/50988084
tagged with: unit-testing
has comment: http://stackoverflow.com/comment/88959914
type: Question
score: 5
tagged with: mocking
has title: Mocking functions retrieved from __getattr__ method
upvote count: 5
has comment: http://stackoverflow.com/comment/88960037
has answer: http://stackoverflow.com/a/50988084
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88959570
has comment: http://stackoverflow.com/comment/88959392
has body: I'm automating some repository operations and I'm using GitPython for this job. Let's simplify things and assume I'd like to assert whether my function called pull method on the repository. Code below: from pytest_mock import MockFixture from git import Git, Repo repo = Repo('/Users/Jatimir/path/to/repo') def pull() -&gt; None: repo.git.pull() However, I noticed that Git class is somewhat special and doesn't implement pull. Instead, it "delegates" all the traffic to __getattr__ which uses another method that does the job. def __getattr__(self, name): ... return lambda *args, **kwargs: self._call_process(name, *args, **kwargs) My question is how to approach testing this? I'm using pytest with pytest-mock that provides a mocker fixture and here are my attempts: def test_pull1(mocker: MockFixture) -&gt; None: pull_mock = mocker.MagicMock(name='pull') getattr_mock = mocker.MagicMock(name='__getattr__', return_value=pull_mock) mocker.patch.object(Git, '__getattr__', getattr_mock) pull() pull_mock.assert_called_once_with() def test_pull2(mocker: MockFixture) -&gt; None: pull_mock = mocker.Mock(name='pull') def __getattr__(self, name): if name == 'pull': return pull_mock mocker.patch.object(Git, '__getattr__', __getattr__) pull() pull_mock.assert_called_once_with() They both work, but I feel like there is a better way and maybe my approach to testing this is wrong.
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/50965175
has title: How to convert an image (get from request.FILES) to byte array in python?
tagged with: io
tagged with: python
linked to: http://stackoverflow.com/q/36417049
has comment: http://stackoverflow.com/comment/88927911
downvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51018813
tagged with: file
has comment: http://stackoverflow.com/comment/88955910
has comment: http://stackoverflow.com/comment/88927898
score: 1
type: Question
has body: Suppose I have a variable "profile_image" of image file type. I have created the variable like below: profile_image = request.FILES.get('profile_image', False) Now I need to convert this image variable to bytes array. How can I do this without saving it to the local drive? I found that file open/read do not work here. I tried like below: with open(profile_image.name, "rb") as imageFile: file_stream = imageFile.read() Please help me. By the way, by converting into bytes array I want to save it to google cloud. Thank you.
has comment: http://stackoverflow.com/comment/88955895
upvote count: 1
linked to: http://stackoverflow.com/q/22351254
answer count: 1
favorite count: 0

task
type: Tag
tags question: http://stackoverflow.com/q/51006521
tag name: task

http://stackoverflow.com/comment/88813910
comment on: http://stackoverflow.com/q/50907015
score: 1
has text: You are getting the error because you only have one dict in `data2` try: `data2=[{}, {}]`
type: QuestionComment
type: Comment

http://stackoverflow.com/q/50871651
score: 1
tagged with: amazon-sagemaker
favorite count: 0
type: Question
tagged with: python
answer count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/50882255
has body: I am trying to invoke an Amazon Sagemaker Endpoint from a local python notebook. This is the code I am using. import boto3 aws_access_key_id = '...............' aws_secret_access_key = '................' tkn = '..........' region_name = '............' amz = boto3.client('sagemaker-runtime', aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, aws_session_token=tkn, region_name=region_name) response = amz.invoke_endpoint( EndpointName='mymodel', Body=b'bytes' ) However, this doesn't work. Do I have to specify something else in Body ?
has title: Python Notebook Invoke Endpoint Sagemaker from Local
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51086736
downvote count: 0

http://stackoverflow.com/q/50976947
accepted answer: http://stackoverflow.com/a/51049076
has body: I have a 2D numpy array that I am searching by column for groups of 1s, which is fairly simple, this effectively a matrix of 1s and 0s: groups = [list(c) for c in mit.consecutive_groups((mit.locate(data[:, 2])))] Here it is only looking at column #3, I want to get out of it a dictionary of values summed over the whole array by column. I want to do this such that I have a dictionary that shows the number of occurrences of a given group length. I'm having trouble figuring out how to do that over even a single column, let alone getting that same value for all columns combined, skipping the first column. I can use this snippet to get key-value pairs of index a group starts on and versus it's length. But what I want to get is a key of group length with a value of the total number of occurences. d = {group[0]: len(group) for group in groups} I can't think of anyway of rewriting this, with or without conditionals that will get me it for even a single column, let alone modifying my initial line of code to allow me to do it over the entire matrix. Here's an example of the input data: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 10 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 20 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 30 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 40 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 50 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 60 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 70 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 80 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 90 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 Ideally I need to also be able to tell if it was at the end of the dataset, as it would have been cut off. So a combination of the method I've been using which doesn't give quite what I need and some other similar method might be the best approach. I simply cannot find a way, been trying all weekend. Thanks.
score: 0
has comment: http://stackoverflow.com/comment/89043131
tagged with: grouping
answer count: 1
tagged with: iteration
tagged with: python
has answer: http://stackoverflow.com/a/51049076
type: AnsweredQuestion
has title: Iterate over Python 2D array grouping columns data for total
has comment: http://stackoverflow.com/comment/88950422
type: Question
tagged with: numpy
tagged with: arrays

http://stackoverflow.com/comment/88791265
type: Comment
has text: Thanks a lot for this instruction. I'll try the method.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50889604

http://stackoverflow.com/a/50891566
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/50891539
downvote count: 0
has body: You can create a connection like this: # create an INET, STREAMing socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # now connect to the web server on port 80 - the normal http port s.connect(("www.python.org", 80)) Also you can get more information in the documentation.

http://stackoverflow.com/a/50979265
type: Answer
answers question: http://stackoverflow.com/q/50953718
has body: This problem was from not initializing with the Google SDK, I was trying to initialize with GitBash and obviously the configuration wasn't set upt properly. The next step was to initialize the app with a requirements.txt file. pip freeze &gt; requirements.txt After that, only include the files needed for the app within the requirements.txt file, and initialize the app by adding: --requirements_file requirements.txt Also, it was necessary to change from firebase_admin==2.11.0 to firebase_admin==2.8.0 as this was bringing up an error.
score: 5
type: AcceptedAnswer
downvote count: 0
upvote count: 5
accepted answer of: http://stackoverflow.com/q/50953718

http://stackoverflow.com/q/50999712
downvote count: 0
tagged with: python
answer count: 4
favorite count: 0
has answer: http://stackoverflow.com/a/51013976
tagged with: autokey
has answer: http://stackoverflow.com/a/50999765
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51107176
upvote count: 1
has answer: http://stackoverflow.com/a/51001973
has body: script 2 doesn't work because variable CODE is forgotten after script 1 is executed. script 1 (hotkey is set to 1) code = 123 script 2 (hotkey is set to 2) if code == 123: keyboard.send_key("G") How to make this or an analogue ? I need digits to be remembered, and then used in another script(s) with a condition like above.
score: 1
type: Question
has title: Can a script not forget variable content after script was executed ? [autokey] [python]

http://stackoverflow.com/comment/89736274
score: 2
has text: Just fixed that error in https://github.com/fabioz/Pydev/commit/090d95d89ce244f00bc8f635087725ae5c38b341 (for PyDev 6.4.4).
comment on: http://stackoverflow.com/a/50969872
type: Comment
type: AnswerComment

http://stackoverflow.com/q/51002096
has comment: http://stackoverflow.com/comment/89001546
tagged with: for-loop
answer count: 1
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/10941479
has title: Getting information from xml files - running efficiency python
tagged with: http://stackoverflow.com/tag/xml
score: 0
has comment: http://stackoverflow.com/comment/88997930
type: Question
has comment: http://stackoverflow.com/comment/88998052
has body: I have two XML files, The first XML file include list of items. The second XML file include list of review details. I need to find if review exists in the item list. For the mission I have a for loop that run on all of the items and for etch item check with another for loop if it exists in the review list (The second XML). Because this XML contain lo.ts of data its take a lot of time The question is if there another way to achieve this with more efficiency. example: for x in price.iter('Item'): # First XML with the items for z in promo.iter('Review'): # Second XML with the reviews if z.find('ItemCode').text == x.find('ItemCode').text: print True # Find the data in the review
has answer: http://stackoverflow.com/a/51002207

http://stackoverflow.com/a/50981755
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50948615
has body: I got it. Here is the query: maxMailsIds = Conversation.objects.filter(mail__receiver=user).annotate(maxId=Max('mail__id')).values_list('maxId', flat=True) items = Mail.objects.filter(id__in=maxMailsIds).order_by('-id').values('subject','message')
type: Answer
answers question: http://stackoverflow.com/q/50948615

http://stackoverflow.com/comment/88801203
score: 0
comment on: http://stackoverflow.com/a/50899698
type: Comment
has text: The question has been re-posted
type: AnswerComment

http://stackoverflow.com/q/50864868
upvote count: 2
has answer: http://stackoverflow.com/a/50865161
has comment: http://stackoverflow.com/comment/88732357
has comment: http://stackoverflow.com/comment/88732496
tagged with: object
has answer: http://stackoverflow.com/a/50865169
accepted answer: http://stackoverflow.com/a/50865014
possible better answer: http://stackoverflow.com/a/50865123
has answer: http://stackoverflow.com/a/50865123
answer count: 4
type: AnsweredQuestion
score: 2
downvote count: 0
has body: I'm writing a program to take a number of players as input from the user and add that many names to a list. Now I want to take the names that are added to the list and use them in a scoring system for each of the players in the player_list. I want to use each name to say this player has this many points. So I believe I want to use the names in the list as each an object and assign each a score. My question is, can I do this with items in a list? My code right now that works to create the list is as follows. # total_list is to be used in the next part of my code total_list = [] players_list = [] max_players = int(input(" how many players tonight? : ")) while len(players_list) &lt; max_players: players = input("First player name? : ") players_list.append(players) print("players so far : ") print(players_list) if len(players_list) == max_players: print("players are: ") print(players_list) The way my code is right now, can I use the name input to the list as an object and assign a variable called score? I think it would look like something like this: players_list[0](score) but I know that would not be the way to write it, if it is indeed possible. Please let me know if I need to clarify.
favorite count: 0
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/88732538
has answer: http://stackoverflow.com/a/50865014
has title: Python, how to use item inputed in a list and use them to be assigned another value? is it possible
tagged with: list

http://stackoverflow.com/q/50993194
accepted answer: http://stackoverflow.com/a/50993297
upvote count: 1
type: AnsweredQuestion
score: 1
tagged with: matplotlib
type: Question
downvote count: 0
favorite count: 0
has title: Python, Plot three charts in plt.subplots(2,2)?
answer count: 1
tagged with: python
has body: By using fig, ax = plt.subplots(2,2) I create a figure with four sub-plots like this what if I just want three plots in the figure? Thanks!
has answer: http://stackoverflow.com/a/50993297

http://stackoverflow.com/comment/88781165
score: 0
has text: Nice. I think another possible solution might be `pd.to_datetime(df_b['datetimecolumn'], dayfirst=True)`
comment on: http://stackoverflow.com/a/50889844
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50864404
score: 1
upvote count: 1
has body: I am using spyder to implement this example of the car-pole tunnel problem. I got the code from Reinforcement Learning. I am having problems executing the code. I have tried on both spyder and the terminal. The return error I receive is Model output "Tensor("activation_1/Identity:0", shape=(?, 16), dtype=float32)" has invalid shape. DQN expects a model that has one dimension for each action, in this case 2. How can I incorporate the installation of dqn to spyder, so that I am able to execute this code in spyder? import numpy as np import gym from keras.models import Sequential from keras.layers import Dense, Activation, Flatten from keras.optimizers import Adam from rl.agents.dqn import DQNAgent from rl.policy import EpsGreedyQPolicy from rl.memory import SequentialMemory #Set Relevant variables ENV_NAME = 'CartPole-v0' # Get the enviornment and extract the number of actions availible in the Cartpole problem env = gym.make(ENV_NAME) np.random.seed(123) env.seed(123) nb_actions = env.action_space.n #hidden layer neural network model. model = Sequential() model.add(Flatten(input_shape=(1,) + env.observation_space.shape)) model.add(Dense(16)) model.add(Activation('linear')) print(model.summary()) policy = EpsGreedyQPolicy() memory = SequentialMemory(limit=50000, window_length=1) dqn = DQNAgent(model=model, nb_actions=nb_actions, memory=memory, nb_steps_warmup=10, target_model_update=1e-2, policy=policy) dqn.compile(Adam(lr=1e-3), metrics=['mae']) #Test model dqn.test(env, nb_episodes=5, vizualize=True)ter co
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/88732459
has comment: http://stackoverflow.com/comment/88763890
has title: Executing tensorflow in spyder
tagged with: spyder
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/88732831
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88731388
answer count: 0

http://stackoverflow.com/a/50892647
score: 0
type: Answer
has body: This problem caused by the difference between python/linux and windows representing paths. I printed the folder_selected and get: C:/Users/name/Documents/Zevel You need to add the following right after calling askdirectory(): folder_selected = folder_selected.replace('/', '\\') Making the path readable for windows, and now it looks like: C:\Users\name\Documents\Zevel Of course you need call subprocess.Popen(["explorer", folder_selected]) and every thing will work.
has comment: http://stackoverflow.com/comment/88785907
answers question: http://stackoverflow.com/q/50892257

http://stackoverflow.com/q/50948061
has title: How to save or download an image that I get in a request -- Python
upvote count: 3
downvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/88893905
has body: So, I am requesting a URL that actually brings a picture, nothing else, you type the URL, click "enter" and it gets you a picture. Now, I want to save that picture into a file in a desired path by using python but I am not succeding. Can you help me? Picture_request = requests.get(Photo_URL) Where to go from there?
favorite count: 0
has comment: http://stackoverflow.com/comment/110361333
tagged with: save
linked to: http://stackoverflow.com/q/13137817
tagged with: python-requests
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/50948613
type: Question
accepted answer: http://stackoverflow.com/a/50948613
answer count: 1

dragonboard
tag name: dragonboard
tags question: http://stackoverflow.com/q/50863275
type: Tag

http://stackoverflow.com/a/50975395
upvote count: 1
type: Answer
has body: You can get a pretty clean version of this using the grouper idiom from the itertools documentation: In [42]: new_list = [{'website': d['website'], 'date': d['date'], 'headliner': headliner, 'data': list(datarow)} ...: for headliner, datarow in zip(d['headliner'], grouper(d['data'], 3))] ...: In [43]: new_list Out[43]: [{'website': 'http://www.zebrawebworks.com/zebra/bluetavern/day.cfm?&amp;year=2018&amp;month=6&amp;day=29', 'date': '2018-06-29', 'headliner': 'Delta Ringnecks', 'data': ['4:00 PM', 'FEE: $0', 'Jug Band Music']}, {'website': 'http://www.zebrawebworks.com/zebra/bluetavern/day.cfm?&amp;year=2018&amp;month=6&amp;day=29', 'date': '2018-06-29', 'headliner': 'Flathead String Band', 'data': ['8:00 PM', 'FEE: $5', 'Old Time Fiddle &amp; Banjoby some young turks!']}]
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/50975224

http://stackoverflow.com/comment/88919942
has text: The point is that if you can not open the file right here right now because sth may be still using it than you may want to come back and check again to see if you can open the file?
comment on: http://stackoverflow.com/q/50961538
score: 0
type: Comment
type: QuestionComment

swagger-ui
tag name: swagger-ui
type: Tag
tags question: http://stackoverflow.com/q/50967548

http://stackoverflow.com/a/50977199
score: 0
type: Answer
has body: A simple solution: dtmp={} for d in jsonstring["Localfiles"]: ip= d["IPAddress"][0] key= (d["FileName"],d["FileLength"]) dtmp.setdefault(key,[]).append(ip) lrslt=[ {"IPAddress":ip,"FileLength":lth,"FileName":fname} for (fname,lth),ip in dtmp.items() ] drslt={"Localfiles":lrslt} print(drslt)
answers question: http://stackoverflow.com/q/50974513

http://stackoverflow.com/q/50898042
has body: I am trying to make an kivy app for simulating simple ecosystem, with kind of interactive map, which can be zoomed and positioned by dragging by user. My first approach to achieve this was using Kivy Scatter widget, which seems to satisfy these requirements. Here's my code (to keep it simple, just gui with buttons and map on the right, with big red rectangle): from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.properties import ObjectProperty from kivy.graphics import Rectangle, Color class GUI(BoxLayout): board = ObjectProperty(None) def draw(self): with self.board.canvas: Color(1,0,0) Rectangle(pos=(0,0),size=(300,300)) class TestApp(App): def build(self): gui = GUI() gui.draw() return gui if __name__=="__main__": app = TestApp() app.run() and my .kv file: #:kivy 1.0.9 &lt;GUI&gt;: board: scatter_board orientation: 'horizontal' spacing: 30 padding: 30 BoxLayout: size_hint: 0.25, 1 orientation: 'vertical' Button: text: 'Start/Resume' Button: text: 'Stop' Scatter: id: scatter_board size_hint: 0.75,1 However, in this situation, while user drags the map over the button, it is not possible anymore to click it (it doesn't get highlighted on click). I tried: setting scatter's 'auto_bring_to_front' to False using 'index' property of both scatter and buttons' parent BoxLayout to manipulate z-index. So basically I want the 'map' not to shadow the button, but to stay below it. Is it possible to achieve this effect with Scatter? Or is it a wrong use-case of scatter, and I should change the approach? If so, do you know any similar and possibly simple ways?
upvote count: 1
answer count: 1
tagged with: user-interface
favorite count: 0
has comment: http://stackoverflow.com/comment/88803575
tagged with: python
tagged with: kivy
has title: Kivy Scatter z-index
linked to: http://stackoverflow.com/q/49800345
has answer: http://stackoverflow.com/a/62924621
downvote count: 0
type: UnansweredQuestion
score: 1
type: Question

http://stackoverflow.com/comment/88788589
comment on: http://stackoverflow.com/q/50894168
has text: `result = [1 for _ in range(rowIndex+1)]` that's unefficient all right. Make it `result = [1]*(rowIndex+1)`
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50978860
tagged with: pandas
has comment: http://stackoverflow.com/comment/88954271
downvote count: 0
has title: why value is ambigious if the logical operator syntax is correct
has comment: http://stackoverflow.com/comment/88953722
favorite count: 0
has comment: http://stackoverflow.com/comment/88953765
has comment: http://stackoverflow.com/comment/88953927
tagged with: python
linked to: http://stackoverflow.com/q/36921951
answer count: 0
type: UnansweredQuestion
score: 1
duplicate of: http://stackoverflow.com/q/36921951
upvote count: 1
has comment: http://stackoverflow.com/comment/88953754
has body: I am receiving below error message in Python after this line of code: data is the panda data frame and A, B are numbers. if((data.loc[ii]&gt;=A) &amp; (data.loc[ii]&lt;B)): labels[ii]=C Error :The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). I have read everything in the internet it says use &amp; instead of and and | instead of or, I even use the parenthesis to avoid operator precedence rule but I am wondering why I am still getting the above error since I am using correct logical operator ?. Thanks
type: Question
tagged with: numpy

http://stackoverflow.com/comment/91703601
has text: Possible duplicate of [how to avoid shell=True in subprocess](https://stackoverflow.com/questions/48100820/how-to-avoid-shell-true-in-subprocess)
comment on: http://stackoverflow.com/q/50905783
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50982068
upvote count: 18
answers question: http://stackoverflow.com/q/50981906
has comment: http://stackoverflow.com/comment/88960952
has comment: http://stackoverflow.com/comment/88969083
type: Answer
has body: Try this: import logging logger = logging.getLogger(__name__) logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)-8s %(message)s', datefmt='%a, %d %b %Y %H:%M:%S', filename='path/to/your/directory/testGene.log', filemode='w') Or import logging import os if not os.path.exists("Logs"): os.makedirs("Logs") logger = logging.getLogger(__name__) logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)-8s %(message)s', datefmt='%a, %d %b %Y %H:%M:%S', filename='Logs/testGene.log', filemode='w')
score: 17
downvote count: 1
has comment: http://stackoverflow.com/comment/88969216

http://stackoverflow.com/a/50988536
type: Answer
has body: Nice little task you've got there. See the comments in the code, hopefully you understand what's going on there: def print_calendar(days, day_of_week): """ days: number of days in the month day_of_week: integer from 0 to 6 describing the column where to start """ # first line: weekdays print(" S M T W Th F S") # it's (almost) the same as: print("{:2} {:2} {:2} {:2} {:2} {:2} {:2}".format("S", "M", "T", "W", "TH", "F", "S")) weeks = (days + day_of_week) // 7 + 1 # number of rows to print day = 1 # initialize day counter # print the calendar grid row wise for y in range(weeks): row = "" for x in range(7): if (y == 0 and x &gt;= day_of_week) or (y &gt; 0 and day &lt;= days): # only print after start of month and before end of month row += "{:2d} ".format(day) day += 1 else: # add blank part of string row += " " print(row) print_calendar(30,4) This will give you S M T W Th F S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
answers question: http://stackoverflow.com/q/50987564
score: 0

http://stackoverflow.com/q/50958938
has answer: http://stackoverflow.com/a/50959037
has comment: http://stackoverflow.com/comment/88915189
score: 0
has body: Im only 3 weeks into attempting to learn python, so im not fully sure what im doing. Im trying to make a short simple and stupid game where i use randint to give a random value in a fight between the player and computer. The health value keeps looping back to the original value and i cant seem to figure out why... Been searching for days. I put a break in to stop the fight but it doesnt have either 'health' reach zero. Thanks for any help. from random import randint n = input() print ('Welcome, ', n, ' Choose your weapon: Sword, Axe, or Mace.') b = input() if b == {'Sword'}: print ('Good Choice ', (n), ' the Sword will keep you safe.') elif b == {'Axe'}: print ('Good Choice ', (n), ' the Axe will do some damage.') elif b == {'Mace'}: print ('Probably a bad choice ', (n), ' the mace is heavy and slow but may protect you.') print ('The Knight Approaches! ', (n), ', Get your', (b),' and get ready!') player = 50 knight = 50 battle = True while player &gt;= 0 or knight &gt;= 0: if b == 'Sword': k2 = (knight - randint(3,4)) p2 = (player - randint(2,6)) print ('You have struck the knight! His health is now', k2) print ('He has hit you as well! Your health is now', p2) elif b == 'Axe': print ('You have struck the knight! His health is now', knight - randint(2,6)) print ('He has hit you as well! Your health is now', player - randint(3,4)) elif b == 'Mace': print ('You have struck the knight! His health is now', knight - randint(0,7)) print ('He has hit you as well! Your health is now', player - randint(2,6)) if player &lt;= 0: print ('You have died...') elif knight &lt;= 0: print ('You have won!') break print ('Good Game')
has answer: http://stackoverflow.com/a/50959039
has answer: http://stackoverflow.com/a/50959049
type: UnansweredQuestion
tagged with: break
tagged with: python
answer count: 4
has comment: http://stackoverflow.com/comment/88915316
has comment: http://stackoverflow.com/comment/88925159
has answer: http://stackoverflow.com/a/50959081
tagged with: loops
has title: Continues to loop back to initial value python
type: Question

http://stackoverflow.com/q/50993993
has comment: http://stackoverflow.com/comment/89045973
score: 1
favorite count: 0
tagged with: python-3.x
type: Question
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/88983567
tagged with: python
has answer: http://stackoverflow.com/a/51009724
upvote count: 1
answer count: 1
has title: numpysavetxt column header
accepted answer: http://stackoverflow.com/a/51009724
tagged with: numpy
has comment: http://stackoverflow.com/comment/88983707
has body: I'm using np.savetxt to create a csv file, but I'm not sure if I can add custom headers to each column. For example, I want my csv to look like: sample excel format For the column headers, preferably I would want it to increment by 1, and possibly index ahead while skipping some ints (I'll have other variables that increment/skip when forming my np array, so I could save the variables in a separate array if that works). As for the row headers, I'll be reading in various files in my directory, so it'd be most optimal to print the file names there (TypeA, TypeB, etc), otherwise anything that increments works as well. Does savetxt support this, or would something else be more optimal? If it helps...I'll have at least 100 columns and 200 rows, so manually listing all of them wouldn't work too well.
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88984883
downvote count: 0

http://stackoverflow.com/a/50950007
upvote count: 1
downvote count: 0
has body: The problem is that your xor list is not a list of bool Displaying the type of i in your loop provides this result: print([type(i) if i == True else type(i) for i in xor]) [&lt;class 'numpy.bool_'&gt;, &lt;class 'numpy.bool_'&gt;, &lt;class 'numpy.bool_'&gt;, &lt;class 'numpy.bool_'&gt;, &lt;class 'numpy.bool_'&gt;, &lt;class 'numpy.bool_'&gt;, &lt;class 'numpy.bool_'&gt;, &lt;class 'numpy.bool_'&gt;, &lt;class 'numpy.bool_'&gt;, &lt;class 'numpy.bool_'&gt;] Anytime you use the keyword is the item must be exactly the item being compared against. There is exactly one value of True in the Python environment. An is comparison compares your variable against that one value of True. In your case, the variable i is never actually True, it's a numpy bool with some value. An == compare would work as each side of the == is evaluated and a bool to bool comparison is made in the end. However, as previously stated, the preferred form has no comparison at all. if i is what you want.
answers question: http://stackoverflow.com/q/50938727
type: Answer
score: 1

http://stackoverflow.com/q/50881693
has comment: http://stackoverflow.com/comment/88765754
linked to: http://stackoverflow.com/q/306313
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/50881888
has comment: http://stackoverflow.com/comment/88766659
upvote count: 13
has comment: http://stackoverflow.com/comment/88766013
score: 12
has answer: http://stackoverflow.com/a/50881808
has body: From some of the answers on Stackoverflow, I came to know that from -5 to 256 same memory location is referenced thus we get true for: &gt;&gt;&gt; a = 256 &gt;&gt;&gt; a is 256 True Now comes the twist (see this line before marking duplicate): &gt;&gt;&gt; a = 257 &gt;&gt;&gt; a is 257 False This is completely understood, but now if I do: &gt;&gt;&gt; a = 257; a is 257 True &gt;&gt;&gt; a = 12345; a is 12345 True Why?
has answer: http://stackoverflow.com/a/50881926
has title: Uncommon behaviour of IS operator in python
has comment: http://stackoverflow.com/comment/88766830
favorite count: 0
has answer: http://stackoverflow.com/a/50882535
accepted answer: http://stackoverflow.com/a/50882535
tagged with: python
answer count: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88766113
possible better answer: http://stackoverflow.com/a/50881808

http://stackoverflow.com/comment/88842925
comment on: http://stackoverflow.com/a/50921215
has text: @TaohidulIslam this gives me " " as the most occurring string, and also doesn't account for substrings in each value. I think this is just considering the whole value of each cell in the CSV row. any fix for that?
type: AnswerComment
type: Comment
score: 0

arguments
tags question: http://stackoverflow.com/q/51008140
tags question: http://stackoverflow.com/q/50886560
tags question: http://stackoverflow.com/q/50977340
type: Tag
tags question: http://stackoverflow.com/q/50885201
tags question: http://stackoverflow.com/q/50991334
tags question: http://stackoverflow.com/q/50944469
tags question: http://stackoverflow.com/q/50948727
tags question: http://stackoverflow.com/q/50887562
tags question: http://stackoverflow.com/q/50941163
tag name: arguments
tags question: http://stackoverflow.com/q/50915226

http://stackoverflow.com/q/50997220
tagged with: python-requests
answer count: 1
accepted answer: http://stackoverflow.com/a/50997329
tagged with: http-headers
type: AnsweredQuestion
has title: Why does the requests library add extra headers to the ones I set?
tagged with: python-3.x
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/50997329
has body: I am trying to do a post request on python utilizing the requests library, when I set my custom headers which are the following: User-Agent: MBAM-C Content-Type: application/json Authorization: True Content-Length: 619 Connection: Close However when It send the request with the custom headers it adds its own headers which give a bad request response from the server.. User-Agent: MBAM-C Accept-Encoding: gzip, deflate Accept: */* Connection: Close Content-Type: application/json Authorization: True Content-Length: 559
has comment: http://stackoverflow.com/comment/88988743
score: 0

http://stackoverflow.com/a/50914892
downvote count: 0
type: Answer
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50914691
answers question: http://stackoverflow.com/q/50914691
has body: BS4 parses HTML, so you can use it to find the contents of this script tag. For example, if this is the only script in you page: script = soup.script.text But it doesn't parse JavaScript. So, you have a few choices: Download (or write) a JavaScript interpreter, use it to execute the code in the script, and then inspect it to see the variable and value it placed into the JS globals. Download (or write) a JavaScript parser, then scan the nodes for the var statement you're looking for and extract and interpret its value. Write a parser for a limited subset of JavaScript that will handle this specific case, but raise a noisy exception if they later rewrite their page to do something completely different in the script tag. Which one you want to do depends on what you're trying to accomplish. But I suspect the last one is what you actually want here. In which case there isn't going to be anything off-the-shelf that does all the work for you. But you can cheat. You don't actually need the whole TralbumData value, just the album_release_date member of it. So the grammar can be as simple as this regex: r'album_release_date: \"(.*?)\"' So: script = soup.script.text reldatematch = re.search(r'album_release_date: \"(.*?)\"', script) if reldatematch: reldate = your_date_parser_func(reldatematch.group(1)) Whether you want to make this more robust is up to you. If, say, you want to verify that this is actually the TralbumData.album_release_date value, not just something that happens to match album_release_date, then the grammar you want is just var TralbumData = OBJECT_LITERAL, and that OBJECT_LITERAL is almost JSON, except that it has bare keys. The first part, you could handle with just string methods: empty, lead, literal = script.partition('var TralbumData = ') if empty or not lead: raise SomeException And for parsing the literal, you could adapt a JSON parser like the JSON example for pyparsing or the stdlib's json module. Or, alternatively, you could do something hacky like …
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88830104

http://stackoverflow.com/comment/88826964
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50900050
type: AnswerComment
has text: line 24, in <listcomp> Comes up with this error Gilad: files = [filenames for filenames in files if os.path.isfile(join(folder_selected, filenames))] NameError: name 'join' is not defined

http://stackoverflow.com/q/51003884
possible better answer: http://stackoverflow.com/a/51003932
answer count: 3
has answer: http://stackoverflow.com/a/51003932
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/89001374
favorite count: 0
has comment: http://stackoverflow.com/comment/89001365
upvote count: 2
has answer: http://stackoverflow.com/a/51003962
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/89001399
has comment: http://stackoverflow.com/comment/89001348
type: AnsweredQuestion
tagged with: list
accepted answer: http://stackoverflow.com/a/51003962
has title: Check values of list within a dictionary inside a dictionary
type: Question
has comment: http://stackoverflow.com/comment/89001356
has body: I have this dictionary (making it simple): tmdbMovie = {'spoken_languages': [{'iso_639_1': 'pt', 'name': 'Português'}]} I'm trying to build an IF clause to check if 'Português' is one valid key for my dict. It's not working as you may expect.. What I've done so far: if 'Português' in [tmdbMovie['spoken_languages'][i]['name'] for i in tmdbMovie['spoken_languages']]: I know I'm missing something.. in this example my list inside dictionary has only one element but it could be more than one. Error: if 'Português' in [tmdbMovie['spoken_languages'][i]['name'] for i in tmdbMovie['spoken_languages']]: TypeError: list indices must be integers or slices, not dict
has answer: http://stackoverflow.com/a/51004649

http://stackoverflow.com/comment/88875321
type: Comment
has text: i renamed the columns, because I had not A, B, C,... but 1,2,3 as column names. The DF was just an example. After changing the column name I get this error message. But I cannot call the columns while they are numbers, like df2.1 , or do I have to call it otherwise then?
comment on: http://stackoverflow.com/a/50938087
score: 0
type: AnswerComment

http://stackoverflow.com/q/51008162
has title: How do I pass the output of SelectKBest to the cross_val_score function?
type: Question
answer count: 1
tagged with: scikit-learn
score: 0
tagged with: python
has answer: http://stackoverflow.com/a/51009000
type: UnansweredQuestion
tagged with: machine-learning
has body: I have the following code here: I am trying to retrieve the 20 best features from my dataset and then test the cross validated score with the Random Forest Classifier however once I've performed SelectKBest I recieve an output: X_train_selected and X_test_selected and it's not immediately obvious to me how I pass this to the cross val score function.

http://stackoverflow.com/q/50927184
has body: i want to inherit from a method in odoo 10 so i checked in from view to know his name but i find that the method are called using a number not his name! some methods in odoo are called from number like the method below. i want to know what means that number and how i can find a method called by his number in form view Code: &lt;button name="135" string="Print" states="done" type="action" groups="base.group_user"/&gt; &lt;button name="143" string="Return" states="done" type="action" groups="base.group_user"/&gt; where and how i can fin a method with the name 135 ?? Thanks
favorite count: 0
tagged with: python
tagged with: http://stackoverflow.com/tag/xml
tagged with: formview
score: 2
type: AnsweredQuestion
upvote count: 3
downvote count: 1
type: Question
tagged with: odoo
has answer: http://stackoverflow.com/a/50927711
has title: what means name="135" in button in formview odoo 10
tagged with: odoo-10
answer count: 1
accepted answer: http://stackoverflow.com/a/50927711

http://stackoverflow.com/a/50914304
score: 1
downvote count: 1
answers question: http://stackoverflow.com/q/50914204
upvote count: 2
type: Answer
has body: It says that for scope following as there will be a variable called ex that was created from Exception. In your case the difference is that in example one you are printing out the class Exception, in example two you are printing an object of type Exception. &gt;&gt;&gt; print(int) &lt;class 'int'&gt; &gt;&gt;&gt; print(int(1)) 1 &gt;&gt;&gt; I often see and use it when opening a file: with open(filename) as f: f.read() In python documentation it has the following example: &gt;&gt;&gt; try: ... raise NameError('HiThere') ... except NameError: ... print('An exception flew by!') ... raise ... An exception flew by! Traceback (most recent call last): File "&lt;stdin&gt;", line 2, in &lt;module&gt; NameError: HiThere Notice that the Code doesn't do anything with the class NameError. Because they are in that block they know that it's a NameError. If they wanted to do something with the error object that was thrown then they would have to rewrite the code with as: &gt;&gt;&gt; try: ... raise NameError('HiThere') ... except NameError as e: ... print(e) ... print('An exception flew by!') ... raise ...

http://stackoverflow.com/q/50932126
has answer: http://stackoverflow.com/a/51087806
has body: Hi I have two dataframes. Input data Frame:- id number idsc mfd 738 as6812 *fage abc van brw amz 745 786-151 *glaeceau smt sp amz 759 b0nadum ankush 574415 mo... admz 764 fdad3-al-c lib anvest-al... amz 887 rec-2s-5 or abc sur... c 64 00954 ankush pure g... amz 8 0000686 dor must die a 3 000adf623 bsc test 10-pi... amz Check Conditions Data Frame:- condition destinationfield expression b_id True idsc [idsc].lower() 1 [mfd]=="amz" idsc re.sub(r'\abc\b','a',[idsc]) 1 [mfd]=="admz" idsc re.sub(r'and \d+ other item', '', [idsc]) 1 True idsc re.sub(r'[^a-z0-9 ]',r'',[idsc]) 1 True idsc [idsc].strip() 1 [mfd] == "c" idsc re.sub(r'\ankush\b','ank',[idsc]) 1 True number re.sub(r'[^0-9]',r'',[number]) 1 True number [number].strip() 1 I am looking for applying each and every rule of condition dataframe on input dataframe and obtain a new dataframe. If my condition is true then I need to apply it on all the rows. if there is any specific value apart from true then I need to apply that condition for a specific record. Is there any better approach to do this in pyspark as the regular expressions are related to python. Instead of running it in for loops. id number idsc mfd 738 as6812 *fage a van brw amz 745 786-151 *glaeceau smt sp amz 759 b0nadum ank 574415 mo... admz 764 fdad3-al-c lib anvest-al... amz 887 rec-2s-5 or a sur... c 64 00954 ank pure g... amz 8 0000686 dor must die a 3 000adf623 bsc test 10-pi... amz input data pipe separated id| number|idsc|mfd 738|as6812|*fage abc van brw|amz 745|786-151|*glaeceau smt sp|amz 759|b0nadum|ankush 574415 mo...|admz 764|fdad3-al-c|lib anvest-al...|amz 887|rec-2s-5|or abc sur...|c 64| 00954|ankush pure g...|amz 8|0000686|dor must die a 3|000adf623|bsc test 10-pi...|amz Conditions Data pipe separated condition|destinationfield|expression|b_id| True|idsc|[idsc].lower()|1 [mfd]=="amz"|idsc|re.sub(r'\abc\b','a',[idsc])|1 [mfd]=="admz"|idsc|re.sub(r'and \d+ other item', '', [idsc])|1 True|idsc|re.sub(r'[^a-z0-9 ]',r'',[idsc])|1 True|idsc|[i…
has title: alter a dataframe by applying rules from a second dataframe
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88863125
tagged with: python
has comment: http://stackoverflow.com/comment/89182073
has comment: http://stackoverflow.com/comment/88863485
downvote count: 1
score: 3
linked to: http://stackoverflow.com/q/19798153
has comment: http://stackoverflow.com/comment/88987353
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/89038548
tagged with: pyspark
answer count: 1

http://stackoverflow.com/q/50960583
has comment: http://stackoverflow.com/comment/88918281
has title: pip install fail with SSL certificate verify failed (_ssl.c:833)
tagged with: pip
possible better answer: http://stackoverflow.com/a/75275026
has comment: http://stackoverflow.com/comment/88918616
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/49768770
has answer: http://stackoverflow.com/a/75275026
has answer: http://stackoverflow.com/a/50960673
score: 10
upvote count: 10
tagged with: ssl-certificate
linked to: http://stackoverflow.com/q/49324802
type: Question
linked to: http://stackoverflow.com/q/25981703
accepted answer: http://stackoverflow.com/a/50960673
has answer: http://stackoverflow.com/a/65331971
has comment: http://stackoverflow.com/comment/88919413
has comment: http://stackoverflow.com/comment/88919456
has comment: http://stackoverflow.com/comment/88919485
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51575966
has body: I am not able to install any external python module through pip install. I have installed python correctly but if I use pip_install it shows me this error. Here is the code after I run the pip install pytesseract C:\Users\190560&gt;pip install pytesseract Collecting pytesseract Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:833)'),)': /simple/pytesseract/ Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:833)'),)': /simple/pytesseract/ Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:833)'),)': /simple/pytesseract/ Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:833)'),)': /simple/pytesseract/ Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:833)'),)': /simple/pytesseract/ Could not fetch URL https://pypi.org/simple/pytesseract/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/pytesseract/ (Caused by SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:833)'),)) - skipping Could not find a version that satisfies the requirement pytesseract (from versions: ) No matching distribution found for pytesseract Could not fetch URL https://pypi.org/simple/pip/: There was a problem confirming the ssl certificate: HTTPSConnection…
has comment: http://stackoverflow.com/comment/88918915
tagged with: python
answer count: 4
has comment: http://stackoverflow.com/comment/88935954

http://stackoverflow.com/comment/88792157
type: AnswerComment
has text: Thank you so much. That did the trick. Side question: any idea as to why openCV doesn't support international fonts? Kinda weird that it only supports one font family.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50896089

http://stackoverflow.com/q/50998813
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51006069
score: 0
has comment: http://stackoverflow.com/comment/88993388
answer count: 1
has body: I have an assignment where I need to create three modules to be called and run, in sequence, within a main program. I assume this is a test case for the more complex final project, but I know it sounds like a dumb idea, so I am including the instructions. I have the code for each of 3 individual modules here (Please note: All of this would work just fine as a single script, but I am tasked with splitting it up). Instructions: Draw the hierarchy chart and then plan the logic for a program that calculates a person’s body mass index (BMI). BMI is a statistical measure that compares a person’s weight and height. The program uses three modules. The first prompts a user for and accepts the user’s height in inches. The second module accepts the user’s weight in pounds and converts the user’s height to meters and weight to kilograms. Then, it calculates BMI as weight in kilograms divided by height in meters squared, and displays the results. There are 2.54 centimeters in an inch, 100 centimeters in a meter, 453.59 grams in a pound, and 1,000 grams in a kilogram. Use named constants whenever you think they are appropriate. The last module displays the message End of job. Create the program in Python and provide the link to repl.it or attach the .py file. Note that running bmi_main.py actually DOES proceed to launch the three modules in sequence, but there is an error from module 2 because it uses 'height' which is a variable defined in module 1 that is apparently forgotten when module 2 starts. This implies I need height to be a global variable even though it is being defined by the user. I didn't think that would be a problem, but trying to declare height at the top of the main program is giving me errors. How can I fix this while retaining this (questionable but necessary) structure? Main: #Title: BMI Main #Author: Name #Class: CISPROG01 import bmi_mod01.py; import bmi_mod02.py; import bmi_mod03.py; #This is the main program, which has to call the modules to carry out enti…
has comment: http://stackoverflow.com/comment/88992969
has title: How to instruct these simple modules to run in sequence?
has comment: http://stackoverflow.com/comment/88993129
tagged with: python
tagged with: module
has answer: http://stackoverflow.com/a/51006069
type: Question

http://stackoverflow.com/comment/88878627
comment on: http://stackoverflow.com/q/50939694
type: QuestionComment
type: Comment
has text: @DebanjanB a screenshot has been attached!
score: 0

http://stackoverflow.com/comment/88815746
type: AnswerComment
score: 0
type: Comment
has text: Thank you very much for your comment! I know, but don't know where I can find help on this task(
comment on: http://stackoverflow.com/a/50906452

http://stackoverflow.com/a/54074590
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/105445138
has comment: http://stackoverflow.com/comment/112387918
answers question: http://stackoverflow.com/q/50882266
has body: I had similar issue with browser, I got No web browser found: could not locate runnable browser. I installed WSLU https://github.com/wslutilities/wslu. Then I got Start : This command cannot be run due to the error: The system cannot find the file specified. At line:1 char:1 + Start --h + ~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [Start-Process], InvalidOperationException + FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand jupyter-notebook does not supply url as a parameter to wlsview. It passes a path with file to browser. eg file:///home/myhome/.local/share/jupyter/runtime/nbserver-5058-open.html with actual url Opening Jupyter Notebook This page should redirect you to Jupyter Notebook. If it doesn't, click here to go to Jupyter. Create a file jupyter-notebook-browser with a content to extract actual url #!/bin/bash file=$(echo "$1" | sed 's/file:\/\///') url=$(grep -oP 'href="\K([^"]*localhost[^"]+)' "$file") wslview "$url" then run jupyter-notebook --browser=jupyter-notebook-browser or define BROWSER variable and run export BROWSER="jupyter-notebook-browser" jupyter-notebook
score: 4
has comment: http://stackoverflow.com/comment/94999894
type: Answer

http://stackoverflow.com/comment/89011675
score: 0
type: AnswerComment
has text: Ok now I understand. So it is necessary to use kernel in CNN together with the weights in every layer?
type: Comment
comment on: http://stackoverflow.com/a/51008657

http://stackoverflow.com/comment/88845836
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50923172
type: Comment
has text: @coldspeed `book = xlrd.open_workbook('file.xlsx'); s = book.sheets()[0]; x = zip(s.col_values(0, 1), s.col_values(1, 1))` isn't much of a nuisance (though sure, xlrd isn't in the stdlib). Anyway, both approaches work. :)

http://stackoverflow.com/a/56345071
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50995279
has body: I solved this issue using the following two process calls: subprocess.call('latex -interaction=batchmode -output-directory='+ outpath + ' ' + input_tex_file, shell=True, stdout=open(os.devnull, 'wb')) subprocess.call('dvipng -q* -T tight -o ' + output_png_file + ' ' + input_dvi_file, shell=True, stdout=open(os.devnull, 'wb')) You'll have to create .tex file first from your raw latex data. Then these commands first create a .dvi file (and some additional auxiliary files) from the .tex file. You can then use dvipng (https://ctan.org/pkg/dvipng?lang=en) to create a .png file.
downvote count: 0
type: Answer

http://stackoverflow.com/a/50979554
has body: Input (df) id quality date 0 1 2.0 2018-06-12 1 1 3.0 2018-06-20 2 1 3.0 2018-06-22 3 1 1.0 2018-05-12 4 2 5.0 2018-06-10 5 2 1.0 2018-06-15 6 2 1.0 2018-06-11 7 3 4.0 2018-07-10 8 3 4.0 2018-07-15 9 3 4.0 2018-07-16 Code # date column (lists) df0 = df.groupby('id')['date'].apply(list).reset_index(drop=False) # quality column (lists) df1 = df.groupby('id')['quality'].apply(list).reset_index(drop=False) # trend column (lists) df['delta'] = df.quality.diff(1) df.loc[df.delta &gt; 0, 'trend'] = 'inc' df.loc[df.delta == 0, 'trend'] = 'same' df.loc[df.delta &lt; 0, 'trend'] = 'dec' df2 = df.groupby('id')['trend'].apply(list).apply(lambda x: x[1:]).reset_index(drop=False) # merge all df3 = pd.merge(df1, df0, on='id', how='left') df3 = pd.merge(df3, df2, on='id', how='left') # remove brackets df3['quality'] = df3.quality.apply(lambda x: ", ".join(repr(e) for e in x)) df3['date'] = df3.date.apply(lambda x: ", ".join(x)) df3['trend'] = df3.trend.apply(lambda x: ", ".join(x)) Output (df3) id quality date trend 0 1 2.0, 3.0, 3.0, 1.0 6-12-18, 6-20-18, ... inc, same, dec 1 2 5.0, 1.0, 1.0 6-10-18, 6-15-18, ... dec, same 2 3 4.0, 4.0, 4.0 7-10-18, 7-15-18, ... same, same
accepted answer of: http://stackoverflow.com/q/50979111
type: Answer
answers question: http://stackoverflow.com/q/50979111
score: 1
upvote count: 1
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88955271

http://stackoverflow.com/a/51006266
has comment: http://stackoverflow.com/comment/89015886
score: 0
has comment: http://stackoverflow.com/comment/89017860
has body: Looks like read_sas still has the same bug as in the other question. The first variable, YEAR, is stored using only 4 bytes and read_sas is making up numbers to fill out the missing 4 bytes instead of filling them with zero bytes. Either find another package that actually understands SAS dataset structure or round or convert the values after reading them in.
has comment: http://stackoverflow.com/comment/89015173
type: Answer
has comment: http://stackoverflow.com/comment/89018046
answers question: http://stackoverflow.com/q/51005244
has comment: http://stackoverflow.com/comment/89015721
has comment: http://stackoverflow.com/comment/89007235

http://stackoverflow.com/comment/88861166
type: AnswerComment
score: 0
type: Comment
has text: OK, look like this is *very* data-dependent. I match yours and you probably will match mine. Guess OP should try both.
comment on: http://stackoverflow.com/a/50930428

http://stackoverflow.com/a/50898105
has comment: http://stackoverflow.com/comment/88939125
has comment: http://stackoverflow.com/comment/88944600
answers question: http://stackoverflow.com/q/50897094
score: 0
type: Answer
has body: You could try putting the main file with the rest of the files and then doing import database. It is the easy way. If you would like to keep your folder organization, I can’t help you.

http://stackoverflow.com/comment/89018056
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50980113
has text: @today maybe although it looks like it would need some finagling. `tf.extract_image_patches()` requires a 4D tensor `[batch, in_rows, in_cols, depth]` where mine is a 2D. And its not clear how the tensors come out (I'm AFK, so can't test). If you can write it as an answer with some basic code I'd be happy to test it tonight and award the bounty.
score: 0

http://stackoverflow.com/comment/88832298
type: QuestionComment
has text: @PierreRoodman from the answer selected in the possible duplicate `removed = re.sub('[!@#$]', '', sentence)` you'd have to update the character class to match your input `remove` variable though
comment on: http://stackoverflow.com/q/50915127
score: 0
type: Comment

http://stackoverflow.com/comment/88719315
has text: if you inspect HTML of the page each product is stored into a li element with id=result + item number for jeans there are 43 items (products)on the page for some other products it is usually around 50 products per page.
comment on: http://stackoverflow.com/q/50857672
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/97208399
has text: Thanks Thomas for your time. It helped me.
comment on: http://stackoverflow.com/a/50988113
type: AnswerComment
type: Comment
score: 1

http://stackoverflow.com/q/50983008
downvote count: 0
tagged with: keras
favorite count: 0
has title: How to save best weights of the encoder part only during auto-encoder training??
tagged with: python
score: 4
tagged with: autoencoder
type: UnansweredQuestion
has body: I am using keras with tensor flow to implement a deep auto-encoder with CNN: So basically the model would be similar to: input_data = Input(shape=(40,500,1)) #encoder x= Conv2D(32,kernel_size=(3,3), padding="same",activation='linear')(input_data) encoded= Conv2D(15,kernel_size=(1,2), strides=(1,2), padding="same",activation='linear')(x) #decoder x= Conv2DTranspose(15,kernel_size=(1,2), padding="same",activation='linear')(encoded) x= Conv2DTranspose(32,kernel_size=(3,3), padding="same",activation='linear')(x) decoded = Conv2DTranspose(1, (3, 3), activation=activationfuntion, padding="same")(x) autoencoder = Model(inputs=input_data,outputs=decoded) encoder = Model(inputs=input_data,outputs=encoded) In order to save the best model weights during training, I am using ModelCheckpoint: autoencoder.compile(loss='mean_squared_error', optimizer='rmsprop'); checkpoint=ModelCheckpoint('bestweight.best.hdf5',monitor='val_loss',verbose=1,save_best_only=True,mode='min'); callbacks_list=[checkpoint] history_info =autoencoder.fit(x_train, x_train, batch_size=batch_size, epochs=50, validation_data=(x_validation,x_validation), callbacks=callbacks_list, shuffle=True) and then later to test on the testdataset: autoencoder.load_weights('bestweight.best.hdf5'); autoencoder.predict(test_data); My question is: I know how to save the best weights of the whole auto-encoder, but is there a way to just save the best training weights of the encoder part so I can use it later for testing. so I can use it in this way: encoder.load_weights('encoderbestweight.best.hdf5'); encoder.predict(test_data);
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/50985253
upvote count: 4
has answer: http://stackoverflow.com/a/65267295
answer count: 2

http://stackoverflow.com/comment/88954409
has text: Thanks, cpinamtz. It's a little bit hard to do that, cos I have almost 3,000 videos to be fixed. And I can't find the way which one is incorrect by Picasa API.
score: 0
comment on: http://stackoverflow.com/q/50903751
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/119423665
score: 1
type: AnswerComment
type: Comment
has text: While this code snippet may solve the problem, it doesn't explain why or how it answers the question. Please [include an explanation for your code](https://meta.stackexchange.com/q/114762/269535), as that 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. You can use the [edit] button to improve this answer to get more votes and reputation!
comment on: http://stackoverflow.com/a/67564802

http://stackoverflow.com/comment/88722097
type: Comment
comment on: http://stackoverflow.com/a/50859550
score: 0
type: AnswerComment
has text: In my actual code (not just this toy example) I've been logging the device placements. That's where I saw that this operation was being assigned to my CPU, and led to me trying this toy example.

http://stackoverflow.com/q/50892823
favorite count: 0
answer count: 3
possible better answer: http://stackoverflow.com/a/50892875
has body: I'm new to Flask, and having some issues setting up a very basic Flask app. Right now, I'm trying to get the user to submit a form on the homepage and then save that form to a SQL database. However, when the user submits the form, I get the following error sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: contact [SQL: 'INSERT INTO contact (name, email) VALUES (?, ?)'] [parameters: ('aaa', 'aaa')] (Background on this error at: http://sqlalche.me/e/e3q8) Relevant code is below: app/models.py from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, BooleanField, SubmitField from wtforms.validators import DataRequired class ContactForm(FlaskForm): name = StringField('Name', validators=[DataRequired()]) email = PasswordField('Email', validators=[DataRequired()]) submit = SubmitField('submit') app/__init__.py from flask import Flask from config import Config from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate app = Flask(__name__) app.config.from_object(Config) db = SQLAlchemy(app) migrate = Migrate(app, db) from app import routes, models app/config.py import os basedir = os.path.abspath(os.path.dirname(__file__)) class Config(object): SECRET_KEY = os.environ.get('SECRET_KEY') or 'some-secret-key' SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or 'sqlite:///' + os.path.join(basedir, 'app.db') SQLALCHEMY_TRACK_MODIFICATIONS = False enter code here Where could I be going wrong here? Do I have to call db.create_all() somewhere? If so, where? Thanks! Edit: I've also run flask db init flask db migrate flask db upgrade
tagged with: python
has title: Flask sqlalchemy.exc.OperationalError: (OperationalError) no such table when trying to update database with SQLAlchemy
upvote count: 3
downvote count: 2
has answer: http://stackoverflow.com/a/50892937
type: AnsweredQuestion
score: 1
type: Question
has answer: http://stackoverflow.com/a/62148584
has answer: http://stackoverflow.com/a/50892875
accepted answer: http://stackoverflow.com/a/50892937
tagged with: flask
tagged with: flask-sqlalchemy

http://stackoverflow.com/a/50950555
score: 3
upvote count: 3
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50945999
has body: Providing an example of how you could scale down an image using PIL (Python Imaging Library - Link to docs) and then place it in an .xlsx file using xlsxwriter. With this example, you can see how you can adjust the size of your image using PIL and then using worksheet.set_column() and worksheet.set_row() you can adjust the cell size to accomodate the size of your image. So effectively, you can adjust the size of your image, adjust the size of the excel cell or do both. It might take a little testing to get the right fit. To make this answer reproducible I used urllib module to download an image to the local directory (that module is not necessary if you're using a local file). import urllib.request from PIL import Image import xlsxwriter import os url = 'https://upload.wikimedia.org/wikipedia/en/thumb/4/43/Ipswich_Town.svg/255px-Ipswich_Town.svg.png' urllib.request.urlretrieve(url, "local_100_perc.png") with Image.open("local_100_perc.png") as img: width_100 = img.width height_100 = img.height width_30 = int(round(width_100 * 0.3, 0)) img = Image.open('local_100_perc.png') wpercent = (width_30/float(width_100)) hsize = int((float(height_100)*float(wpercent))) img = img.resize((width_30,hsize), Image.ANTIALIAS) img.save('local_30_perc.png') workbook = xlsxwriter.Workbook('test.xlsx') worksheet = workbook.add_worksheet() worksheet.set_column('A:B', 10) worksheet.set_row(1, 70) worksheet.write('A2', 'Image:') worksheet.insert_image('B2', 'local_30_perc.png') workbook.close() With expected Output:

http://stackoverflow.com/comment/88779638
type: QuestionComment
comment on: http://stackoverflow.com/q/50889172
has text: Every "call" to `Contact` creates a new object - they will reside in different parts of memory
score: 0
type: Comment

http://stackoverflow.com/comment/88818847
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50909357
has text: I'm not sure what the second one is. What command is it? Can you paste it on its own?

http://stackoverflow.com/comment/88941152
has text: @YakymPirozhenko ur example still proves my point that there's a problem with the DP solution since it produces `4` for 1 case and `2` for the other case, whereas for the original recursion it produces `2` for both
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50938911

http://stackoverflow.com/q/50985105
tagged with: python
has title: Change network settings using Python script
score: 2
answer count: 0
tagged with: subprocess
type: Question
tagged with: network-programming
has body: I am trying to connect to a different WiFi network via a Python script. I am using a Raspberry Pi 3 Model B+ that is running the latest version of Raspbian. Adding a new network to the wpa_supplicant.conf Given a different network with SSID testing and its password testingPassword, I learned that I can add a new network by executing the following in the terminal: wpa_passphrase "testing" "testingPassword" | sudo tee -a /etc/wpa_supplicant/wpa_supplicant.conf &gt; /dev/null So I figured I could use the subprocess library in python: import subprocess ssid = '"testing"' passkey='"testingPassword"' command = ["wpa_passphrase", ssid, passkey, "|", "sudo", "tee", "-a", "/etc/wpa_supplicant/wpa_supplicant.conf", "&gt;", "/dev/null"] subprocess.run(command) But all this does is output (in the terminal): network={ ssid=""testing"" #psk=""testingPassword"" psk=3f446508c00cab57863ae62c8aaa505a4fae5d73461a0f10aee09988be8a2ae6 } ------------------ (program exited with code: 0) Press return to continue Problem Running the python script does not actually append the string to wpa_supplicant.conf. Any idea what I'm doing wrong? Solved @DougieLawson solved this for me on the raspberry pi forum by using subprocess.Popen. See usage below: import subprocess ssid = "MickeyMouse" passkey = "MinnieMouse" p1 = subprocess.Popen( ["wpa_passphrase", ssid, passkey], stdout=subprocess.PIPE ) p2 = subprocess.Popen( ["sudo", "tee", "a", "/etc/wpa_supplicant/wpa_supplicant.conf", "&gt;", "/dev/null"], stdin=p1.stdout, stdout=subprocess.PIPE ) p1.stdout.close() # Give p1 a SIGPIPE if p2 dies. output,err = p2.communicate()
downvote count: 0
favorite count: 0
tagged with: python-3.x
tagged with: linux
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/comment/88919984
score: 0
type: Comment
type: QuestionComment
has text: The you should wait for the lock to become available, rather than keep trying.
comment on: http://stackoverflow.com/q/50961538

http://stackoverflow.com/q/50923442
tagged with: matplotlib
type: Question
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/88846856
type: UnansweredQuestion
tagged with: python
has title: in python (plt.table set rowColours in first row)
has comment: http://stackoverflow.com/comment/88849350
has body: Hi I always get an error when I want to make the first row of my table color.I want to create a table and highlight the first row in color. Is there any other way to shape that? Edit here is my complete code import matplotlib.pyplot as plt import pandas as pd from pandas.plotting import table #first_page DATA_FILE = "C:/test/corr.xlsx" df = pd.read_excel("C:/test/corr.xlsx") s = df.iloc[0:15, 0:10] fig, ax = plt.subplots(figsize=(5, 1)) plt.suptitle("1.Excel-Daten", fontsize =15) ax.xaxis.set_visible(False) ax.yaxis.set_visible(False) ax.set_frame_on(False) tabla = table(ax, s, colWidths=[0.30]*len(df.columns), rowColours='r', colColours = 'r') tabla.auto_set_font_size(False) tabla.set_fontsize(15) tabla.scale(1.5,1.5) plt.show My error is: runfile('C:/Users/ucarm.lokal/.spyder-py3/untitled17.py', wdir='C:/Users/ucarm.lokal/.spyder-py3') Traceback (most recent call last): File "", line 1, in runfile('C:/Users/ucarm.lokal/.spyder-py3/untitled17.py', wdir='C:/Users/ucarm.lokal/.spyder-py3') File "C:\Anaconda\lib\site-packages\spyder\utils\site\sitecustomize.py", line 705, in runfile execfile(filename, namespace) File "C:\Anaconda\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "C:/Users/ucarm.lokal/.spyder-py3/untitled17.py", line 25, in tabla = table(ax, s, colWidths=[0.30]*len(df.columns), rowColours='r', colColours = 'r') File "C:\Anaconda\lib\site-packages\pandas\plotting_tools.py", line 65, in table colLabels=colLabels, **kwargs) File "C:\Anaconda\lib\site-packages\matplotlib\table.py", line 652, in table text=colLabels[col], facecolor=colColours[col], IndexError: string index out of range
answer count: 0

http://stackoverflow.com/comment/88930433
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50966410
has text: Thanks @JonatasCD - the problem we have isn't with the file paths and we aren't doing this processing in Windows. The problem is to do with filenames that contain a forward slash.

http://stackoverflow.com/comment/88931757
comment on: http://stackoverflow.com/a/50934563
score: 0
type: AnswerComment
has text: That is just perfect. Thank you so much. The pd.Grouper solution is perfect for my use case.
type: Comment

http://stackoverflow.com/q/50914546
has comment: http://stackoverflow.com/comment/88830022
type: Question
has comment: http://stackoverflow.com/comment/88829717
tagged with: network-programming
score: 0
has body: I am currently writing a performance test for a system that I built. I am executing X thousand API calls and measuring the time it takes. I would now also like to know how much traffic the X thousand calls caused. However, I am running the test 30 times inside a loop so that I can calculate the mean and the confidence intervals to filter out spikes because of overflowing buffers and such. Is there a tool that allows me to calculate the traffic caused by my script for each loop? This question's answer suggests to use psutil, however that seems to measure the network traffic for the whole system?
linked to: http://stackoverflow.com/q/33064891
has comment: http://stackoverflow.com/comment/88829792
tagged with: python-3.x
has title: Measuring traffic caused by a (part of a) python script
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/8958614
tagged with: performance
has comment: http://stackoverflow.com/comment/88830864
answer count: 0

http://stackoverflow.com/a/51003377
answers question: http://stackoverflow.com/q/51003207
has comment: http://stackoverflow.com/comment/89000557
type: Answer
score: 1
has comment: http://stackoverflow.com/comment/89000584
upvote count: 1
has body: FailedPreconditionError (see above for traceback): Attempting to use uninitialized value mean_squared_error/count The value count from the above error, is one of the local variable metrics.mean_squared_error uses to calculate MSE (the other is count). So you need to initialize the local variables using: sess.run(tf.local_variables_initializer())
downvote count: 0

http://stackoverflow.com/comment/89013197
has text: It installs the package as [editable](https://pip.pypa.io/en/stable/reference/pip_install/#install-editable)
comment on: http://stackoverflow.com/q/51010251
type: Comment
type: QuestionComment
score: 3

http://stackoverflow.com/comment/89015566
type: Comment
has text: The checkboxes are now correctly position but the text keeps getting spaced as seen on the first picture. Any ideas?
comment on: http://stackoverflow.com/a/50993941
score: 0
type: AnswerComment

http://stackoverflow.com/a/50869210
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50869093
downvote count: 0
has body: You need to use self, or the class name, to access the class variable s class C: s = "but why" def __init__(self): print(C.s, self.s) if __name__ == '__main__': c = C()

http://stackoverflow.com/comment/88837225
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50917384
type: Comment
has text: This is an interesting question, hopefully someone will have answer. My gut says it not be available in python with xlrd etc. In .NET with excel-interop you want the cell validation property. see :https://stackoverflow.com/questions/25659888/add-dropdown-list-in-the-excel-sheet-using-c-sharp . One suggestion which may still be fruitless would be to look at xlwings.

http://stackoverflow.com/comment/88728350
type: QuestionComment
score: 2
has text: How are you starting container? Just by `docker-compose up -d`? Did you rebuild it between attempts with `docker-compose build`?
comment on: http://stackoverflow.com/q/50862085
type: Comment

http://stackoverflow.com/a/51013692
downvote count: 0
answers question: http://stackoverflow.com/q/51011244
type: Answer
has comment: http://stackoverflow.com/comment/89060714
has body: You have to use QWebChannel, for that you have to download qwebchannel.js (link leads to qwebchannel.js for Qt 5.12, for different versions change github branch). In the following code I show an example: . ├── index.html ├── main.py └── qwebchannel.js main.py import sys from PySide2 import QtCore, QtGui, QtWidgets, QtWebEngineWidgets, QtWebChannel class WebEnginePage(QtWebEngineWidgets.QWebEnginePage): pass class AppManager(QtCore.QObject): textChanged = QtCore.Signal(str) def __init__(self, webview): QtCore.QObject.__init__(self) self.m_text = "" timer = QtCore.QTimer(self) timer.timeout.connect(self.on_timeout) timer.start(1000) def on_timeout(self): self.text = QtCore.QDateTime.currentDateTime().toString() @QtCore.Property(str, notify=textChanged) def text(self): return self.m_text @text.setter def setText(self, text): if self.m_text == text: return self.m_text = text self.textChanged.emit(self.m_text) class WebView(QtWebEngineWidgets.QWebEngineView): def __init__(self, parent=None): QtWebEngineWidgets.QWebEngineView.__init__(self, parent) self.setPage(WebEnginePage(self)) def contextMenuEvent(self, event): pass class AppWindow(QtWidgets.QMainWindow): def __init__(self): QtWidgets.QMainWindow.__init__(self) self.view = WebView(self) self.page = self.view.page() self.app_manager = AppManager(self.view) channel = QtWebChannel.QWebChannel(self) self.page.setWebChannel(channel) channel.registerObject("app_manager", self.app_manager) self.view.load(QtCore.QUrl.fromLocalFile(QtCore.QDir.current().filePath("index.html"))) self.setCentralWidget(self.view) if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) w = AppWindow() w.show() sys.exit(app.exec_()) index.html This is title
has comment: http://stackoverflow.com/comment/89060705
score: 5
upvote count: 5

http://stackoverflow.com/q/50904604
tagged with: scikit-image
tagged with: image-processing
answer count: 1
score: 0
has title: skimage sample from non-integer locations in image?
accepted answer: http://stackoverflow.com/a/50913481
tagged with: python
has body: We can sample from integer positions in an image because images are constructed as 2d arrays, and we just take whatever data is sitting in the array location. With non-integer positions, like say between two pixels, this is not so straightforward. However, it's such a common problem that (for ex.) GPUs have this functionality baked into the hardware so long as you're satisfied with linear interpolation. I can't find any functionality for this in skimage, but it seems so fundamental to image processing that I feel like I must be missing something. I would expect something like: sample(img, (64.5, 120.37), interpolation='linear')
tagged with: interpolation
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50913481
type: Question

http://stackoverflow.com/q/50886876
has body: I have a binary file which I try to decode. The format is something like this: Fix header bytes - Define the beginning of a package Type - which type of information it contains Length - Number of bytes are in the package (with out crc,...) Message... CRC8 - checksum End of Package byte In my program i read byte after byte and then search for the header and read the rest of the message based on the length value. Assuming the CRC8 is not correct, then i can't trust the length value and I would not like to lose all the bytes i read, but just one. I guess this is a common problem for parsing data... Any ideas?
score: 0
has comment: http://stackoverflow.com/comment/88775477
has comment: http://stackoverflow.com/comment/88775228
has title: How to lose less as possible bytes in case of a checksum error
tagged with: python
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/88775275

http://stackoverflow.com/comment/117041219
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50995397
has text: `json.dumps(data['attributes'])` doesn't work for me. I get the error 'Object of type QuerySet is not JSON serializable'. I believe this is referring to the list that contains each attribute.
type: AnswerComment

http://stackoverflow.com/a/50931647
type: Answer
has body: Because timedelta is the closest to MySQL's time data type in Pandas/Numpy. Consider the following DataFrame: In [306]: df Out[306]: time 0 10:11:12 1 22:23:24 In [307]: df.dtypes Out[307]: time object dtype: object you can either convert it to datetime (this will require a date part): In [308]: pd.to_datetime(df.time) Out[308]: 0 2018-06-19 10:11:12 1 2018-06-19 22:23:24 Name: time, dtype: datetime64[ns] # &lt;---- note the dtype or to a timedelta: In [309]: pd.to_timedelta(df.time) Out[309]: 0 10:11:12 1 22:23:24 Name: time, dtype: timedelta64[ns] # &lt;---- note the dtype
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50931416
answers question: http://stackoverflow.com/q/50931416

http://stackoverflow.com/q/50946387
tagged with: algorithm
has answer: http://stackoverflow.com/a/50958252
score: -1
answer count: 1
downvote count: 1
favorite count: 0
has body: I am trying to implement quicksort in place in ascending and descending order. The pivot element is the middle one. If the list is length 2 the pivot element is the first one. if the list length is even the pivot element is the last number of the first half of list. I have written a function which is called quickSort(L, ascending True) L = List, true=ascending, false=descending quickSort(testList1,False) def quickSort(L, ascending = True): print('Quicksort, Parameter L:') print(L) def quicksort(listToSort,lowIndex,highIndex): if ((highIndex - lowIndex) &gt; 0): p = partition(listToSort,lowIndex,highIndex) quicksort(listToSort,lowIndex,p-1) quicksort(listToSort,p+1,highIndex) def partition(listToSort, lowIndex, highIndex): divider = lowIndex pivot = highIndex for i in range(lowIndex,highIndex): if (listToSort[i] &lt; listToSort[pivot]): listToSort[i], listToSort[divider] = listToSort[divider],listToSort[i] divider +=1 listToSort[pivot], listToSort[divider] = listToSort[divider], listToSort[pivot] return divider testList1 = [1,0,2,3,4,6,5,8,9,7] testList2 = list([3.14159 , 1./127, 2.718 , 1.618 , -23., 3.14159]) testList3 = [10,9,8,7,6,5,4,3,2,1] quicksort(testList1,0,9) print (testList1) quicksort(testList2,0,5) print (testList2) quicksort(testList3,0,9) print (testList3) quickSort(testList1,False)
type: UnansweredQuestion
has title: Quicksort ascending and descendding python
tagged with: python
tagged with: quicksort
upvote count: 0
has comment: http://stackoverflow.com/comment/88895898
type: Question

http://stackoverflow.com/comment/88979533
type: QuestionComment
score: 0
has text: This looks SO complex. Looks to me you are missing a preventDefault. `$('#ticket-form').on("submit",function(event) { event.preventDefault();`
type: Comment
comment on: http://stackoverflow.com/q/50992402

http://stackoverflow.com/q/50915224
answer count: 1
tagged with: linux
has answer: http://stackoverflow.com/a/50915345
tagged with: python
has body: I can communicate with a device over UART with the following command in the linux shell: echo 'CMD' &gt; /dev/ttyPS1 I tried to recreate this action in Python using the Pyserial module, but nothing happens. I have tried to use it in both a .py file as well as inside of 2.7 interpreter (in case of timing delay issues). import serial ser = serial.Serial('/dev/ttyPS1', 115200) ser.write('CMD') Interestingly enough... after running the snippet of python, I cannot write to the device using the linux shell. stty shows me that Pyserial has added a bunch of options to the device. If I clear these extra options, then I can use the linux shell to talk with my device again. Before Python script: &gt;&gt;&gt; stty -F /dev/ttyPS1 speed 115200 baud; line = 0; -brkint -imaxbel After Python script: &gt;&gt;&gt; stty -F /dev/ttyPS1 speed 115200 baud; line = 0; min = 0; time = 0; -brkint -icrnl -imaxbel -opost -onlcr -isig -icanon -iexten -echo -echoe -echok -echoctl -echoke Why is this behavior happening? Is there a way to make Pyserial act like the linux shell?
has title: Pyserial cannot write to tty like the linux shell
tagged with: uart
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50915345
type: Question
score: 0
tagged with: raspberry-pi
tagged with: pyserial

http://stackoverflow.com/comment/88899153
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50950013
has text: I believe I have reduced it to the minimum amount of code. Let me know if this suffices.

http://stackoverflow.com/comment/88911930
has text: Have you put the `from tkinter import Frame` at the top of the Clock.py file?
comment on: http://stackoverflow.com/q/50957228
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/89009619
comment on: http://stackoverflow.com/q/51008334
type: Comment
type: QuestionComment
has text: Well, yeah, you've indented that code as though it's part of a function. I'm not going to through all of that code but why are you declaring `global` outside of a function and do you really want global variables in Flask?
score: 1

http://stackoverflow.com/comment/88795458
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50897891
has text: Now its showing this error!! See I edited again

http://stackoverflow.com/a/50931229
score: 0
has body: If I understand you correctly, you want to get the text of the selected item from the list. To do that use: self.listWidgetPdfList.selectedItems()[0].text() Here you use 0 as the index because you want only the first item in the selected items list. Iterating through the list is unnecessary if you only want the selected item.
type: Answer
answers question: http://stackoverflow.com/q/50926669
has comment: http://stackoverflow.com/comment/88919288

http://stackoverflow.com/q/50897520
downvote count: 0
has answer: http://stackoverflow.com/a/50897583
has title: Return closest value in look up table, and put in list of dicts
answer count: 1
favorite count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/50897583
tagged with: dictionary
type: AnsweredQuestion
tagged with: list
score: 1
has body: I have a list of dicts like so: my_data = [{'id': 'A', 'density':0.7}, {'id': 'B', 'density':1.5}, {'id': 'C', 'density':3.75}] and a Look Up Table (lut) as a list of dicts like so: lut = [{'density': 1.1, 'capacity': 5.19}, {'density': 2.5, 'capacity': 9.42}, {'density': 4.3, 'capacity': 16.78}] For each dict in my_data, I want to take 'density' and find the closest corresponding 'density' value in the lut. I then want to add the corresponding 'capacity' item to that dict. I've started with a function as so: def function_for_adding_capacity(data, lut): my_list_of_dicts = [] for datum in data: for item in lut: datum['capacity'] = ... my_list_of_dicts.append({ 'id': datum['id'], 'density': datum['density'], 'capacity': datum['capacity'], return my_list_of_dicts I'm just not sure (1) if I need the second loop, and (2) what to do to find the closest matching density, than returning the corresponding capacity?
upvote count: 1
type: Question

http://stackoverflow.com/comment/88881209
type: AnswerComment
has text: And I think this is the one to go for.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50941672

http://stackoverflow.com/a/50973304
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50951893
score: 1
accepted answer of: http://stackoverflow.com/q/50951893
has body: I solved the problem on my own. #Queue i = int(gwi["Server"][0]) #Number of Servers line_idx=get_line(data,'Queue1 Position') del data[line_idx+1] queue_text = "" for x in range(1,i+1): if x&lt;i: queue_text = queue_text+('Queue'+str(x)+' Position { 1.500000 '+str(1.100000-x+1)+' 0.000000 m }\n'+'Queue'+str(x)+ ' Points { { 1.500 '+str(0.700-x+1)+' 0.000 m } { 2.500 '+str(0.700-x+1)+' 0.000 m } }\n\n') else: queue_text = queue_text+('Queue'+str(x)+' Position { 1.500000 '+str(1.100000-x+1)+' 0.000000 m }\n'+'Queue'+str(x)+ ' Points { { 1.500 '+str(0.700-x+1)+' 0.000 m } { 2.500 '+str(0.700-x+1)+' 0.000 m } }\n') data[line_idx] = queue_text
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/a/50952817
has comment: http://stackoverflow.com/comment/137042444
type: Answer
has body: You would be needing to install tesseract. https://github.com/tesseract-ocr/tesseract/wiki Check out the above documentation on the installation.
has comment: http://stackoverflow.com/comment/88903279
score: 1
upvote count: 2
downvote count: 1
answers question: http://stackoverflow.com/q/50951955

http://stackoverflow.com/q/50892550
has answer: http://stackoverflow.com/a/50892566
upvote count: 2
linked to: http://stackoverflow.com/q/16096754
has body: I have tried ways on converting list to strings as found in other questions but the output doesn't seem to be what I should get. I have an input of [['This','is','here.'],['Second','sentence','here.']] and I would like to convert this to string and be saved to a text file with the output: This is here. Second sentence here. what I did is, list = [['This','is','here.'],['Second','sentence','here.']] with open(outfile, 'w') as newfile: newfile.write(str('\n'.join((str(i) for i in list)))) The output of this in the .txt file is: ['This', 'is', 'here.'] ['Second', 'sentence', 'here.'] A help is very much appreciated. thanks!
has comment: http://stackoverflow.com/comment/88785686
downvote count: 1
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50892568
has answer: http://stackoverflow.com/a/50892568
has title: How to convert list of list of word strings to strings as sentences?
accepted answer: http://stackoverflow.com/a/50892566
type: Question
answer count: 2
favorite count: 0
tagged with: python-2.7
tagged with: python
score: 1
tagged with: python-3.x

http://stackoverflow.com/comment/88881275
comment on: http://stackoverflow.com/a/50941678
has text: @PM 2Ring: Good points, well made. I will adjust my reaction.
score: 0
type: AnswerComment
type: Comment

package
tags question: http://stackoverflow.com/q/50987150
tag name: package
tags question: http://stackoverflow.com/q/50874361
type: Tag
tags question: http://stackoverflow.com/q/50929414
tags question: http://stackoverflow.com/q/50942277
tags question: http://stackoverflow.com/q/50953880
tags question: http://stackoverflow.com/q/50874045
tags question: http://stackoverflow.com/q/50879668
tags question: http://stackoverflow.com/q/50950571
tags question: http://stackoverflow.com/q/50890899
tags question: http://stackoverflow.com/q/50912024
tags question: http://stackoverflow.com/q/50857160

http://stackoverflow.com/a/50965309
type: AcceptedAnswer
has body: If you are looking for python code to achieve a lot more, you can find it at this repo... https://github.com/DevashishPrasad/Angle-Distance So, to solve your problem this code might be helpful - # import the necessary packages from imutils import perspective from imutils import contours import numpy as np import imutils import cv2 # load the image, convert it to grayscale, and blur it slightly image = cv2.imread("test.png") gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) gray = cv2.GaussianBlur(gray, (7, 7), 0) # perform edge detection, then perform a dilation + erosion to # close gaps in between object edges edged = cv2.Canny(gray, 50, 100) edged = cv2.dilate(edged, None, iterations=1) edged = cv2.erode(edged, None, iterations=1) # find contours in the edge map cnts = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnts = cnts[0] if imutils.is_cv2() else cnts[1] # loop over the contours individually for c in cnts: # This is to ignore that small hair countour which is not big enough if cv2.contourArea(c) &lt; 1000: continue # compute the rotated bounding box of the contour box = cv2.minAreaRect(c) box = cv2.cv.BoxPoints(box) if imutils.is_cv2() else cv2.boxPoints(box) box = np.array(box, dtype="int") # order the points in the contour such that they appear # in top-left, top-right, bottom-right, and bottom-left # order, then draw the outline of the rotated bounding # box box = perspective.order_points(box) # draw the contours on the image orig = image.copy() cv2.drawContours(orig, [box.astype("int")], -1, (0, 255, 0), 5) # loop over the original points for (xA, yA) in list(box): # draw circles corresponding to the current points and cv2.circle(orig, (int(xA), int(yA)), 9, (0,0,255), -1) cv2.putText(orig, "({},{})".format(xA, yA), (int(xA - 50), int(yA - 10) - 20), cv2.FONT_HERSHEY_SIMPLEX, 1.8, (255,0,0), 5) # show the output image, resize it as per your requirements cv2.imshow("Image", cv2.resize(orig,(800,600))) cv2.waitKey(0) Comments exp…
downvote count: 0
has comment: http://stackoverflow.com/comment/88949040
accepted answer of: http://stackoverflow.com/q/50957574
type: Answer
answers question: http://stackoverflow.com/q/50957574
has comment: http://stackoverflow.com/comment/88962235
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/88935379
has comment: http://stackoverflow.com/comment/88962346

http://stackoverflow.com/q/50999577
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51007777
tagged with: django
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88993346
has title: How can I change a boolean value with POST request Django
linked to: http://stackoverflow.com/q/19454310
accepted answer: http://stackoverflow.com/a/51007777
tagged with: html-table
tagged with: boolean
score: 0
has comment: http://stackoverflow.com/comment/88997458
answer count: 1
has body: Edit: My goal is to create a small e-commerce. In my index I have a list of products, one of the attributes is a boolean called in_cart which states if the product is in the cart or not. By default all boolean values are false. In my template is a table with all the products next to which I put a button "add to cart", which redirects to the cart template. However when I click on add to cart, the value of the boolean in question does not change to true. Any thoughts? List of car parts available: Name Price {% for product in products_list %} {{ product.id }} {{ product.name }} ${{ product.price }} {% if not product.in_cart %} {% csrf_token %} {% else %} {{ print }} {% endif %} {% endfor %} See cart And these are my views: def index(request): if request.method == "GET": products_list = Product.objects.all() template = loader.get_template('products/index.html') context = {'products_list': products_list} return HttpResponse(template.render(context, request)) return HttpResponse('Method not allowed', status=405) def cart(request): cart_list = Product.objects.filter(in_cart = True) template_cart = loader.get_template('cart/cart.html') context = {'cart_list': cart_list} return HttpResponse(template_cart.render(context, request)) def add_to_cart(request, product_id): if request.method == 'POST': try: product = Product.objects.get(pk=product_id) product.in_cart = True product.save() except Product.DoesNotExist: return HttpResponse('Product not found', status=404) except Exception: return HttpResponse('Internal Error', status=500) return HttpResponse('Method not allowed', status=405) Model: class Product(models.Model): name = models.CharField(max_length=200) price = models.IntegerField() in_cart = models.BooleanField(default=False) ordered = models.BooleanField(default=False) def __str__(self): return self.name URLs urlpatterns = [ path('', views.index, name='index'), path('cart/', views.cart, name='cart') re_path(r'^add_to_cart/(?P<product_id>[0-9]+)$', views.add_to_cart, nam…
has comment: http://stackoverflow.com/comment/89001539
favorite count: 0
has comment: http://stackoverflow.com/comment/89015974
has comment: http://stackoverflow.com/comment/88994979
tagged with: python

http://stackoverflow.com/comment/88973225
score: 0
type: Comment
has text: Thanks. You should make this the answer and I can mark this as resolved.
type: QuestionComment
comment on: http://stackoverflow.com/q/50988050

http://stackoverflow.com/comment/89011874
type: Comment
has text: Ok, thank you very much !
comment on: http://stackoverflow.com/q/51008838
type: QuestionComment
score: 0

http://stackoverflow.com/a/50942372
accepted answer of: http://stackoverflow.com/q/50942291
has body: datetime.strptime(word[0], '%Y-%m-%d %H:%M:%S ') will work. Note the '-' and the trailing space. Depending on your use case and whether you have more and differently dirty data, you might be better off stripping the input or using some more robust utility like dateparser.
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/89007458
answers question: http://stackoverflow.com/q/50942291
has comment: http://stackoverflow.com/comment/88895920

http://stackoverflow.com/q/50900734
linked to: http://stackoverflow.com/q/36692720
possible better answer: http://stackoverflow.com/a/50900826
tagged with: linear-algebra
has answer: http://stackoverflow.com/a/50900826
type: Question
tagged with: numpy
score: 0
answer count: 2
tagged with: scikit-learn
accepted answer: http://stackoverflow.com/a/50900910
has title: Vectorizing radial basis function's euclidean distance calculation for multidimensional features
tagged with: python
linked to: http://stackoverflow.com/q/47877530
has body: I suspect there is probably a SO post that has answered this question, but I have not been able to find it yet, so I apologize in advance if this is a duplicate question. I'm attempting to implement a radial basis function kernel from scratch using Numpy for my own learning purposes. For one-dimensional inputs, the calculation is pretty easy: def kernel(x, y): return * np.exp( -0.5 * np.subtract.outer(x, y)**2) The above is from a blog post on Gaussian Processes. But I'm trying to extend this to multiple dimensions. I have an implementation that works fine below: x = np.array([[4,3,5], [1,3,9], [0,1,0], [4,3,5]]) distances = [] γ = -.5 for i in x: for j in x: distances.append(np.exp(γ * np.linalg.norm(i - j) ** 2)) np.array(distances).reshape(len(x),len(x)) [[1.00000000e+00 3.72665317e-06 1.69189792e-10 1.00000000e+00] [3.72665317e-06 1.00000000e+00 2.11513104e-19 3.72665317e-06] [1.69189792e-10 2.11513104e-19 1.00000000e+00 1.69189792e-10] [1.00000000e+00 3.72665317e-06 1.69189792e-10 1.00000000e+00]] I am checking using sklearn.pairwise.rbf_kernel from sklearn.metrics.pairwise import rbf_kernel print(rbf_kernel(x, gamma= .5)) [[1.00000000e+00 3.72665317e-06 1.69189792e-10 1.00000000e+00] [3.72665317e-06 1.00000000e+00 2.11513104e-19 3.72665317e-06] [1.69189792e-10 2.11513104e-19 1.00000000e+00 1.69189792e-10] [1.00000000e+00 3.72665317e-06 1.69189792e-10 1.00000000e+00]] But clearly the double for loops are not the most efficient way of iterating through this. What's the best way to vectorize this operation? This SO post provides an efficient way of calculating distances, but does not provide the vectorization I need.
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50900910

http://stackoverflow.com/comment/88857872
type: AnswerComment
type: Comment
has text: lets keep the useful information in one single answer
comment on: http://stackoverflow.com/a/50929373
score: 0

http://stackoverflow.com/comment/135521969
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50888637
score: 0
has text: Wouldn't `df.index[df.a.str.contains('-$')]` be more efficient than `df[df.a.str.contains('-$')].index`?

http://stackoverflow.com/a/50873917
downvote count: 0
answers question: http://stackoverflow.com/q/50873652
has body: You are seeing an integer overflow. The maximum value that np.uint16 can represent is 2^16 = 65536. 41238 * 256 is much larger than 2^16. The value you get is 41238 * 256 % 2^16. To avoid the overflow, convert your numbers to np.uint32, and then multiply by 256: convert = data16.astype(np.uint32) * 256 Note that you are converting to a 24 Bit range with your 2^8 multiplication factor, not to a 32 Bit range.
accepted answer of: http://stackoverflow.com/q/50873652
upvote count: 2
type: AcceptedAnswer
type: Answer
score: 2

http://stackoverflow.com/a/50898652
has body: &gt;&gt;&gt; for row in table.find_all("tr"): ... cols = row.find_all("td") ... if not cols: ... continue ... name, year, des = filter(None, [col.text.strip() for col in cols]) ... print (f'Name: {name}, Year: {year}, Des: {des}') ... Name: K. Ratna Prabha, Year: 2014, Des: Non-Executive Chairman of the Board Name: Mohan Kulkarni, Year: 2012, Des: Compliance Officer, Company Secretary Name: Naveen Singh, Year: 2014, Des: Managing Director, Executive Director Name: B. Khanna, Year: 2014, Des: Non-Executive Director - Nominee of BIFR Name: V. Rammohan, Year: 2013, Des: Non-Executive Director - Nominee of IFCI Name: Aravind Shrivastava, Year: 2013, Des: Non-Executive Director Name: M. Lakshminarayana, Year: 2009, Des: Non-Executive Independent Director Name: C. Okaly, Year: 2010, Des: Non-Executive Independent Director Name: S. Parameswarappa, Year: 1996, Des: Non-Executive Independent Director Name: C. Shivashankar, Year: 1995, Des: Non-Executive Independent Director &gt;&gt;&gt;
accepted answer of: http://stackoverflow.com/q/50898312
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50898312
score: 0
type: Answer

http://stackoverflow.com/comment/89007007
type: QuestionComment
comment on: http://stackoverflow.com/q/51006809
type: Comment
has text: I did use inheritance at first, but due to some restriction of the parent class, some functionality cannot be inherited properly.
score: 0

http://stackoverflow.com/q/50935506
has answer: http://stackoverflow.com/a/67278775
has answer: http://stackoverflow.com/a/50935556
has title: Unable to drop column, object has no attribute error
linked to: http://stackoverflow.com/q/13411544
type: Question
upvote count: 4
score: 4
has answer: http://stackoverflow.com/a/50935993
answer count: 3
tagged with: pandas
downvote count: 0
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88869674
has body: I have a csv file with column titles: name, mfr, type, calories, protein, fat, sodium, fiber, carbo, sugars, vitamins, rating. When I try to drop the sodium column, I don't understand why I'm getting a NoneType' object has no attribute 'drop' error I've tried df.drop(['sodium'],axis=1) df = df.drop(['sodium'],axis=1) df = df.drop (['sodium'], 1, inplace=True)
tagged with: python

jpype
tag name: jpype
tags question: http://stackoverflow.com/q/50886416
type: Tag

http://stackoverflow.com/a/50887311
has comment: http://stackoverflow.com/comment/89110608
accepted answer of: http://stackoverflow.com/q/50886888
has comment: http://stackoverflow.com/comment/89117780
answers question: http://stackoverflow.com/q/50886888
type: Answer
has comment: http://stackoverflow.com/comment/89115966
has comment: http://stackoverflow.com/comment/89110532
score: 2
has comment: http://stackoverflow.com/comment/89011976
has comment: http://stackoverflow.com/comment/89108222
has comment: http://stackoverflow.com/comment/89109554
has comment: http://stackoverflow.com/comment/89110302
has body: Here's a possible fix for your code: import threading import pygame from pygame.locals import * from time import sleep import sys pygame.init() screen = pygame.display.set_mode((1160, 640), 0, 0) screen.fill((255, 255, 255)) pygame.display.flip() def background(): number = 0 while True: if number &lt; 10: number = number + 1 print(number) sleep(1) else: print("10 seconds are over!") break def foreground(): while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if pygame.key.get_mods() &amp; pygame.KMOD_CTRL and event.key == pygame.K_q: print('HELLO_WORLD') pygame.display.update() b = threading.Thread(name='background', target=background) b.start() foreground()
has comment: http://stackoverflow.com/comment/89011628
downvote count: 1
has comment: http://stackoverflow.com/comment/88778611
has comment: http://stackoverflow.com/comment/89112058
has comment: http://stackoverflow.com/comment/89007156
has comment: http://stackoverflow.com/comment/89109758
has comment: http://stackoverflow.com/comment/88779118
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89110322
upvote count: 3
has comment: http://stackoverflow.com/comment/88778759
has comment: http://stackoverflow.com/comment/89110255

http://stackoverflow.com/q/50983106
type: UnansweredQuestion
upvote count: 1
tagged with: python
answer count: 0
score: 1
has title: Dynamic class variable for Marshmallow Schema?
has body: I'm making several Schemas using Marshmallow. Some of them would be UserSchema, PatientSchema and AppointmentSchema. I'm also making a "overall" FeedbackSchema, looking like this: class FeedbackSchema(Schema): success = fields.Bool() message = fields.String() error = fields.String() data = ? I imagine that when a end user asks for the route /users/all it will result in a FeedbackSchema where the data field is filled with a list of all users. That is, fields.List(fields.Nested(UserSchema)). However if they go to /patient/1 the data field is filled with a single patient, that is fields.Nested(PatientSchema). What I want is to not have to create several different FeedbackSchemas being virtually identical, except in their definition of the type of the data class variable. How can I achieve this dynamically? Some sort of class factory I'm not aware of? My current solution is using this subclassing: class UserFeedbackSchema(FeedbackSchema): data = fields.Nested(UserSchema)
type: Question
has comment: http://stackoverflow.com/comment/89017688
downvote count: 0
tagged with: marshmallow
has comment: http://stackoverflow.com/comment/89028622
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/q/50992472
tagged with: python
has answer: http://stackoverflow.com/a/50992581
possible better answer: http://stackoverflow.com/a/50992579
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/50992579
upvote count: 3
accepted answer: http://stackoverflow.com/a/50992581
type: Question
linked to: http://stackoverflow.com/q/31306741
has body: I have the following dataframe, which looks like the below: df = pd.DataFrame({'fruit': ['berries','berries', 'berries', 'tropical', 'tropical','tropical','berries','nuts'], 'code': [100,100,100,200,200, 300,400,500], 'subcode': ['100A', '100B', '100C','200A', '200B','300A', '400A', '500A']}) code fruit subcode 0 100 berries 100A 1 100 berries 100B 2 100 berries 100C 3 200 tropica 200A 4 200 tropical 200B 5 300 tropical 300A 6 400 berries 400A 7 500 nuts 500A I want to transform the dataframe to this format: code fruit subcode1 subcode1 subcode1 0 100 berries 100A 100B 100C 3 200 tropica 200A 200B 5 300 tropical 300A 6 400 berries 400A 7 500 nuts 500A Unfortunately, I'm stuck as to how to proceed. I've consulted posts like, Unmelt Pandas DataFrame, and have combinations of stack and unstack. I suspect that some concatenation is involved, too. Would appreciate any advice to help point me in the right direction!
has title: how to transform dataframe so that column values are row values
answer count: 3
tagged with: pandas
downvote count: 0
tagged with: melt
has answer: http://stackoverflow.com/a/50992838
favorite count: 0

sympy
tags question: http://stackoverflow.com/q/50936279
tag name: sympy
tags question: http://stackoverflow.com/q/50903574
tags question: http://stackoverflow.com/q/50888655
tags question: http://stackoverflow.com/q/50971490
tags question: http://stackoverflow.com/q/50955699
tags question: http://stackoverflow.com/q/50919465
tags question: http://stackoverflow.com/q/50959348
type: Tag
tags question: http://stackoverflow.com/q/50904546
tags question: http://stackoverflow.com/q/50994300
tags question: http://stackoverflow.com/q/51003899

http://stackoverflow.com/a/50945143
type: Answer
answers question: http://stackoverflow.com/q/50945078
score: 2
accepted answer of: http://stackoverflow.com/q/50945078
downvote count: 0
type: AcceptedAnswer
has body: Use img.attrs["src"] Ex: from bs4 import BeautifulSoup s = """ Sample Image """ soup = BeautifulSoup(s, "html.parser") s = soup.find('div', {'class' : 'img-holder'}) print( s.img.attrs["src"] )
upvote count: 2

http://stackoverflow.com/comment/88852101
type: Comment
type: QuestionComment
has text: @SvenFestersen I did have a look at them but they both wait for the response because they print the status of the website.I don't even want to see whether the website is down or not.
score: 0
comment on: http://stackoverflow.com/q/50926267

http://stackoverflow.com/q/50994116
tagged with: tensorflow
type: Question
answer count: 1
has body: I am training a model in TensorFlow that works perfectly when I evaluate from the trained model. However, at various points, I am saving a checkpoint and then loading that checkpoint to run evaluations on it. The loaded network will just output NaNs. Using tfdbg and running the filter "has_inf_or_nan" when feeding input ends up showing the first NaNs in the network appearing in the moving_mean and moving_variance variables in one of the batch normalization layers. Saving is being done with the following code: with self.graph.as_default(): if not self.saver: self.saver = tf.train.Saver(tf.global_variables(), max_to_keep=10000) save_dir = create_save_dir(path, name) return self.saver.save(self.session, save_dir, global_step=iteration, write_meta_graph=True) Loading is being done with the following code: with self.graph.as_default(): save_dir = create_save_dir(load_dir, load_name) self.saver = tf.train.import_meta_graph(save_dir + "-" + str(iteration) + ".meta") self.saver.restore(self.session, save_dir + "-" + str(iteration)) self.input_layer = self.graph.get_tensor_by_name("network/input_layer:0") self.out_policy_layer = self.graph.get_tensor_by_name("network/out_policy_layer:0") self.out_value_layer = self.graph.get_tensor_by_name("network/out_value_layer/Tanh:0") self.is_training = self.graph.get_tensor_by_name("network/is_training:0") Again, the thing that has me suspecting some issue with my save/load routine is the fact that the network is outputting valid results if I run through the network that has been trained. I am only getting the NaNs when I run something through a network that was loaded. Editing to add that my batch norm is being created with the following code: def _conv_block(self, name, input_layer, filter_size, num_input_channels, num_output_channels): weights = self._create_weights_for_layer(f"{name}_weights", shape=[filter_size[0], filter_size[1], num_input_channels, num_output_channels], use_regularizer=self._config.l2_regularizer) conv = self._c…
accepted answer: http://stackoverflow.com/a/57530211
tagged with: batch-normalization
downvote count: 0
favorite count: 0
tagged with: machine-learning
tagged with: python
type: AnsweredQuestion
score: 3
has title: TensorFlow NaN in Output Only When Restoring Model
has answer: http://stackoverflow.com/a/57530211
upvote count: 3

http://stackoverflow.com/comment/88866185
has text: @Uueerdo You maybe correct, but the arg statement works even if you get rid of the double quotes on the last value. So I am not sure exactly. I currently have ('6','3') and it works fine as well.
comment on: http://stackoverflow.com/a/50933653
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/88944636
comment on: http://stackoverflow.com/q/50970652
type: QuestionComment
has text: What is `tldextract`? Looks like it may not have set up its logging correctly.
score: 0
type: Comment

http://stackoverflow.com/q/50902067
tagged with: tensorflow-lite
tagged with: pytorch
tagged with: tensorflow
upvote count: 12
has body: I'm developing a Tensorflow embedded application using TF lite on the Raspberry Pi 3b, running Raspbian Stretch. I've converted the graph to a flatbuffer (lite) format and have built the TFLite static library natively on the Pi. So far so good. But the application is Python and there seems to be no Python binding available. The Tensorflow Lite development guide (https://www.tensorflow.org/mobile/tflite/devguide) states "There are plans for Python bindings and a demo app." Yet there is wrapper code in /tensorflow/contrib/lite/python/interpreter_wrapper that has all the needed interpreter methods. Yet calling this from Python eludes me. I have generated a SWIG wrapper but the build step fails with many errors. There is no readme.md describing the state of the interpreter_wrapper. So, I wonder if the wrapper has worked for others and I should persist or is it fundamentally broken and I should look elsewhere (PyTorch)? Has anyone found a path to the TFLite Python bindings for the Pi3?
possible better answer: http://stackoverflow.com/a/51093144
has answer: http://stackoverflow.com/a/51093144
has answer: http://stackoverflow.com/a/50961731
type: AnsweredQuestion
downvote count: 0
tagged with: raspberry-pi3
favorite count: 0
has title: How to import the tensorflow lite interpreter in Python?
type: Question
score: 12
answer count: 2
tagged with: python
accepted answer: http://stackoverflow.com/a/50961731
linked to: http://stackoverflow.com/q/38646036

http://stackoverflow.com/comment/89337682
has text: Got it, thanks Charlie!
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50952548
score: 0

http://stackoverflow.com/q/50932821
has comment: http://stackoverflow.com/comment/92367118
favorite count: 0
has body: Pandoc doesn't render well HTML tables into docx documents. I get the content of a request, I render it using a template file. Then I use pypandoc like this: response = render( request, 'template.html', { "field1": f1, "field1": f2, } ) import pypandoc pypandoc.convert(source=response.content, format='html', to='docx', outputfile='output.docx') The template.html contains a table. In the docx file I get an table with its content separated below. Are there extra parameters to consider to solve this? Or maybe pandoc conversion doesn't support well tables yet? Are there any functional example? Maybe there is an easier way to do it? EDIT 1 I provide more concise example. Here is a testing python snippet: $ cat test-table.py #!/usr/bin/env python test_table = """ Table with colgroup and col Lime Lemon Orange Green Yellow Orange Fruit Fruit Fruit """ print("[test_table]") print(test_table) import pypandoc pypandoc.convert(source=test_table, format='html', to='docx', outputfile='test-table.docx') ## Write to html with open('test-table.html', 'w') as fh: fh.write(test_table) I open the html file: $ firefox test-table.html and get the following html page: which is good. I also get the following docx document: $ libreoffice test-table.docx Which is not good. I exported the docx file into a pdf file and got the following output: $ evince test-table.pdf Note that what we see in the images are the whole page, there is no scrolling possible. Date from the second column doesn't exist at all. Any ideas? EDIT 2 Pandoc has been installed in a conda environment: $ type pandoc pandoc is hashed (/home/kaligne/local/miniconda3/bin/pandoc) Pandoc version is: $ pandoc -v pandoc 2.2.1 Compiled with pandoc-types 1.17.4.2, texmath 0.11, skylighting 0.7.0.2 Default user data directory: /home/kaligne/.pandoc Copyright (C) 2006-2018 John MacFarlane Web: http://pandoc.org This is free software; see the source for copying conditions. There is no warranty, not even for merchantability or fitness for…
has comment: http://stackoverflow.com/comment/88864369
type: UnansweredQuestion
tagged with: python
answer count: 0
has title: convert html table to docx file with pypandoc
type: Question
score: 5
upvote count: 5
tagged with: pypandoc
has comment: http://stackoverflow.com/comment/113158135
has comment: http://stackoverflow.com/comment/88894096
downvote count: 0

http://stackoverflow.com/comment/88851476
type: Comment
comment on: http://stackoverflow.com/q/50926012
type: QuestionComment
score: 0
has text: It is basically a RabbitMQ topic exchange principle.

http://stackoverflow.com/a/50981345
has body: git://github.com is not an SSH URL, it is a Git-protocol URL. Try git config --global url."git@github.com/".insteadOf git://github.com/ Any git://github.com/ will be replaced by the SSH URL git@github.com/...
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50976162

http://stackoverflow.com/q/50888226
type: Question
tagged with: dataframe
has answer: http://stackoverflow.com/a/50888362
score: 0
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/50888238
accepted answer: http://stackoverflow.com/a/50888238
has title: Add a list per index value in DataFrame in Pandas
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50888362
has comment: http://stackoverflow.com/comment/88777799
has body: Please help my out. How is it possible to create a new column in a DataFrame and join a list of values for every index available in a DataFrame? For example, i have a df with index values: i1 i2 i3 and a list: ls = ['asd', 'qwe', 'zxc'] I'd like to update the df to look like this: i1 asd i1 qwe i1 zxc i2 asd i2 qwe i2 zxc i3 asd i3 qwe i3 zxc Thanks!

http://stackoverflow.com/comment/89058823
has text: No, it was an edit mistake but it didn't change anything anyway. I'm still stuck and I tried to close the file after writing, it didn't work either
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51032294

http://stackoverflow.com/q/50990740
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/c
type: Question
has body: I'm using a library in C that works with a callback as a parameter, see this super simple example: #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include "axgmb.h" void callback(interrupt_handler pointer) { printf("*****[APP]%lx , %lx\n", pointer.data, pointer.value); } int main(void) { AXGMB_DIO_Open(); AXGMB_DIO_interruptHandler(callback); sleep(1); AXGMB_DIO_Close(); return ERR_Success; }; interrupt_handler is a structure like this: typedef struct interrupt_handler{ unsigned long unsigned long unsigned long unsigned long }interrupt_handler; I'm trying to use it with Python 2.7, so far I wrote this: mydll = windll.LoadLibrary("AGP2_API.dll") @c.CFUNCTYPE(None, c.c_char_p) def callBackTest(a): print("Test call back "+str(a)) iRet=mydll.AXGMB_DIO_Open() mydll.AXGMB_DIO_interruptHandler(callBackTest) time.sleep(10) mydll.AXGMB_DIO_Close() It works, in the sense that the call back is called correctly, but I'm not able to get the right data I need to, I wrote just str(a) to see if something comes out. I have to use struct to read the data but I have no clue, I come up with something like this but not sure, and not sure how to use it: class testStruct(Structure): _fields_ = [('val1', c_longdouble), ('val2', c_longdouble), ('val3', c_longdouble), ('val4', c_longdouble)]
has comment: http://stackoverflow.com/comment/89000103
tagged with: python-2.7
score: 0
has title: callback function with pointer
tagged with: python
has comment: http://stackoverflow.com/comment/89000083
answer count: 0

http://stackoverflow.com/q/50893437
has answer: http://stackoverflow.com/a/70983333
tagged with: django
upvote count: 7
type: Question
accepted answer: http://stackoverflow.com/a/50894284
has body: This isn't really a complex problem (to my knowledge). I know in MongoDB you can feed in a string and it automatically tokenizes and performs full-text search using that string as a query. However, in Django, I have yet to find similar functionality, and all of the examples I've seen have done something along the lines of: from django.contrib.postgres.search import SearchQuery query = SearchQuery('foo') Is the reason people only use one word because SearchQuery can only use one word? What I want to know is how to perform full-text search with multiple words. Is it as easy as doing from django.contrib.postgres.search import SearchQuery query = SearchQuery('foo and also bar') ? Or does it need to be more complicated than that?
score: 7
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/50893495
favorite count: 0
has title: Django Full-Text Search with multiple words
tagged with: postgresql
tagged with: python
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/47377947
has answer: http://stackoverflow.com/a/50894284
possible better answer: http://stackoverflow.com/a/70983333

http://stackoverflow.com/comment/88988447
comment on: http://stackoverflow.com/q/50996633
score: 0
type: Comment
type: QuestionComment
has text: @blhsing it still returns the same thing :/

http://stackoverflow.com/a/50961886
type: Answer
answers question: http://stackoverflow.com/q/50961773
upvote count: 1
has body: Good start! You need to do it like this and it will work: res = es.search(index="demo",body={ "from": 0, "size": 0, "query": { "match_all": {} }, "aggs": { "date_avg": { "date_histogram": { "field": "datetime", "interval": "year" }, "aggs": { "avg_a": { "avg": { "field": "field.a" } }, "avg_b": { "avg": { "field": "field.b" } }, "avg_c": { "avg": { "field": "field.c" } } } } } })
accepted answer of: http://stackoverflow.com/q/50961773
type: AcceptedAnswer
downvote count: 0
score: 1

http://stackoverflow.com/q/50975025
linked to: http://stackoverflow.com/q/12714415
answer count: 3
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
downvote count: 1
has title: Pandas "read_csv" Function Returns NAN for All Cells in My Table
favorite count: 0
has answer: http://stackoverflow.com/a/56225753
has answer: http://stackoverflow.com/a/78395589
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/138209052
has body: My original CSV file has float values in each cell but after I use pd.read_csv() to read the file, it returns me a blank table. I tried to set the delimiter and the encoding of the function but it didn't help at all. The CSV file is automatically generated by a software and I have no way check the settings of the settings. Is there any way I can read my file to a dataframe with correct values? >>> pd.read_csv('./HISTORY_LOG_05-31-2018.CSV') D Unnamed: 1 Unnamed: 2 ... Unnamed: 108 Unnamed: 109 Unnamed: 110 0 NaN NaN NaN ... NaN NaN NaN 1 NaN NaN NaN ... NaN NaN NaN 2 NaN NaN NaN ... NaN NaN NaN 3 NaN NaN NaN ... NaN NaN NaN 4 NaN NaN NaN ... NaN NaN NaN 5 NaN NaN NaN ... NaN NaN NaN [6 rows x 111 columns] I simplified the CSV file to A,B 0.000,0.000 0.000,0.000 and I still got results like: >>> pd.read_table('./HISTORY_LOG_05-31-2018.CSV', encoding="cp1252") D 0 NaN 1 NaN 2 NaN >>> pd.read_table('./HISTORY_LOG_05-31-2018.CSV', encoding="cp1252", delimiter=",") D Unnamed: 1 0 NaN NaN 1 NaN NaN 2 NaN NaN
has comment: http://stackoverflow.com/comment/138209162
score: 7
has answer: http://stackoverflow.com/a/71373669
linked to: http://stackoverflow.com/q/2398393
upvote count: 8
type: Question
has comment: http://stackoverflow.com/comment/88951041

http://stackoverflow.com/q/50859987
type: Question
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/50860007
possible better answer: http://stackoverflow.com/a/50860037
tagged with: processing-efficiency
downvote count: 0
has answer: http://stackoverflow.com/a/50860037
favorite count: 0
tagged with: python-3.x
tagged with: http://stackoverflow.com/tag/csv
has title: Efficient way to get group names in pandas
score: 6
tagged with: python
upvote count: 6
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50860007
has body: I have a .csv file with around 300,000 rows. I have set it to group by a particular column, with each group having around 140 members (2138 total groups). I am trying to generate a numpy array of the group names. I have used a for loop to generate the names as of now but it takes a while for everything to process. import numpy as np import pandas as pd df = pd.read_csv('file.csv') grouped = df.groupby('col1') group_names = [] for name,group in grouped: group_names.append(name) group_names = np.array(group_names, dtype=object) I am wondering if there is a more efficient way to do this, whether by using a pandas module or directly converting the names into a numpy array.

http://stackoverflow.com/a/50948766
type: Answer
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/50945375
has body: As the documentation states, the data points x and y need to define a curve y = f(x). That means: For every point in x there needs to be exactly one point in y. Take e.g. this data of sin(x): Every point in x has exactly one point in y, and the 1d splinefit works well. Now take (something like) your proposed data in comparison: Every point in x appears two times, and, even worse, with two different values in y. Therefore, this data is invalid.
has comment: http://stackoverflow.com/comment/88923296
accepted answer of: http://stackoverflow.com/q/50945375
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/88963326
score: 0
has text: @PeterWood for items in file also didn't work. I got this message in python console "Process finished with exit code 247"
comment on: http://stackoverflow.com/q/50983903
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50863647
type: Answer
has body: If I understand correctly, you can extract what you need (numbers) with a regex, and do your calculations on the result: salaries = (df['Salary Offered'] .str.replace(',','') .str.findall(r'(\d+\.?\d+)') .apply(lambda x: pd.Series(x).astype(float)) .mean(1)) &gt;&gt;&gt; salaries 0 18323.0 1 20000.0 2 NaN 3 16000.0 4 41000.0 5 9126.0 6 9.7 7 37500.0 8 24800.0 9 21500.0 regex explanation: \d finds any digit character. \d+ finds any sequence of multiple digits (+ means one or more in regex). \.? means "optionally, find any .". So all together, \d+\.?\d+ says: "find any sequence of digits, optionally followed by a . and another sequence of digits on the other side of that .". dealing with the per hour vs per annum I'm not sure what you mean to do about the per hour rows, but you said that you can do it intuitively, so I suppose you have a plan for it. Personally, I would do something along the lines of the following, though you might have to tweak it based on your dataframe and what you're trying to capture specifically. salaries = (df['Salary Offered'] .str.replace(',','') .str.findall(r'(\d+\.?\d+)') .apply(lambda x: pd.Series(x).astype(float)) .mean(1) .to_frame('salary offered')) salaries['per'] = df['Salary Offered'].str.extract(r'(per\s\w+)') &gt;&gt;&gt; salaries salary offered per 0 18323.0 per annum 1 20000.0 per annum 2 NaN NaN 3 16000.0 per annum 4 41000.0 per annum 5 9126.0 per annum 6 9.7 per hour 7 37500.0 per annum 8 24800.0 per annum 9 21500.0 per annum
has comment: http://stackoverflow.com/comment/88746833
has comment: http://stackoverflow.com/comment/88752043
has comment: http://stackoverflow.com/comment/88730342
answers question: http://stackoverflow.com/q/50863504
upvote count: 4
downvote count: 0
score: 4

http://stackoverflow.com/q/50982003
has answer: http://stackoverflow.com/a/50982256
tagged with: multithreading
type: Question
type: AnsweredQuestion
has body: I am learning PyQT and Multithreading, and I think I need help here. In my code, I have a a class Tool, and a thread TaskThread. From the thread, I call the function dummy_function which perform a proccess being displayed in the GUI by a progress-bar. When dummy_function finishes, I want to print a message in the GUI, by calling self.outputText.setText("Hello"). However, I get the following error: AttributeError: 'TaskThread' object has no attribute 'outputText' Code: import sys import datetime import time from PyQt4 import QtCore, QtGui, uic from PyQt4.QtCore import * from PyQt4.QtGui import * # Link to GUI qtCreatorFile = "GUInterface.ui" Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile) def time_converter_to_unix(start_datetime, end_datetime): # Convert QTimeEdit to UNIX Timestamp (int, msec included), and then to float start_datetime_unix_int = start_datetime.toMSecsSinceEpoch () start_datetime_unix = (float(start_datetime_unix_int) / 1000) end_datetime_unix_int = end_datetime.toMSecsSinceEpoch () end_datetime_unix = (float(end_datetime_unix_int) / 1000) return start_datetime_unix, end_datetime_unix def dummy_function(self, start_datetime_unix, end_datetime_unix): # Dummy function, just to simulate a task. It takes parameters just for testing. result = start_datetime_unix * end_datetime_unix # Pre-steps for mapping from one range to other (progress-bar) OldMax = 99999 OldMin = 1 NewMax = 100 NewMin = 1 OldRange = (OldMax - OldMin) NewRange = (NewMax - NewMin) u = 1 for i in range (OldMax): u = i*2 OldValue = i print OldValue NewValue = (((OldValue - OldMin) * NewRange) / OldRange) + NewMin print "NEW VALUE: ", NewValue self.emit(QtCore.SIGNAL('CPU_VALUE'), NewValue) self.outputText.setText("Hello") class Tool(QtGui.QMainWindow, Ui_MainWindow): def __init__(self, parent = None): # Setting-ip UI QtGui.QMainWindow.__init__(self) Ui_MainWindow.__init__(self) self.setupUi(self) # Button Action self.runButton.clicked.connect(self.onStart) # Progress Bar and L…
accepted answer: http://stackoverflow.com/a/50982256
tagged with: pyqt
answer count: 1
tagged with: python-multithreading
tagged with: python
has title: Python - Parents and Multithreading issues
score: 0

http://stackoverflow.com/comment/88878473
has text: Ops! When I start writing my answer then there is no answer in this question.That's why I haven't noticed his answer.
comment on: http://stackoverflow.com/a/50940270
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/88950545
has text: @Aran-Fey: and using generators to communicate about a process that has side effects is very effective too. Your generalisation doesn't hold, sorry.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50977130

http://stackoverflow.com/comment/88834550
type: Comment
type: QuestionComment
has text: Meanwhile, if you're using `gyp`, AFAIK that's a dead project which doesn't support Python 3 and never will, which means installing Python 3.6 isn't going to help. Either use Apple's Python 2.7, or install another Python 2.7 instead. IIRC, for the former, it should be as simple as `npm install --python=python2.7`. But if you search for help on that, instead of help on Python installations that you didn't actually need to do, you'll probably find better information.
score: 2
comment on: http://stackoverflow.com/q/50917156

http://stackoverflow.com/q/50966412
score: -3
has comment: http://stackoverflow.com/comment/88933747
has title: Remove blank spaces from scanned photos
accepted answer: http://stackoverflow.com/a/50968747
has comment: http://stackoverflow.com/comment/88931248
answer count: 1
favorite count: 0
has body: I am browsing for days now to find a solution to this problem. No existing solution has worked yet. Here is my problem : I scan photos, on which there are some blank spaces (that can be anywhere (top, right, left, bottom)). I would like to adjust theses photos by removing the blank spaces. Here is an example (there's no white square on this original photo, that's just for anonymity) : Here is the original photo. Here, I've highlighted what I want to suppress. And here is what I expect to be the result. I use OpenCV to do that (Python version) but if you have a solution with another program, no problem! Has anyone found a solution about how to perform that ? Thank you. Have a great day !
tagged with: python
has comment: http://stackoverflow.com/comment/88929622
tagged with: opencv
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88933317
has answer: http://stackoverflow.com/a/50968747
tagged with: photos
downvote count: 3
type: Question
has comment: http://stackoverflow.com/comment/88933791
has comment: http://stackoverflow.com/comment/88932613
tagged with: edges
upvote count: 0

http://stackoverflow.com/a/50937366
has comment: http://stackoverflow.com/comment/88873234
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/50937334
accepted answer of: http://stackoverflow.com/q/50937334
type: AcceptedAnswer
downvote count: 0
has body: It sounds like you're just asking how to store a value in a variable: attack_result = player.attack(boss) if attack_result == 'mercy': # etc. elif attack_result in ('heal, no_mercy'): # etc. elif attack_result == 'attack': # etc. This way, instead of calling player.attack(boss) over and over, we just call it once, and then use the result over and over. While we're at it, as pointed out by David in a comment, in ('heal, no_mercy') probably isn't testing what you wanted. 'heal, no_mercy' is a single string. So ('heal, no_mercy') is a single string wrapped in meaningless parentheses. It's very different from ('heal', 'no_mercy'), which is a pair of strings. What you've written will do a substring search—which will actually be true for heal and no_mercy, but also for mercy and al and any other substring. You probably want to change it to: elif attack_result in ('heal', 'no_mercy'):
type: Answer

http://stackoverflow.com/q/50974425
has title: Getting NotImplementedError when using data from dask when running an OLS regression
tagged with: statsmodels
type: Question
has body: What I want to do is actually pretty simple. I want to run a OLS regression by using data from dask. It is fine, if I just install data into dask dataframe or I use pandas (but I get memory error when I use Pandas). # import modules import statsmodels.formula.api as smf import dask.dataframe as dd df = dd.read_csv(input_file) mod = smf.ols(formula='lnq ~ lnp + lnp:C(product_code)+ C(product_code)', data=df) results = mod.fit(cov_type = 'cluster', cov_kwds={'groups': df['product_code']}) print(results.summary()) However, I get the following error: File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 710, in runfile execfile(filename, namespace) File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 101, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "H:/yoox_3.py", line 11, in &lt;module&gt; mod = smf.ols(formula='lnq ~ lnp + lnp:C(product_code)+ C(product_code)', data=df) File "C:\ProgramData\Anaconda3\lib\site-packages\statsmodels\base\model.py", line 155, in from_formula missing=missing) File "C:\ProgramData\Anaconda3\lib\site-packages\statsmodels\formula\formulatools.py", line 68, in handle_formula_data NA_action=na_action) File "C:\ProgramData\Anaconda3\lib\site-packages\patsy\highlevel.py", line 310, in dmatrices NA_action, return_type) File "C:\ProgramData\Anaconda3\lib\site-packages\patsy\highlevel.py", line 165, in _do_highlevel_design NA_action) File "C:\ProgramData\Anaconda3\lib\site-packages\patsy\highlevel.py", line 70, in _try_incr_builders NA_action) File "C:\ProgramData\Anaconda3\lib\site-packages\patsy\build.py", line 696, in design_matrix_builders NA_action) File "C:\ProgramData\Anaconda3\lib\site-packages\patsy\build.py", line 448, in _examine_factor_types done = cat_sniffers[factor].sniff(value) File "C:\ProgramData\Anaconda3\lib\site-packages\patsy\categorical.py", line 204, in sniff for value in data: File "C:\ProgramData\Anaconda3\lib\site-packages\…
score: 0
answer count: 1
tagged with: dask
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50989348
tagged with: python

http://stackoverflow.com/q/50948859
accepted answer: http://stackoverflow.com/a/50950762
type: Question
tagged with: multiprocessing
has title: Gracefully stopping python daemon with child proceses
answer count: 1
tagged with: asynchronous
tagged with: daemon
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50950762
has body: I'm trying to implement a python daemon in the traditional start/stop/restart style to control a consumer to a messaging queue. I've successfully used python-daemons to create a single consumer, but I need more than one listener for the volume of messages. This led me to implement the multiprocessing library in my run function along with a os.kill call for the stop function: def run(self): for num in range(self.num_instances): p = multiprocessing.Process(target=self.start_listening) p.start() def start_listening(self): with open('/tmp/pids/listener_{}.pid'.format(os.getpid()), 'w') as f: f.write("{}".format(os.getpid())) while True: // implement message queue listener def stop(self): for pid in os.listdir('/tmp/pids/'): os.kill(int(os.path.basename(pid)), signal.SIGTERM) shutil.rmtree('/tmp/pids/') super().stop() This is almost ok, but I'd really like to have a graceful shutdown of the child processes and do some clean up which would include logging. I read about signal handlers so I switched the signal.SIGTERM to signal.SIGINT and added a handler to the daemon class. def __init__(self): .... signal.signal(signal.SIGINT, self.graceful_stop) def stop(self): for pid in os.listdir('/tmp/pids/'): os.kill(int(os.path.basename(pid)), signal.SIGINT) super().stop() def graceful_stop(self): self.log.deug("Gracefully stopping the child {}".format(os.getpid())) os.rm('/tmp/pids/listener_{}.pid".format(os.getpid())) ... However, when tested, the child processes get killed but it doesn't seem like the graceful_stop function never gets called (files remain, logging doesn't get logged, etc). Am I implementing the handler wrong for the child processes? Is there a better way of having multiple listeners with a single control point?
tagged with: python
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/88999277
has text: [How to run a function on all Spark workers before processing data in PySpark?](https://stackoverflow.com/q/37343437/8371915) and [How can I load data that can't be pickled in each Spark executor?](https://stackoverflow.com/q/35500196/8371915) should be useful for you.
comment on: http://stackoverflow.com/q/51001480
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/a/50927123
downvote count: 1
upvote count: 0
score: -1
has body: import pandas as pd from xml.etree import ElementTree as xml df = pd.read_csv("file_path") csv_data = df.values root = xml.Element("TariffRecords") tariff = xml.subelement("Tariff", root) for index, data in enumarate(csv_data): row = xml.Element("A"+str(index), tariff) row.set(str(data))
type: Answer
answers question: http://stackoverflow.com/q/50926595

http://stackoverflow.com/comment/88861957
has text: If you can't install any packages, then you will not be able to access Oracle from python. With that said, WHY can't you install any packages? If it is a company policy, you must point out to them that they are asking you to do the impossible.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50931375

http://stackoverflow.com/a/53081544
has body: I had the same problem today. So I simply build my own method assertDictAlmostEqual. def assertDictAlmostEqual(self, d1, d2, msg=None, places=7): # check if both inputs are dicts self.assertIsInstance(d1, dict, 'First argument is not a dictionary') self.assertIsInstance(d2, dict, 'Second argument is not a dictionary') # check if both inputs have the same keys self.assertEqual(d1.keys(), d2.keys()) # check each key for key, value in d1.items(): if isinstance(value, dict): self.assertDictAlmostEqual(d1[key], d2[key], msg=msg) else: self.assertAlmostEqual(d1[key], d2[key], places=places, msg=msg)
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/50935269
score: 2
downvote count: 0

eclipse
tag name: eclipse
tags question: http://stackoverflow.com/q/51005155
tags question: http://stackoverflow.com/q/50951077
type: Tag

http://stackoverflow.com/comment/88821570
comment on: http://stackoverflow.com/a/50910732
type: AnswerComment
type: Comment
score: 0
has text: How could you specify the attribute other than a string?

http://stackoverflow.com/comment/88919904
score: 1
type: AnswerComment
type: Comment
has text: @Dark yup. I'll keep this one here because of the little primer on arrays :)
comment on: http://stackoverflow.com/a/50961402

http://stackoverflow.com/comment/88748090
type: Comment
type: QuestionComment
has text: Also if you're using strings, include them in quotes either `'` or `"`.
comment on: http://stackoverflow.com/q/50873118
score: 0

http://stackoverflow.com/a/64513803
downvote count: 0
has body: For Windows users only: Install tesseract using: pip install tesseract and then add this line to your code, mind the "\" pytesseract.pytesseract.tesseract_cmd = "C:\Program Files (x86)\Tesseract-OCR\\tesseract.exe"
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50951955

http://stackoverflow.com/q/51004972
has body: I'm using python and Visual Studio Code for scripting inside ANSA and VisIt. These two applications both have built-in classes and functions/methods that Visual Studio Code cannot see. Therefore IntelliSense doesn't help me with calls to built-ins. What is the recommended way to give Visual Studio Code information about built-in classes and functions/methods. In Typescript there is .d.ts files; is there anything similar for python?
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/59892611
has title: Make VSCode know about application built-ins
score: 1
upvote count: 1
tagged with: intellisense
type: Question
tagged with: visual-studio-code
accepted answer: http://stackoverflow.com/a/59892611
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/88826945
has text: You can edit it into the body of your question here then
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50912638

http://stackoverflow.com/comment/88870081
type: QuestionComment
has text: @MarcosViníciusdaSilva here is the DEBUG of the error to help more, https://pastebin.com/jTnBdtSM
score: 0
comment on: http://stackoverflow.com/q/50918102
type: Comment

parallel-processing
tags question: http://stackoverflow.com/q/50923323
tags question: http://stackoverflow.com/q/50912844
tags question: http://stackoverflow.com/q/50934443
tags question: http://stackoverflow.com/q/50958259
tags question: http://stackoverflow.com/q/50979373
tags question: http://stackoverflow.com/q/50901313
type: Tag
tag name: parallel-processing
tags question: http://stackoverflow.com/q/50855076
tags question: http://stackoverflow.com/q/50878960
tags question: http://stackoverflow.com/q/50955427
tags question: http://stackoverflow.com/q/50861098

http://stackoverflow.com/q/50899901
type: Question
score: 3
has answer: http://stackoverflow.com/a/50900636
has title: plotting a vbar_stack using a dataframe
tagged with: pandas
answer count: 1
downvote count: 0
has body: I'm struggling to get a stacked vbar working. With python/pandas and bokeh I want to plot several statistics about the players of a football team. The dataframe is nicely filled, the values are a string where they should be an int where it should be a numeric value. I used the sample of bokeh to try and adjust it for my purpose, but I'm stuck on 'ValueError: Keyword argument sequences for broadcasting must be the same length as stackers' this error. My code (without imports and scraping pieces) is: source = ColumnDataSource(data=statsdfsource'goals','assists','naam') p = figure(plot_height=250, title="Fruit Counts by Year", toolbar_location=None, tools="") p.vbar_stack(['goals','assists'], x='naam', width=0.9, color=colors, source=source) p.y_range.start = 0 p.x_range.range_padding = 0.1 p.xgrid.grid_line_color = None p.axis.minor_tick_line_color = None p.outline_line_color = None p.legend.location = "top_left" p.legend.orientation = "horizontal" show(p) The dataframe I fill the columndatasource with is goals assists naam 0 NaN NaN Miguel Santos 1 NaN NaN Aykut Özer 2 NaN NaN Job van de Walle 3 NaN NaN Rowen Koot 4 8.0 6.0 Perr Schuurs 5 4.0 2.0 Wessel Dammers 6 12.0 2.0 Stefan Askovski 7 1.0 NaN Mica Pinto 8 NaN NaN Christopher Braun 9 1.0 4.0 Marco Ospitalieri 10 NaN 1.0 Clint Esser The result I want to reach is a stacked columnframe, where on the x-axis is the name of the player, with 2 columns above it, one with the goals the player made and one with the assists. I think I'm messing up somewhere with how my dataframe is built, but I'm a bit floating how it should be formed (can't really imagine on the other hand that the dataframe doesn't fit the purpose).
favorite count: 0
accepted answer: http://stackoverflow.com/a/50900636
tagged with: python
type: AnsweredQuestion
upvote count: 3
tagged with: bokeh

http://stackoverflow.com/a/50956866
upvote count: 4
score: 4
accepted answer of: http://stackoverflow.com/q/50956835
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50956835
type: Answer
has body: You were close - just use the reversed list iterators: &gt;&gt;&gt; list(zip(*[reversed(y) for y in Y]))[0] (200, 509, 529, 561, 637) Or, more directly, a list comprehension: [y[-1] for y in Y]

http://stackoverflow.com/comment/88939566
score: 0
type: AnswerComment
has text: Hi, exactly, i double clicked into the cert, and I made sure it was "always trust". Just to confirm, I also confirmed the cert by opening a web page on the 3rd party server in Safari (if cert isn't trusted, Safari won't return the test web page)
type: Comment
comment on: http://stackoverflow.com/a/50966925

http://stackoverflow.com/comment/88732657
has text: Using `eval` *programmatically* on repr is a horrible idea. More it's about "let's copy-paste this into a REPL and tweak it", at which point the `<...>` convention starts to matter.
type: Comment
score: 1
comment on: http://stackoverflow.com/a/50865045
type: AnswerComment

outliers
tags question: http://stackoverflow.com/q/50950019
type: Tag
tag name: outliers
tags question: http://stackoverflow.com/q/50904088
tags question: http://stackoverflow.com/q/51006163
tags question: http://stackoverflow.com/q/50879242

http://stackoverflow.com/q/50966244
accepted answer: http://stackoverflow.com/a/50973285
tagged with: python
tagged with: qudpsocket
type: AnsweredQuestion
tagged with: pyqt5
type: Question
has answer: http://stackoverflow.com/a/50973285
has body: def main(): app = QCoreApplication([]) local_ip = QHostAddress('192.168.43.126') port = 2359 udp_socket = QUdpSocket() b = QByteArray() b.append('i0000,0000') udp_socket.writeDatagram(b, QHostAddress('192.168.43.1'), port) udp_socket.bind(QHostAddress('192.168.43.126'),port) while True: #print('in the while loop') while udp_socket.hasPendingDatagrams(): #print('has pending datadrams ') s = udp_socket.readDatagram(10) print(s) app.exec_() if __name__ == '__main__': main() this i snot working the Socket is not binding to the port i don't knew why i need to make the server waits for a message but not using signals
has title: PyQt5 QUdpSocket not binding to address and a port
score: 0
answer count: 1

http://stackoverflow.com/q/50878631
tagged with: dlopen
has body: The problem I'm facing is as follow: I generate a shared object called customkinetics.so from a f90 file I use this object in a Cantera (chemistry code) written in C++ with a python interface. The object is called in a subroutine (CustomKinetics.cpp) as follow: #include "cantera/kinetics/CustomKinetics.h" #include &lt;iostream&gt; #include &lt;dlfcn.h&gt; using namespace std; namespace Cantera { //Fortran External Routine extern "C" { void customkinetics_(doublereal* P, doublereal* T, doublereal* rho, const doublereal* m_y, doublereal* wdot); } CustomKinetics::CustomKinetics(thermo_t* th) : GasKinetics(th) { printf("WARNING: Using customized kinetics from f90 file.\n"); // Closing the library if it has already been opened if (handle == NULL){ dlclose(handle); } handle = dlopen("customkinetics.so", RTLD_LAZY | RTLD_LOCAL); // load symbol ck = (ck_t) dlsym(handle, "customkinetics_"); } void CustomKinetics::get_wdot_custom(doublereal* wdot) { doublereal P = thermo().pressure(); doublereal T = thermo().temperature(); doublereal rho = thermo().density(); const doublereal* m_y = thermo().massFractions(); // calculation ck(&amp;P,&amp;T,&amp;rho,&amp;m_y[0],&amp;wdot[0]); } } It works fine until I overwrite the .f90 file that i then compile again thus overwriting the .so and then when I call it again I actually call the first object. I know dlclose() is not supposed to completely remove the object from the memory but is there any way to do so ? The fortran Makefile: customkinetics.so: customkinetics.f90 gfortran -c customkinetics.f90 -g -fPIC -o customkinetics.o gfortran -shared -o customkinetics.so customkinetics.o
has answer: http://stackoverflow.com/a/50880238
type: UnansweredQuestion
has title: Unload shared object (.so file) opened with dlopen() in C++
tagged with: python
tagged with: c++
tagged with: cantera
tagged with: fortran
type: Question
score: 0
answer count: 1

http://stackoverflow.com/q/50930300
upvote count: 1
tagged with: python
answer count: 1
tagged with: conv-neural-network
has title: Training Error in PyTorch - RuntimeError: Expected object of type FloatTensor vs ByteTensor
has answer: http://stackoverflow.com/a/50930566
tagged with: image
has body: A minimal working sample will be difficult to post here but basically I am trying to modify this project http://torch.ch/blog/2015/09/21/rmva.html which works smoothly with MNIST. I am trying to run it with my own dataset with a custom dataloader.py as below: from __future__ import print_function, division #ds import numpy as np from utils import plot_images import os #ds import pandas as pd #ds from skimage import io, transform #ds import torch from torchvision import datasets from torch.utils.data import Dataset, DataLoader #ds from torchvision import transforms from torchvision import utils #ds from torch.utils.data.sampler import SubsetRandomSampler class CDataset(Dataset): def __init__(self, csv_file, root_dir, transform=None): """ Args: csv_file (string): Path to the csv file with annotations. root_dir (string): Directory with all the images. transform (callable, optional): Optional transform to be applied on a sample. """ self.frame = pd.read_csv(csv_file) self.root_dir = root_dir self.transform = transform def __len__(self): return len(self.frame) def __getitem__(self, idx): img_name = os.path.join(self.root_dir, self.frame.iloc[idx, 0]+'.jpg') image = io.imread(img_name) # image = image.transpose((2, 0, 1)) labels = np.array(self.frame.iloc[idx, 1])#.as_matrix() #ds #landmarks = landmarks.astype('float').reshape(-1, 2) #print(image.shape) #print(img_name,labels) sample = {'image': image, 'labels': labels} if self.transform: sample = self.transform(sample) return sample class ToTensor(object): """Convert ndarrays in sample to Tensors.""" def __call__(self, sample): image, labels = sample['image'], sample['labels'] #print(image) #print(labels) # swap color axis because # numpy image: H x W x C # torch image: C X H X W image = image.transpose((2, 0, 1)) #print(image.shape) #print((torch.from_numpy(image))) #print((torch.from_numpy(labels))) return {'image': torch.from_numpy(image), 'labels': torch.from_numpy(labels)} def get_train_valid_loader(data_dir, batch_…
downvote count: 0
score: 1
accepted answer: http://stackoverflow.com/a/50930566
type: AnsweredQuestion
favorite count: 0
tagged with: tensor
tagged with: pytorch
type: Question

http://stackoverflow.com/a/50927880
has body: Using the csv module and an iterable of dictionaries L: import csv L = [{'day': 1, 'temperature': 30}, {'day': 2, 'temperature': 40}] with open(r'c:\temp\out.csv', 'w', newline='') as f: wr = csv.writer(f) wr.writerow(['day', 'temperature']) for item in L: wr.writerow([item['day'], item['temperature']]) Result: day,temperature 1,30 2,40
score: 3
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/50925340
type: Answer

http://stackoverflow.com/comment/88911562
comment on: http://stackoverflow.com/a/50957016
score: 0
type: Comment
type: AnswerComment
has text: I tried this, however I got error 500 (internal server error) on my website when submitted the form that gets inputed_email. Why is this?

http://stackoverflow.com/q/50935610
score: 0
answer count: 1
tagged with: python-2.6
has comment: http://stackoverflow.com/comment/88870003
has body: I rewrote the following Python 2.7+ code as follows for Python 2.6. Python 2.7+ options = {key: value for key, value in options.items() if value is not None} Python 2.6 options = dict((key, value) for key, value in options.items() if value is not None) But I am getting the following error SyntaxError: Generator expression must be parenthesized if not sole argument What did I do wrong?
tagged with: python
has comment: http://stackoverflow.com/comment/88870642
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88871242
has comment: http://stackoverflow.com/comment/88872060
has comment: http://stackoverflow.com/comment/88869911
has comment: http://stackoverflow.com/comment/88869908
has title: Python 2.6 Generator expression must be parenthesized if not sole argument
has answer: http://stackoverflow.com/a/68964073
type: Question

tcp
type: Tag
tags question: http://stackoverflow.com/q/50893815
tags question: http://stackoverflow.com/q/50962259
tags question: http://stackoverflow.com/q/50989064
tags question: http://stackoverflow.com/q/50878441
tag name: tcp

http://stackoverflow.com/a/50863820
has body: Yes, print is the culprit. The most interesting part of the exception is this: def getvalue(self): result = _SpoofOut.getvalue(self) if encoding: result = result.decode(encoding) local/lib/python2.7/site-packages/_pytest/doctest.py:509: pytest tries to decode unicode, so Python tries to encode it first — and fails. I think this is a bug in pytest: it should test if result is bytes or unicode: if encoding and isinstance(result, bytes): result = result.decode(encoding) Please report it to pytest issue tracker. You can test the fix and if it works you can send a pull request.
upvote count: 2
score: 2
accepted answer of: http://stackoverflow.com/q/50860112
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88731216
answers question: http://stackoverflow.com/q/50860112
type: Answer

http://stackoverflow.com/comment/109996092
score: 0
type: Comment
type: QuestionComment
has text: Run "pipenv lock", it works for me.
comment on: http://stackoverflow.com/q/50865274

http://stackoverflow.com/q/51000500
tagged with: nameerror
has answer: http://stackoverflow.com/a/51000526
has answer: http://stackoverflow.com/a/51000524
score: 0
type: UnansweredQuestion
tagged with: python
has title: Name Error: Global name 'r' is not defined
type: Question
answer count: 2
has body: Ive been working on this sample code for a while and cant seem to wrap my head around this seemingly simple error. The code is as follows: class area : r=5 l=2 b=3 def __init__(self,r,l,b): print "parent constructor" self.r=r self.l=l self.b=b def __del__(self): print "parent deconstructor" def circle(self): circle_area= 3.14 * r * r print "area of circle is :",circle_area def rectangle(self): rect_area=l*b print "area of rectangle :",rect_area obj=area(4,5,4) obj2=area(2,5,4) obj.circle() The error message says : File "yaa.py", line 18, in circle circle_area= 3.14 * r * r NameError: global name 'r' is not defined.

http://stackoverflow.com/a/51001658
has comment: http://stackoverflow.com/comment/89007804
has body: You can find the four extreme points in a contour the following way: First, finding contours for a given image. I considered the following image for this illustration: (Skipping the contour finding section) cnt = contours[0] #--- since there is only one contour in the image leftmost = tuple(cnt[cnt[:,:,0].argmin()][0]) rightmost = tuple(cnt[cnt[:,:,0].argmax()][0]) topmost = tuple(cnt[cnt[:,:,1].argmin()][0]) bottommost = tuple(cnt[cnt[:,:,1].argmax()][0]) #--- drawing these points on the image ---- cv2.circle(im2, leftmost, 6, (0, 0, 255), -1) cv2.circle(im2, rightmost, 6, (0, 0, 255), -1) cv2.circle(im2, topmost, 6, (0, 255, 0), -1) cv2.circle(im2, bottommost, 6, (0, 255, 0), -1) cv2.imshow('final', im2)
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/51000056
type: Answer
downvote count: 0

http://stackoverflow.com/comment/88968023
comment on: http://stackoverflow.com/q/50986671
type: QuestionComment
type: Comment
score: 1
has text: Why do you add `" client:AP"` to the response? Slso, why ddo you mention "File" in the question title? Is this pertinent?

http://stackoverflow.com/q/50949692
upvote count: 1
tagged with: arrays
favorite count: 0
has title: Converting a list of numpy array to a single int numpy array
has body: I have a list of numpy arrays, that I want to convert into a single int numpy array. For example if I have 46 4 x 4 numpy arrays in a list of dimension 2 x 23, I want to convert it into a single integer numpy array of 2 x 23 x 4 x 4 dimension. I have found a way to do this by going through every single element and using numpy.stack(). Is there any better way?
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50953565
downvote count: 0
score: 1
type: Question
has answer: http://stackoverflow.com/a/50950023
has comment: http://stackoverflow.com/comment/88897995
tagged with: numpy
answer count: 2

http://stackoverflow.com/comment/88875157
type: QuestionComment
has text: Did you try including the path to `p5` in your `PYTHONPATH`? Instructions on doing so are in https://stackoverflow.com/questions/3701646/how-to-add-to-the-pythonpath-in-windows
comment on: http://stackoverflow.com/q/50938421
score: 0
type: Comment

http://stackoverflow.com/comment/88880629
has text: Consider using [`if line.startswith("###")`](https://docs.python.org/3/library/stdtypes.html#str.startswith) to check for `"###"` at the _beginning_ of the line, instead of anywhere in the line.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50940964

http://stackoverflow.com/q/50943381
answer count: 2
duplicate of: http://stackoverflow.com/q/1373164
has answer: http://stackoverflow.com/a/50943549
has body: I am fairly new to Python and trying to figure out way to use variables from file as described below. I have a file query.txt query1="select count(*) from table1;" query2="select count(*) from table2;" My main program: conn=connect_db() print &gt;&gt;log,"connection successful" c=conn.cursor() with open('query.txt') as fp: for line in fp: print line i=1 query="query"+str(i) #If I print query I get query1 #I am looking to pass query1 as argument, to execute first query c.execute(query); r=c.fetchone() print r i+=1 In shell I would use c.execute($query) and it would replace it with it's assigned value. How do I achieve it with Python? Appreciate your help and guidance.
has title: Unix like use of variables in python
linked to: http://stackoverflow.com/q/902408
tagged with: python
has comment: http://stackoverflow.com/comment/88910922
has comment: http://stackoverflow.com/comment/88884265
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88910958
linked to: http://stackoverflow.com/q/1373164
has answer: http://stackoverflow.com/a/50943509
has comment: http://stackoverflow.com/comment/88884595
type: Question
has comment: http://stackoverflow.com/comment/88884389
has comment: http://stackoverflow.com/comment/88884478
has comment: http://stackoverflow.com/comment/88884537
linked to: http://stackoverflow.com/q/13793399
has comment: http://stackoverflow.com/comment/88884518
score: 0

http://stackoverflow.com/q/50860933
has comment: http://stackoverflow.com/comment/88724426
has answer: http://stackoverflow.com/a/50860997
favorite count: 0
has body: I have some strings below: 123123|00|992|1111 222222|2222|19|922 997997|3333|922|77 How can I format like this (sort by len): 123123|1111|00|992 222222|2222|19|922 997997|3333|77|922
upvote count: 1
tagged with: python
has title: python format string by length
has comment: http://stackoverflow.com/comment/88725878
has answer: http://stackoverflow.com/a/50861126
answer count: 3
has comment: http://stackoverflow.com/comment/88724436
downvote count: 4
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/21299988
has answer: http://stackoverflow.com/a/50860989
score: -3
accepted answer: http://stackoverflow.com/a/50860989
type: Question
possible better answer: http://stackoverflow.com/a/50860997

http://stackoverflow.com/a/50934643
has comment: http://stackoverflow.com/comment/88868666
downvote count: 0
type: Answer
score: 2
has body: You can easily do this in python without using windows batch commands. You can use the subprocess library to run external scripts simultaneously and then wait for them all to complete. processes = [] scripts = [ r'C:\myfolder\1.py', r'C:\myfolder\2.py', r'C:\myfolder\3.py', ] for script in scripts: p = subprocess.Popen(['python', script]) processes.append(p) for p in processes: p.wait() # Run other processes here
upvote count: 2
has comment: http://stackoverflow.com/comment/88868630
answers question: http://stackoverflow.com/q/50934443

http://stackoverflow.com/q/50958668
has answer: http://stackoverflow.com/a/50958688
tagged with: python
has body: I have this sample array: In [38]: arr Out[38]: array([ 0, 44, 121, 154, 191]) The above is just a sample whereas my actual array size is pretty huge. So, what is an efficient way to compute a distance matrix? The result should be: In [41]: res Out[41]: array([[ 0, 44, 121, 154, 191], [ -44, 0, 77, 110, 147], [-121, -77, 0, 33, 70], [-154, -110, -33, 0, 37], [-191, -147, -70, -37, 0]]) I wrote a for loop based implementation which is too slow. Could this be vectorized for efficiency reasons?
tagged with: vectorization
has answer: http://stackoverflow.com/a/50958691
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
tagged with: numpy
has title: Efficient way to compute distance matrix in NumPy
tagged with: arrays
accepted answer: http://stackoverflow.com/a/50958691
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/77703065
favorite count: 0
possible better answer: http://stackoverflow.com/a/50958688
tagged with: multidimensional-array

http://stackoverflow.com/comment/88836107
comment on: http://stackoverflow.com/q/50917912
has text: @Sirknow-a-ton it would be easy to figure out what your program is doing (if it is running or not) by using basic debugging statements placed in your code.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50971420
type: Answer
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50971042
has body: It should work if you move the configuration of timeouts in constructor of client client = httpclient.AsyncHTTPClient(defaults=dict(request_timeout=180))
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50971042

http://stackoverflow.com/a/50919531
downvote count: 0
type: Answer
upvote count: 4
has body: Just put the response variable outside your loop. You instantiate it whenever the "for i, j" loop iterates. Like so: response = make_response() for i, j in zip(list_1, list_2): url = 'http://www.website.com/{}'.format(i) payload = 'encoded{}'.format(j) headers = {...} request = requests.request("POST", url, data=payload, headers=headers) for key, value in request.cookies.items(): response.set_cookie(key, value) return response
answers question: http://stackoverflow.com/q/50918819
score: 4
accepted answer of: http://stackoverflow.com/q/50918819
type: AcceptedAnswer

http://stackoverflow.com/q/50981100
tagged with: gmail
score: 2
type: Question
has answer: http://stackoverflow.com/a/67893484
tagged with: javascript
tagged with: http://stackoverflow.com/tag/html
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/88957716
has body: I need to insert my own form in a gmail email, so that my client can fill that form, press a submit button and trigger a response with the form content to my domain. I already did the template (example image below) and successfully sent the email with it using python gmail API by inserting the html code in the body. My question is the following: Once the user completes the form, how do I get the info in my domain server? Maybe by doing an ajax request when the button is pressed? Help will be much appreciated! Thank you!! Template example:
favorite count: 0
has title: Can I use custom html-css-js form within an Email?
upvote count: 2
type: UnansweredQuestion
tagged with: python
tagged with: css

http://stackoverflow.com/comment/88757883
type: Comment
score: 0
comment on: http://stackoverflow.com/a/50877755
type: AnswerComment
has text: @antfuentes87 I mean, they all do exactly the same thing... but it's your call I guess. I agree with @tobias_k though, `enumerate`/`itertools.count` are more versatile.

http://stackoverflow.com/comment/88955325
type: QuestionComment
comment on: http://stackoverflow.com/q/50979721
type: Comment
has text: Yes. I've omitted all the code that seemed extraneous to wanting to set the attribute. `Baz` is a core object. `Qux` is a wrapper for `Baz`. An instance of `Baz` can be referenced by multiple `Qux` instances.
score: 0

http://stackoverflow.com/a/50891335
answers question: http://stackoverflow.com/q/50882895
type: Answer
has body: Since my question was answered by @user2285236 in the comments, I try to summary it. The method first() does not select the first group, but the first entry of every group. The reason why there is no built-in implementation something like list(df.groupby(level=0))[0][1] is that groupby() method sorts the entries. For example, lets arrange the example above and make the 'first' group 'qux?. Which would look like this: arrays = [['qux', 'qux', 'bar', 'bar', 'baz', 'baz', 'foo', 'foo'], ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']] tuples = list(zip(*arrays)) index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second']) s = pd.Series(np.random.randn(8), index=index) df = pd.DataFrame(np.random.randn(8, 4), index=arrays) the call of list(df.groupby(level=0))[0][1] returns: 0 1 2 3 bar one -0.335708 -0.315253 -0.087970 0.754242 two -1.608651 1.005786 1.800341 -1.059510 rather than the 'first' group, which I expect to be: 0 1 2 3 qux one -0.374186 0.812865 0.578298 -0.901881 two -0.137799 0.278797 -1.171522 0.319980 However, every group can be called with the built-in method get_group(). Hence, in this case, I could get the 'first' group by calling: df.groupby(level=0).get_group('qux')
score: 0

http://stackoverflow.com/a/70791054
answers question: http://stackoverflow.com/q/50891138
upvote count: 1
score: 1
has body: try this: import requests import requests_proxychain requests_proxychain.patch() r = requests.get( 'https://httpbin.org/get', proxies={'all': 'http://10.10.1.10:3128,socks5://90.90.90.90:8080'} ) print(r.text) requests_proxychain.py ''' requirements: python_socks async_timeout usage: import requests import requests_proxychain requests_proxychain.patch() requests.get( 'https://httpbin.org/get', proxies={'all': 'socks5://127.0.0.1:1080,http://127.0.0.2:1080'} ) tested: requests/2.8.0 + python/3.6.15 requests/2.27.1 + python/3.10.2 ''' import asyncio from requests.utils import select_proxy from requests.adapters import HTTPAdapter from python_socks.async_.asyncio import Proxy from python_socks.async_ import ProxyChain try: import requests.packages.urllib3 as urllib3 except ImportError: # requests &gt;= v2.16.0 import urllib3 HTTPConnection = urllib3.connection.HTTPConnection HTTPSConnection = urllib3.connection.HTTPSConnection HTTPConnectionPool = urllib3.connectionpool.HTTPConnectionPool HTTPSConnectionPool = urllib3.connectionpool.HTTPSConnectionPool PoolManager = urllib3.PoolManager real_get_connection = HTTPAdapter.get_connection def patch(): HTTPAdapter.get_connection = patched_get_connection def proxy_from_url(url: str): for scheme in 'socks4', 'socks5': scheme_rdns = scheme + 'h' if url.startswith(scheme_rdns): url = url.replace(scheme_rdns, scheme, 1) return Proxy.from_url(url, rdns=True) return Proxy.from_url(url) def parse_proxychain_url(url): proxy = map(str.strip, url.split(',')) proxy = filter(None, proxy) proxy = list(map(proxy_from_url, proxy)) return ProxyChain(proxy) class ChainConnection(HTTPConnection): def __init__(self, *args, **kwargs): self._socks_options = kwargs.pop('_socks_options') super().__init__(*args, **kwargs) def _new_conn(self): proxy = self._socks_options['proxychain'] loop = asyncio.get_event_loop() conn = loop.run_until_complete( proxy.connect(self.host, self.port)) conn.setblocking(True) return conn class ChainHTTPSConnection(Chain…
downvote count: 0
type: Answer

http://stackoverflow.com/a/50859328
answers question: http://stackoverflow.com/q/50859183
score: 2
downvote count: 0
has body: You can skip the header lines: for line in lines[2:]: p= line.split() x1.append(float(p[3])) This leaves out the first two lines of you input.dat
upvote count: 2
type: Answer

http://stackoverflow.com/comment/88780831
type: Comment
has text: It was actually you who gave me the idea. And yes, it is pretty nice, but I'm really hoping that the ML Studio team has even bigger ambitions with the integration of notebooks.
comment on: http://stackoverflow.com/a/50876324
type: AnswerComment
score: 0

http://stackoverflow.com/comment/88818915
type: Comment
type: QuestionComment
has text: Do not post the link to your data. Simply copy paste your input data and then your expected output. I know that input data may range from 100 rows to millions hence, you need to provide a minified example of your data. Go through the link I posted before to understand what I am asking for.
comment on: http://stackoverflow.com/q/50908940
score: 0

http://stackoverflow.com/comment/88942851
has text: Thanks but this is what I am getting in error , "Length mismatch: Expected axis has 10296 elements, new values have 10297 elements"
type: Comment
comment on: http://stackoverflow.com/a/50972353
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88795110
has text: What is *system R*? Please point to links if it is distinct from the R language.
score: 0
comment on: http://stackoverflow.com/q/50897395
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50965697
has comment: http://stackoverflow.com/comment/88928272
type: AcceptedAnswer
downvote count: 0
score: 1
has body: Update: full version that resulting 1001 lines import csv data = [] with open('SO_dataset.csv', 'rb') as csvfile: spamreader = csv.reader(csvfile) for row in spamreader: print ', '.join(row) data.append((row[2] if len(row)&gt; 2 else '')) f = open("Answers.txt", "w") i = 0 for line in data: i += 1 line = line.replace('\n',' ') f.write(str(i) + '. ' + line) f.write("\n") f.close Actually, your original code seems fine. If you are talking about the txt file break your line and wrap to next line, that's property of Notepad... If you input them into word or excel, they should be fine without breaking line.
has comment: http://stackoverflow.com/comment/88955417
type: Answer
accepted answer of: http://stackoverflow.com/q/50965349
has comment: http://stackoverflow.com/comment/88927859
answers question: http://stackoverflow.com/q/50965349
upvote count: 1
has comment: http://stackoverflow.com/comment/88927739

flask-restplus
tag name: flask-restplus
tags question: http://stackoverflow.com/q/50967548
type: Tag

keyboardinterrupt
tag name: keyboardinterrupt
type: Tag
tags question: http://stackoverflow.com/q/50886731

http://stackoverflow.com/comment/88835100
has text: Thank you, I appreciate the help. Its all a bit overwhelming. I can see several things I did wrong up front, some of the rest are a bit hard to wrap my brain around. I can see where I was messing up the actual calculation. I toyed with it some more and it runs, but I know it is incorrect, and I know I am not having it use the values I want when I want them. I tried to comment out my thought process, Ill update the question
type: AnswerComment
score: 1
type: Comment
comment on: http://stackoverflow.com/a/50915144

http://stackoverflow.com/comment/127582498
has text: Now, the constraint is `index.size(i) <= source.size(i)` for all `i != dim`.
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/61262046
type: Comment

http://stackoverflow.com/q/50901229
duplicate of: http://stackoverflow.com/q/12433695
downvote count: 2
has answer: http://stackoverflow.com/a/50901237
answer count: 1
accepted answer: http://stackoverflow.com/a/50901237
has comment: http://stackoverflow.com/comment/88802334
has title: How to iterate over a list two at a time in Python 3?
linked to: http://stackoverflow.com/q/509211
favorite count: 0
tagged with: python-3.x
duplicate of: http://stackoverflow.com/q/8865878
tagged with: python
linked to: http://stackoverflow.com/q/8865878
has comment: http://stackoverflow.com/comment/88802373
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/8671280
score: 1
has comment: http://stackoverflow.com/comment/88802277
has body: I am trying iterate over a list, two at a time. This is my code: list_1 = [1,3,2,4,3,1,2,7] The ouput should be like this(the iteration should start from the first element): 1 2 3 2 Seven, is not there because the iteration in only 2. This is my try: nums = [1,3,2,4,3,1,2,7] for x, y in zip(*[iter(nums)]*2): print(x, y) But my output is: 1 3 2 4 3 1 2 7 How can I achieve the proper iteration using Python 3?
type: Question
upvote count: 3

http://stackoverflow.com/q/50903448
linked to: http://stackoverflow.com/q/50929918
score: 1
upvote count: 1
type: Question
tagged with: pymodbus
has body: In pymodbus library in server.sync, SocketServer.BaseRequestHandler is used, and defines as follow: class ModbusBaseRequestHandler(socketserver.BaseRequestHandler): """ Implements the modbus server protocol This uses the socketserver.BaseRequestHandler to implement the client handler. """ running = False framer = None def setup(self): """ Callback for when a client connects """ _logger.debug("Client Connected [%s:%s]" % self.client_address) self.running = True self.framer = self.server.framer(self.server.decoder, client=None) self.server.threads.append(self) def finish(self): """ Callback for when a client disconnects """ _logger.debug("Client Disconnected [%s:%s]" % self.client_address) self.server.threads.remove(self) def execute(self, request): """ The callback to call with the resulting message :param request: The decoded request message """ try: context = self.server.context[request.unit_id] response = request.execute(context) except NoSuchSlaveException as ex: _logger.debug("requested slave does not exist: %s" % request.unit_id ) if self.server.ignore_missing_slaves: return # the client will simply timeout waiting for a response response = request.doException(merror.GatewayNoResponse) except Exception as ex: _logger.debug("Datastore unable to fulfill request: %s; %s", ex, traceback.format_exc() ) response = request.doException(merror.SlaveFailure) response.transaction_id = request.transaction_id response.unit_id = request.unit_id self.send(response) # ----------------------------------------------------------------------- # # Base class implementations # ----------------------------------------------------------------------- # def handle(self): """ Callback when we receive any data """ raise NotImplementedException("Method not implemented by derived class") def send(self, message): """ Send a request (string) to the network :param message: The unencoded modbus response """ raise NotImplementedException("Method not implemented by derived class") setup() is call…
has title: modify a function of a class from another class
has answer: http://stackoverflow.com/a/50903589
answer count: 2
tagged with: handler
downvote count: 0
has comment: http://stackoverflow.com/comment/88806707
has answer: http://stackoverflow.com/a/51007173
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: socketserver
has comment: http://stackoverflow.com/comment/88809875

http://stackoverflow.com/comment/88908723
score: 0
has text: Can you elaborate what do you mean by "as a function (`| dump(opt=True)`)" ? What is `dump` here?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50955335

http://stackoverflow.com/q/50944442
answer count: 1
tagged with: upload
has comment: http://stackoverflow.com/comment/88887671
has comment: http://stackoverflow.com/comment/88887336
has title: How to make Bottle refuse too big uploaded files?
has comment: http://stackoverflow.com/comment/88887030
has answer: http://stackoverflow.com/a/50958201
tagged with: python
tagged with: bottle
has body: Here is a way to accept upload with Bottle: &lt;form action="/upload" method="post" enctype="multipart/form-data"&gt; &lt;input type="file" name="file" /&gt; &lt;/form&gt; and from bottle import route, request @route('/upload', method='POST') def do_upload(): myfile = request.files.get('file') size = len(myfile.read()) # oops the file is already read anyway! if size &gt; 1024*1024: # 1 MB return "File too big" However, with this technique a 500 MB file would be read anyway, before noticing it's a "too big file". Question: how to prevent a Bottle server to even accept a too big uploaded file, without having to read it first (and waste bandwidth/memory!)? If not possible with Bottle only, how to do it with Apache + mod_wsgi (I currently use this)?
has comment: http://stackoverflow.com/comment/88886802
linked to: http://stackoverflow.com/q/14296438
tagged with: mod-wsgi
score: 0
type: UnansweredQuestion
type: Question
tagged with: apache

http://stackoverflow.com/a/51178849
score: 0
type: Answer
has body: you declared font as a variable in the first line, you need to change it to font1 or some facsimile of such
answers question: http://stackoverflow.com/q/50950046

decorator
tags question: http://stackoverflow.com/q/50931196
tags question: http://stackoverflow.com/q/51005837
tags question: http://stackoverflow.com/q/50892564
tags question: http://stackoverflow.com/q/50895659
tags question: http://stackoverflow.com/q/50995683
tags question: http://stackoverflow.com/q/50898115
tags question: http://stackoverflow.com/q/50864988
tag name: decorator
tags question: http://stackoverflow.com/q/50855495
type: Tag

http://stackoverflow.com/q/50874821
accepted answer: http://stackoverflow.com/a/50875045
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88751283
type: Question
tagged with: numpy
score: 0
answer count: 1
tagged with: fread
tagged with: python
has body: I'm trying to read noncontiguous fields from a binary file in Python using numpy fromfile function. It's based on this Matlab code using fread: fseek(file, 0, 'bof'); q = fread(file, inf, 'float32', 8); 8 indicates the number of bytes I want to skip after reading each value. I was wondering if there was a similar option in fromfile, or if there is another way of reading specific values from a binary file in Python. Thanks for your help. Henrik
has answer: http://stackoverflow.com/a/50875045
tagged with: fromfile
has title: How to skip bytes after reading data using numpy fromfile

http://stackoverflow.com/comment/88951541
comment on: http://stackoverflow.com/q/50977683
score: 0
type: QuestionComment
has text: or maybe it's the EOL character? Open the file with a texteditor like Notepad++ to check. Then set it accordingly with the `lineterminator` parameter of [`read_csv`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html)
type: Comment

http://stackoverflow.com/q/50931858
tagged with: python
upvote count: 0
tagged with: google-api
type: UnansweredQuestion
type: Question
has title: Google Maps Places API unauthorized error
score: -1
tagged with: google-maps
answer count: 1
downvote count: 1
has body: I'm trying to use the Places API to get a list of restaurants in a city. I keep getting this error: Traceback (most recent call last): File "googlePlacesAPI.py", line 10, in &lt;module&gt; radius=20000, types=[types.TYPE_FOOD]) File "/Users/**me**/Downloads/slimkrazy-python-google-places-d4b7363/googleplaces/__init__.py", line 281, in nearby_search lat_lng_str = self._generate_lat_lng_string(lat_lng, location) File "/Users/**me**/Downloads/slimkrazy-python-google-places-d4b7363/googleplaces/__init__.py", line 593, in _generate_lat_lng_string 'lat_lng must be a dict with the keys, \'lat\' and \'lng\'. Cause: %s' % str(e)) ValueError: lat_lng must be a dict with the keys, 'lat' and 'lng'. Cause: Request to URL https://maps.googleapis.com/maps/api/geocode/json?sensor=false&amp;key=YOUR_API_KEY&amp;address=%7B%27lat%27%3A+%2733.7490%27%2C+%27lng%27%3A+%2784.3880%27%7D failed with response code: REQUEST_DENIED which I believe is the result of my API key not working, despite being enabled in the Google Developer Console. What could I be missing?
favorite count: 0
has answer: http://stackoverflow.com/a/50932224

http://stackoverflow.com/comment/88817300
comment on: http://stackoverflow.com/a/50901737
type: Comment
has text: Very nice explanation sir.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88868948
score: 1
comment on: http://stackoverflow.com/q/50935134
type: Comment
type: QuestionComment
has text: Properties don't work with old-style classes. Inherit from `object` if you're not inheriting from anything else.

http://stackoverflow.com/q/50901772
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88807726
type: Question
tagged with: python
score: 0
has body: I want to plot a real-time graph in matplot lib with a limited number of X axis values (say 10). My current graph does not do that and instead compresses the entire graph. When i get my 11th value, I want my 1st value to be wiped off. any ideas? I was thinking of using a cyclic queue, but do not know where and how to start. My current code (dummy data) is: for i in range(0,100): #time time.sleep(0.1) for s in range(0,sensors): x[s].append(random.randint(20,80)) drawnow(makePlot)
has comment: http://stackoverflow.com/comment/89224844
tagged with: live-streaming
has title: Live matplotlib plotting maintaining the axes values (only 10 in x axis)
tagged with: matplotlib
tagged with: http://stackoverflow.com/tag/json
linked to: http://stackoverflow.com/q/4151320
answer count: 0

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

http://stackoverflow.com/a/50935772
answers question: http://stackoverflow.com/q/50935665
has body: Needed quotes around the data variable 'data = {"inputs": [{"data": {"image": {"url": "https://samples.clarifai.com/demographics.jpg"}}}]}'
downvote count: 1
has comment: http://stackoverflow.com/comment/88870204
score: -1
upvote count: 0
type: Answer

http://stackoverflow.com/q/50995279
tagged with: pandas
answer count: 1
favorite count: 0
tagged with: latex
tagged with: pdflatex
tagged with: python
linked to: http://stackoverflow.com/q/26678467
score: 2
downvote count: 0
type: UnansweredQuestion
has title: Converting TeX file to image in Python
type: Question
has answer: http://stackoverflow.com/a/56345071
has body: Using this accepted answer as a reference, I've been trying to replicate the pandas DF to TeX to PDF to png recipe. However, my Python 3 (using a Jupyter Notebook thru Anaconda Navigator) is giving me some trouble. I've installed MiKTeX at the following default location on my local disk: C:\Users\USERNAME\AppData\Local\Programs\MiKTeX\2.9 I also installed LaTex at the following location: C:\Users\USERNAME\AppData\Local\Programs\Python\Python36-32\Lib\site-packages\notebook\static\components\MathJax\extensions\TeX However, when I run the chunk of code using my Pandas df object: filename = 'out.tex' pdffile = 'out.pdf' outname = 'out.png' template = r'''\documentclass[preview]{{standalone}} \usepackage{{booktabs}} \begin{{document}} {} \end{{document}} ''' with open(filename, 'wb') as f: f.write(bytes(template.format(df.to_latex()),'UTF-8')) subprocess.call(['pdflatex', filename], shell=True) subprocess.call(['convert', '-density', '300', pdffile, '-quality', '90', outname]) It's simply returning "4", and the only file created from my original df is "out.tex". I'd like the DF to be turned into a png image so I can keep the full process in my Notebook script. Any advice would be much appreciated. Thanks.
upvote count: 2

http://stackoverflow.com/a/51009302
has body: i think it's ok. that's a bit messy but you'll hopefully get the idea rprod = {0: [2,1,1], 1: [3,1,2], 2: [2,2,2]} comp = [7, 3, 4] flat_comp = [[1]*x for x in comp] # [[1, 1, 1, 1, 1, 1, 1], [1, 1, 1], [1, 1, 1, 1]] # turn prod into a list of rprod indices prod = [2, 1, 0] flat_prod = [i for i, x in enumerate(prod) for _ in range(x)] # [0, 0, 1] result = [[] for _ in range(len(comp))] for i in range(len(comp)): result[i] = flat_comp[i] for production in flat_prod: result[i].append(-rprod[production][i]) print(result) # [[1, 1, 1, 1, 1, 1, 1, -2, -2, -3], [1, 1, 1, -1, -1, -1], [1, 1, 1, 1, -1, -1, -2]]
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51006814

http://stackoverflow.com/comment/88940874
type: QuestionComment
has text: No, I'm asking why your desired output has apostrophes
comment on: http://stackoverflow.com/q/50972143
score: 0
type: Comment

http://stackoverflow.com/comment/88961707
comment on: http://stackoverflow.com/q/50982284
has text: Somethings changing `localhost` to `host='127.0.0.1'` does the trick. Have you tried it?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50950906
tagged with: loops
has comment: http://stackoverflow.com/comment/88900595
type: Question
has comment: http://stackoverflow.com/comment/88900122
has title: Clean text files - remove unwanted content in LOOP (R/python)
has comment: http://stackoverflow.com/comment/88899859
has comment: http://stackoverflow.com/comment/88899836
score: 0
has body: I want to clean all the "waste" (making the files unsuitable for analysis) in unstructured text-files. In this specific situation, one option to only retain the wanted information, is to only retain all numbers above 250 (the text is a combination of string, numbers, ...) For a large number of text files, I want to do follow action in R: x <- x[which(x >= "250"),] The code for 1 text file works perfectly (above), when I try to do the same in a loop (for the large N of text files, it fails (error: incorrect number of dimensions o)). for(i in 1:length(files)){ i<- i[which(i >= "250"),] } Anyone any idea how to solve this in R (or python) ? picture: very simplified example of a text file, I want to retain everything between (START) and (END)
answer count: 1
has answer: http://stackoverflow.com/a/50951538
has comment: http://stackoverflow.com/comment/88899976
tagged with: http://stackoverflow.com/tag/r
has comment: http://stackoverflow.com/comment/88900193
has comment: http://stackoverflow.com/comment/88899717
has comment: http://stackoverflow.com/comment/88900669
tagged with: python
has comment: http://stackoverflow.com/comment/88899587
type: UnansweredQuestion
tagged with: data-cleaning

http://stackoverflow.com/q/50933647
has answer: http://stackoverflow.com/a/50959841
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50933783
has comment: http://stackoverflow.com/comment/88866208
tagged with: python
has answer: http://stackoverflow.com/a/50933850
has title: Python: How to end a program after user inputs 3 invalid values and prevent following functions from running without using system exit/break?
type: Question
tagged with: function
score: 0
answer count: 3
has body: i'm currently taking a programming class and the professor would like us to end all of our programs "logically" so we are not able to use system exits or breaks. I did this successfully before but the added in factor of functions has halted me as I do not know how I could terminate the program so that the other functions do not run either. My program just spits out error message but continues to the next calculation, I need it to terminate completely. here is my code: def main(): #miles to kilometers input miles_km = float(input('Please enter how many miles you would like to convert.')) #function call milestoKm(miles_km) #Fahrenheit to Celsius fah_cel = float(input('Please enter how many degrees Farenheit you would like to convert.')) #Function call FahToCel(fah_cel) gal_liters = float(input('Please enter how many gallons you would like to convert.')) #Function call GaltoLit(gal_liters) #Pounds to Kilograms pounds_kg = float(input('Please enter how many pounds you would like to convert.')) #Function call PoundsToKg(pounds_kg) #Inches to Centimeters inches_cm = float(input('Please enter how many inches you would like to convert.')) #function call InchesToCm(inches_cm) def milestoKm(miles): tries = 0 while miles &lt;0 and tries &lt;3: print('Error: enter a valid value') miles = float(input('Please enter how many miles you would like to convert.')) tries+=1 if tries ==3 and miles &lt;0: print('Error: valid value not entered.') return miles if tries &lt;=2: km_miles = (miles *1.6) return print(miles, 'miles is equal to', format(km_miles ,',.2f'), 'kilometers.') def FahToCel(faren_deg): tries = 0 while faren_deg &lt;1000 and tries &lt;3: print('Error: enter a valid value') faren_deg = float(input('Please enter how many degrees Farenheit you would like to convert.')) tries+=1 if tries ==3: print('Error: valid value not entered.') return faren_deg if tries &lt;=2: cels_deg = ((faren_deg -32) *(5/9)) return print(faren_deg, 'degrees Farenheit is equal to', format(cels_deg, …

http://stackoverflow.com/q/50981097
accepted answer: http://stackoverflow.com/a/50981157
has body: pyqt gui not responding I'm trying to make a gui for my linkedin scraper program. But the GUI becomes not responding once the main program starts execution. Its working fine till the main function is called . Gui code is class MainWindow(QMainWindow): def __init__(self): QMainWindow.__init__(self) self.setMinimumSize(QSize(720, 540)) self.setWindowTitle("LinkedIn Scraper") self.nameLabel = QLabel(self) self.nameLabel.setText('Keywords:') self.keyword = QLineEdit(self) self.keyword.move(130, 90) self.keyword.resize(500, 32) self.nameLabel.move(70, 90) self.nameLabel = QLabel(self) self.nameLabel.setText('Sector:') self.sector = QLineEdit(self) self.sector.move(130, 180) self.sector.resize(500, 32) self.nameLabel.move(70, 180) self.btn = QPushButton('Download', self) self.btn.clicked.connect(self.doAction) self.btn.resize(200, 32) self.btn.move(270, 360) self.pbar = QProgressBar(self) self.pbar.setGeometry(110, 450, 550, 25) def doAction(self): print('Keyword: ' + self.keyword.text()) print('Sector: ' + self.sector.text()) main(self.keyword.text(),self.sector.text()) also want to link that progressbar with main , How can i do that ? main function is a long one ang has many sub functions. So i want to link that to each subfunctions
tagged with: pyqt
has comment: http://stackoverflow.com/comment/88957570
has comment: http://stackoverflow.com/comment/88957679
answer count: 1
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/50981157
type: AnsweredQuestion
score: 0
tagged with: pyqt5
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88957623
has title: Pyqt GUI not responding

http://stackoverflow.com/comment/88790635
comment on: http://stackoverflow.com/q/50894168
score: 0
has text: in compiled languages, decrement loops don't use the prefetch data cache as much as increment loops.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50996820
has answer: http://stackoverflow.com/a/50999564
favorite count: 0
tagged with: sql
tagged with: sqlite
upvote count: 6
tagged with: jupyter-notebook
has body: How do you import an SQLite3 database file you have stored on your computer into Python Jupyter Notebook? My goal is to be able to analyze the data in Python Pandas the same way I do when I import CSV files.
type: UnansweredQuestion
has title: How to import a SQLite3 database into Python Jupyter Notebook?
score: 6
tagged with: python
type: Question
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/88916862
type: AnswerComment
score: 0
type: Comment
has text: You don't really need Python for that. `sed '1s/^/[/;$!/}/},/;$s/$/]/' file>file.json`
comment on: http://stackoverflow.com/a/50959911

http://stackoverflow.com/comment/89070441
type: Comment
type: QuestionComment
has text: @ascripter, here is link of original data: https://drive.google.com/open?id=1DGe3ZKeoW7UsGGq-lPQZmK0_8UXK1D6I
score: 0
comment on: http://stackoverflow.com/q/50975701

http://stackoverflow.com/a/50921891
downvote count: 0
has comment: http://stackoverflow.com/comment/88861213
has comment: http://stackoverflow.com/comment/88853458
type: Answer
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/88853678
answers question: http://stackoverflow.com/q/50918687
has body: I cannot reproduce this bug, neither with Scapy current version (2.4.0), nor with the current development version. You should probably upgrade Scapy to at least 2.4.0.

http://stackoverflow.com/comment/88916348
type: AnswerComment
type: Comment
has text: @ibonyun. Putting the new dict code in `__new__` ensures that inheritance will work properly. I didn't do the check right, so that's fixed now.
comment on: http://stackoverflow.com/a/50935756
score: 0

http://stackoverflow.com/comment/106140445
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/59753011
type: Comment
has text: Everything that is not a string is coerced to a string to avoid having mixed types in the array.

http://stackoverflow.com/a/50992652
answers question: http://stackoverflow.com/q/50992584
type: AcceptedAnswer
has body: You can do this using list concatenation res = [[i*j for j in a if i!=j] for i in a] [[0, 0, 0], [0, 2, 3], [0, 2, 6], [0, 3, 6]] Edit: Explanation: This runs two loops and multiplies i and j if the values are not equal. As @abarnert pointed out, this will not work if the values are repeated, something like [1, 0, 2, 2] In that case, we can use the index to identify the element instead of values. Edit2: As pointed out by @coldspeed, using enumerate is a cleaner and better way to do this, e.g.: res =[[x * y for i, y in enumerate(a) if i != j] for j, x in enumerate(a)] Using range, we can do this way: res = [[a[i]*a[j] for j in range(0,len(a)) if i!=j] for i in range(0,len(a))] Running this for a = [0 ,1 ,2 ,2] we get [[0, 0, 0], [0, 2, 2], [0, 2, 4], [0, 2, 4]]
has comment: http://stackoverflow.com/comment/88980264
accepted answer of: http://stackoverflow.com/q/50992584
type: Answer
has comment: http://stackoverflow.com/comment/88980356
has comment: http://stackoverflow.com/comment/88980263
downvote count: 0
score: 6
has comment: http://stackoverflow.com/comment/88980340
upvote count: 6
has comment: http://stackoverflow.com/comment/88980314
has comment: http://stackoverflow.com/comment/88980111

http://stackoverflow.com/comment/139098081
comment on: http://stackoverflow.com/q/50950690
type: Comment
type: QuestionComment
score: 1
has text: This type of coding optimization seems like a great way of making developers not understand the code and spend time learning how/why the code was optimized in the first place.

http://stackoverflow.com/q/50898341
answer count: 2
possible better answer: http://stackoverflow.com/a/50898793
tagged with: matrix
has answer: http://stackoverflow.com/a/50898793
downvote count: 1
linked to: http://stackoverflow.com/q/11874767
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/88814547
accepted answer: http://stackoverflow.com/a/50898831
has title: How to display a set of files with MatPlotLib in a loop
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88800986
upvote count: 0
has body: I have a set of .txt named "occupancyGrid_i", i being a number from 0-100. What I'd like to do is to open every one of them and show them for 3 seconds. The data of the .txt is a [N x M] matrix. import numpy import matplotlib.pyplot as plt import time while True: matrix = numpy.loadtxt('res/matrix_' + str(i) + '.txt') plt.clf() plt.imshow(matrix) plt.show() time.sleep(3) i=i+1 What I have done so far doesn't seem to be enough. What am I doing wrong?
tagged with: matplotlib
has answer: http://stackoverflow.com/a/50898831
type: Question
score: -1

http://stackoverflow.com/comment/88862751
has text: I want to correlate the first 10 with the next 10 columns, and so on.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50929361

http://stackoverflow.com/comment/88910568
type: AnswerComment
score: 0
has text: Thank you very much. All is resolved. Really appreciated your help!!
type: Comment
comment on: http://stackoverflow.com/a/50954824

http://stackoverflow.com/q/50958112
tagged with: python-3.x
tagged with: tkinter
has comment: http://stackoverflow.com/comment/88917017
answer count: 0
type: UnansweredQuestion
upvote count: 1
has comment: http://stackoverflow.com/comment/88916777
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88916980
has title: Unexpected EOF while parsing with Tkinter
score: 0
favorite count: 0
tagged with: python
has body: I execute the following function: def multi_joueurs(): global liste_des_joueurs liste_des_joueurs=[] def nombre_des_joueurs(): fen2305=Tk() fen2305.title("un seul joueur") fen2305.config(bg='royalblue') label=Label(fen2305,text="nombre des joueurs dans ce matche:") global nobre_jouer nobre_joer=Entry(fen2305) botn=Button(fen2305,text="valider") label.grid() nobre_joer.grid() botn.grid() nobre_jouer=nobre_joer.get() ferme(fen2305) fen2305.mainloop() def ouvre(m): fen23055=Tk() fen23055.title("un seul joueur") fen23055.config(bg='royalblue') label=Label(fen23055,text="donner le nom du joueur "+str(m)+":") nom_joueur=Entry(fen23055) label.grid() nom_joueur.grid() def va(): global nom_pre_joueur nom_pre_joueur=nom_joueur.get() if nom_pre_joueur!='': fen23055.destroy() botn=Button(fen23055,text="valider",command=va) botn.grid() fen23055.mainloop() def nom_des_joueurs(): for m in range(int(eval(nobre_jouer))): ouvre(nobre_jouer) liste_des_joueurs.append(str(nom_pre_joueur)) nombre_des_joueurs() nom_des_joueurs() But here is the error: , line 4, in nom_des_joueurs for m in range(int(eval(nobre_jouer))): File "&lt;string&gt;", line 0 ^ SyntaxError: unexpected EOF while parsing

http://stackoverflow.com/q/50961759
upvote count: 8
type: Question
tagged with: http://stackoverflow.com/tag/html
has body: I am new to Dash and I am in need of some assistance. I need to create a dynamic number of inputs, but I have no idea how to bind a dynamic number of callback for each slider component. I am only able to create a dynamic number of sliders, but as you can see in the code, I need to hard code the number of callbacks. Is there a better way to to this so that it is more dynamic? @app.callback( Output('slider-container', 'children'), [Input('button', 'n_clicks')]) def add_sliders(n_clicks): return \ html.Div([ html.Div([ html.Div(dcc.Slider(id='slider-{}'.format(i))), dcc.Input( id='input-{}'.format(i), placeholder='Graph Name', type='text', value='' ), html.Div(id='output-{}'.format(i), style={'marginTop': 30}) ]) for i in range(n_clicks)] ) # up to 10 sliders for i in range(10): @app.callback( Output('slider-{}'.format(i), 'children'), [Input('slider-{}'.format(i), 'value'), Input('input-{}'.format(i), 'value')]) def update_output(slider_i_value, input_i_value): return str(slider_i_value) + str(input_i_value)
tagged with: python
tagged with: dynamic
answer count: 1
tagged with: python-2.7
tagged with: plotly-dash
score: 8
has title: Dynamically adding HTML inputs in Dash framework
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/108335599
favorite count: 0
has answer: http://stackoverflow.com/a/65546586

http://stackoverflow.com/q/50915139
favorite count: 0
has body: Edit: Since writing this, I remembered a third necessary condition. That is, if the difference between the values at index 1 (time) is greater than or equal to 2, then the rows should be sorted normally by the index 1 (time) column. So because the time value for B is 6 and within a difference of 2 for the T time of 5, B should come after T. However,for T and K, for example, because the 7 value for K is 2 greater than the 5 value for T, T should come first. Let's say I have this array input = [['user_id', 'time', 'address'], ['F', 5, 5], ['T', 5, 8], ['B', 6, 6], ['K', 7, 7], ['J', 7, 9], ['M', 9, 10]] I'd like to sort the rows -- first in ascending order by index 1 (time). However, secondarily, if index 2 (address) for a given user_id such as 'B' is less than index 2 (address) for another user such as 'T', I'd like user_id 'B' to come before user_id 'T'. So the final output would look like this: output = [['user_id', 'time', 'address'], ['F', 5, 5], ['B', 6, 6] ['T', 5, 8], ['K', 7, 7], ['J', 7, 9], ['M', 9, 10]] If possible, I'd like to do this without Pandas.
possible better answer: http://stackoverflow.com/a/50915284
has title: Can I do a conditional sort on two different columns, but where the order of two columns is reversed based on the secondary condition?
type: Question
has answer: http://stackoverflow.com/a/50915284
tagged with: python
score: 1
has comment: http://stackoverflow.com/comment/88830746
accepted answer: http://stackoverflow.com/a/50915436
answer count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/88833970
has comment: http://stackoverflow.com/comment/88830386
tagged with: list
has comment: http://stackoverflow.com/comment/88830312
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50915436
downvote count: 0
has comment: http://stackoverflow.com/comment/88834002
tagged with: sorting

http://stackoverflow.com/comment/89008930
comment on: http://stackoverflow.com/q/51007672
has text: I can see two-two web elements for username and password field , would you be more specific which one you want to use for login ?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89487352
type: QuestionComment
has text: No problem. That's because I removed the syntax highlighting directive (i.e. ` `); since adding the Python tag automatically highlights the syntax and there was no need for the directive anymore.
comment on: http://stackoverflow.com/q/50862101
score: 0
type: Comment

http://stackoverflow.com/comment/88760958
type: AnswerComment
has text: The output you listed is different from what the OP requested.
type: Comment
comment on: http://stackoverflow.com/a/50879427
score: 1

http://stackoverflow.com/q/50899612
tagged with: http://stackoverflow.com/tag/csv
has title: Changing date time format in all rows in csv file
tagged with: datetime
tagged with: python
has body: I have a csv file with data in this form.. 2018-06-01T09:20:00+0530,16.85,16.9,16.85,16.9,1000 2018-06-01T09:21:00+0530,16.9,17,16.9,17,500 2018-06-01T09:22:00+0530,17,17,15.5,15.5,500 2018-06-01T09:23:00+0530,15.5,15.5,15.5,15.5,0 And I need to get it into this format.. 01/06/2018 09:20:00,16.85,16.9,16.85,16.9,1000 01/06/2018 09:21:00,16.9,17,16.9,17,500 01/06/2018 09:22:00,17,17,15.5,15.5,500 01/06/2018 09:23:00,15.5,15.5,15.5,15.5,0 Basically the date format has to be changed for all rows in the file.. I have not been able to code this and using macros is rather painful.
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88830928
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/50924201
accepted answer: http://stackoverflow.com/a/50924201
possible better answer: http://stackoverflow.com/a/50906722
score: 0
answer count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/88799144
has answer: http://stackoverflow.com/a/50906722
favorite count: 0
has comment: http://stackoverflow.com/comment/88846783

http://stackoverflow.com/q/50894723
has comment: http://stackoverflow.com/comment/88789520
has comment: http://stackoverflow.com/comment/88789560
has title: Selenium Timeoutexception Error
linked to: http://stackoverflow.com/q/50824810
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/50897857
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/88789533
has answer: http://stackoverflow.com/a/50898078
type: UnansweredQuestion
tagged with: selenium
has body: Still working on this Instagram problem, i really need your help. Here is my code: input_button = wait(browser,10).until(EC.element_to_be_clickable((By.XPATH, '//button[@class ="chBAG"]'))) action=ActionChains(browser) action.move_to_element(input_button) action.click() action.perform() Here is the HTML: Fermer But I got a: selenium.common.exceptions.TimeoutException: Message: Could someone help me solve that problem ? Thx
duplicate of: http://stackoverflow.com/q/50824810
has comment: http://stackoverflow.com/comment/88793384
has comment: http://stackoverflow.com/comment/88789584

http://stackoverflow.com/q/50874445
type: AnsweredQuestion
score: 1
tagged with: bokeh
upvote count: 1
type: Question
has title: Bokeh: Not able to update format of hover tooltip
has body: I'm trying to update the format of an already defined hover tooltip, but I do not observe any change. The change I do in the example below is changing the x-axis between number and time scale ('00:00:00'). The x-axis is updated as expected. Using Bokeh version 0.12.16, mac OS X, Safari browser. Any hints with respect to what I'm doing wrong is appreciated. from bokeh.plotting import figure, ColumnDataSource from bokeh.models import HoverTool, NumeralTickFormatter, AdaptiveTicker from bokeh.models.widgets import RadioGroup from bokeh.layouts import row, widgetbox from bokeh.io import curdoc def update_axis_format(new): if new == 0: format_num = '0' mantissas= [1,2,5] else: format_num = '00:00:00' mantissas=[3.6, 7.2, 18] p.xaxis[0].formatter = NumeralTickFormatter(format = format_num) p.xaxis.ticker = AdaptiveTicker(base = 10, mantissas = mantissas) p.xgrid.ticker = AdaptiveTicker(base = 10, mantissas = mantissas) p.tools[0].tooltips[2] = ("x", "@x{{{}}}".format(format_num)) source = ColumnDataSource(data=dict( x=[10, 2000, 10000, 40000, 50000], y=[2, 5, 8, 2, 7], desc=['A', 'b', 'C', 'd', 'E'], )) hover = HoverTool(tooltips=[ ("index", "$index"), ("desc", "@desc"), ("x", "@x") ]) p = figure(plot_width=400, plot_height=400, tools=[hover], title="Mouse over the dots") p.circle('x', 'y', size=20, source=source) xaxis_format = RadioGroup( labels=["x-axis as number", "x-axis as time"], active=0) xaxis_format.on_click(update_axis_format) widget = widgetbox(xaxis_format) curdoc().add_root(row(widget,p))
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/50878702
accepted answer: http://stackoverflow.com/a/50878702
tagged with: python

http://stackoverflow.com/comment/88878898
type: Comment
comment on: http://stackoverflow.com/q/50940542
has text: `a.h` is 4; `a.w` is 10. Multiply each by two and add them together, and you get 28. Doesn't seem like it's that complicated.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/88967971
score: 4
comment on: http://stackoverflow.com/q/50986671
type: Comment
type: QuestionComment
has text: You're receiving a `dict`, but you appear to try and parse the whole `dict` as a `str`. Just use `data['key']` instead, for example.

http://stackoverflow.com/q/50889324
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50889504
has comment: http://stackoverflow.com/comment/88780169
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/50889504
type: Question
possible better answer: http://stackoverflow.com/a/50889472
has answer: http://stackoverflow.com/a/50889472
has answer: http://stackoverflow.com/a/50889476
downvote count: 0
score: 6
answer count: 3
tagged with: pandas
favorite count: 0
has title: Pandas left join DataFrames by two columns
has body: Could you please help me with joining two DataFrames. I have two DataFrames. df1: index val1 val2 -------------------- 1 str1 abc1 2 str2 abc2 3 str3 abc3 4 str4 abc9 5 str5 abc4 df2: index val2 ------------ 1 abc1 2 abc2 4 abc3 5 abc4 9 abc5 I need to create a DataFrame based on the previous two with a left join by two columns. Columns index and val2 have the same names in both DataFrames. The result of df3 should look like this: index val1 val2 val3 ---------------------------- 1 str1 abc1 1 2 str2 abc2 1 3 str3 abc3 NaN 4 str4 abc9 NaN 5 str5 abc4 1 Indexes from df2 that are not present in df1 should be dropped, if an index in df1 has the same val2 as in df2 then 1 should be added to a new column val3, else: NaN. Huge thanks in advance!
tagged with: python
tagged with: merge
upvote count: 6

http://stackoverflow.com/q/50949301
tagged with: python
has title: name 'pythoncom' is not defined
linked to: http://stackoverflow.com/q/4145079
has body: I had read this and installed pywin32 from this place, both Python27 and Python36. However I got the error. I don't know why. I tried both Python27 and Python36. The errors are identical. To be more detailed, I put my sample code below: import win32com.client from win32com.client import constants, DispatchBaseClass, CastTo, VARIANT import sys mode = win32com.client.VARIANT(pythoncom.VT_BSTR | pythoncom.VT_BYREF, "") Result after delete the old Python, reinstalled both ActivePython 3.6 and pywin32com package. Screen shot like below: Is there any workaround which needn't use the pythoncom?
has comment: http://stackoverflow.com/comment/88916570
type: Question
score: 0
has comment: http://stackoverflow.com/comment/88916986
tagged with: com
answer count: 1
has comment: http://stackoverflow.com/comment/88897122
has answer: http://stackoverflow.com/a/72631803
type: UnansweredQuestion

http://stackoverflow.com/q/50977818
tagged with: keras
tagged with: tensorflow-datasets
has comment: http://stackoverflow.com/comment/92952585
tagged with: tensorflow-estimator
tagged with: python
has comment: http://stackoverflow.com/comment/91619117
favorite count: 0
answer count: 0
has comment: http://stackoverflow.com/comment/91620550
type: UnansweredQuestion
has title: Keras + Estimators + weighted samples
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/93141950
score: 3
has comment: http://stackoverflow.com/comment/99174006
has comment: http://stackoverflow.com/comment/93355376
upvote count: 3
type: Question
has body: With Keras, adding sample weights that weight the loss function individually for each sample was simply done in the model.fit() method. Now I am scaling the problem using Keras models (tf.keras), Estimators (tf.estimator) and Datasets (tf.data), via tf.keras.estimator.model_to_estimator. Is there a way to specify sample weights using an Estimator? The Estimator subclass DNNClassifier does have 'weight columns' which would work well if this functionality could be transferred.
downvote count: 0

http://stackoverflow.com/comment/88799944
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50899233
has text: I don't know the approach for this. I don't know how to write test case in python which send mail of test report. @Hawkins
score: 0

http://stackoverflow.com/comment/88892059
type: Comment
type: QuestionComment
has text: There was a error in my urls file which i corrected, now the code is working and I can see the template on the url, But I want to save the data from this template to mySQL database. How can I do that?
comment on: http://stackoverflow.com/q/50946723
score: 0

http://stackoverflow.com/comment/88901369
has text: @gota -- you don't really have much of a choice, unfortunately, as the function is not supported in `nopython` mode. The only workaround I can think of is writing some C-code to read in the data, wrap it using cffi (http://numba.pydata.org/numba-doc/latest/reference/pysupported.html#cffi) and then in the C-code, copy the data into a pre-allocated numpy array that numba understands. I'm not sure what the performance characteristics are going to be though, and it's going to add a build step that might not be desirable and is certainly more complex.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50911665

http://stackoverflow.com/q/51002605
duplicate of: http://stackoverflow.com/q/2612802
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/89005073
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89005047
has comment: http://stackoverflow.com/comment/88998929
has title: how to chage the value of python dictionary
has body: In the following code, I created a simple dictionary, then I want to change the value of key B, but all the other values are changed,If the statement score.setdefault(name, values) is replaced by score.setdefault(name, [0,0,0]),then it works ok。I am so confused could somebody help me? Thank you very much. names = ['A', 'B', 'C'] score = {} values = [0,0,0] #Create a dictionary: {'A': [0, 0, 0], 'B': [0, 0, 0], 'C': [0, 0, 0]} for name in names: score.setdefault(name, values) print(score) #Change the value of key B for name in names: score['B'][0] = 1 print(score) #The result is: {'A': [1, 0, 0], 'B': [1, 0, 0], 'C': [1, 0, 0]}
linked to: http://stackoverflow.com/q/2612802
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/88761734
has text: In my program I didn't name it input, I just did it here to show that is the kind of input that the program will take.
comment on: http://stackoverflow.com/q/50879786
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/50861450
type: Question
accepted answer: http://stackoverflow.com/a/50862394
tagged with: pyqt4
has body: I have added a Label in PyQt4 which contains an image. This image fits the window completely when it is not maximised. My aim is that the label should auto resize and fit the window completely even when maximised. My code is as follows: class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName(_fromUtf8("MainWindow")) MainWindow.resize(1047, 600) self.centralwidget = QtGui.QWidget(MainWindow) self.centralwidget.setObjectName(_fromUtf8("centralwidget")) self.label = QtGui.QLabel(self.centralwidget) self.label.setGeometry(QtCore.QRect(0, 0, 1081, 551)) self.label.setText(_fromUtf8("")) self.label.setPixmap(QtGui.QPixmap(_fromUtf8("Capture.PNG"))) self.label.setObjectName(_fromUtf8("label")) if __name__ == "__main__": import sys app = QtGui.QApplication(sys.argv) MainWindow = QtGui.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_()) Please tell me how shall I modify my code?
tagged with: python-2.7
score: 0
tagged with: pyqt
answer count: 1
tagged with: python-3.x
has title: Auto Resize of Label in PyQt4
has answer: http://stackoverflow.com/a/50862394
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/88856353
has text: @CraigBrett unnecessary? I don't get you. Could you elaborate a bit?
type: Comment
score: 0
comment on: http://stackoverflow.com/a/50928509
type: AnswerComment

http://stackoverflow.com/comment/88887742
type: Comment
type: QuestionComment
has text: Works fine for me.....
comment on: http://stackoverflow.com/q/50944866
score: 0

http://stackoverflow.com/a/50909681
score: 1
has comment: http://stackoverflow.com/comment/88820059
has comment: http://stackoverflow.com/comment/88820498
has comment: http://stackoverflow.com/comment/88819780
has comment: http://stackoverflow.com/comment/88821010
has comment: http://stackoverflow.com/comment/88820554
has comment: http://stackoverflow.com/comment/88819886
upvote count: 1
has comment: http://stackoverflow.com/comment/88820931
has comment: http://stackoverflow.com/comment/88820819
has body: I'm working on the assumption that data is aligned at the same columns in each record. I put the header line and a typical line in two distict variables, you are going to read them from a file &gt;&gt;&gt; a = 'Column1 Column2 Column3 Column4' &gt;&gt;&gt; b = 'apple fruits banana fruits orange fruits grapes fruits' i is a list of indices into the header, initially empty, and inside represent the fact that we are inside a column name &gt;&gt;&gt; i = [] &gt;&gt;&gt; inside = False We count the characters and check if we are at the beginning of a column name &gt;&gt;&gt; for n, c in enumerate(a): ... if c == ' ': ... inside = False ... continue ... if not inside: ... inside = True ... i.append(n) &gt;&gt;&gt; i [0, 18, 38, 58] we have the indices of the beginnings of columns, and the beginning of the next one is, in slice notation, also the end of the current one --- we need just the end of the last column but using slice notation we can use the value None &gt;&gt;&gt; [b[j:k].rstrip() for j, k in zip(i,i[1:]+[None])] ['apple fruits', 'banana fruits', 'orange fruits', 'grapes fruits'] of course you have to apply the same indices trick to every data line in the input file. P.S.: you may want to use the itertools.zip_longest method as in [... for j, k in itertools.zip_longest(i, i[1:])] you may want to cache the generator to avoid instantiating it for every data line cached_indices = list(itertools.zip_longest(i, i[1:])) for line in data: c1, c2, c3, c4 = [... for i, j in cached_indices] I tried to implement what I had suggested in a comment below, here it is my best effort... $ cat fetch.py from itertools import count # this import is necessary from io import StringIO # this one is needed to simulate an open file # Your data, notice that some field in the last two lines is misaligned data = '''\ Column1 Column2 Column3 Column4 ---------------------------------------------------------------------------- apple fruits banana fruits orange fruits grapes fruits mango fruit…
type: Answer
has comment: http://stackoverflow.com/comment/88820863
answers question: http://stackoverflow.com/q/50909164
downvote count: 0

http://stackoverflow.com/q/51007517
has answer: http://stackoverflow.com/a/51007919
has comment: http://stackoverflow.com/comment/89008677
tagged with: django
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89009033
has title: Django ImageField - render only the element
possible better answer: http://stackoverflow.com/a/76923646
has comment: http://stackoverflow.com/comment/89008558
tagged with: django-forms
has comment: http://stackoverflow.com/comment/89008937
type: Question
upvote count: 2
answer count: 2
has comment: http://stackoverflow.com/comment/89009025
downvote count: 0
tagged with: django-uploads
favorite count: 0
accepted answer: http://stackoverflow.com/a/51007919
has answer: http://stackoverflow.com/a/76923646
tagged with: python
score: 2
has body: I have a Django form which has an ImageField in it, and I render the field like this in my template: {{ form.my_image_field }} The resulting HTML looks like this: Currently: ....jpg Clear Change: I want to render only the <input element, since I am using the bootstra-fileinput library: https://www.npmjs.com/package/bootstrap-fileinput : Is it possible to do this without writing the tag manually in the template?
has comment: http://stackoverflow.com/comment/89008517

http://stackoverflow.com/a/50970932
score: 0
answers question: http://stackoverflow.com/q/50970266
type: Answer
has comment: http://stackoverflow.com/comment/88958768
has body: You are probably using Python2. In Python2 input() returns an int, for having a string you should use raw_input(): while True: value = raw_input('enter text: ') if value == 'stop': print('bye-bye') break else: print('continue!') Do not use input() in Python2 since it actually evaluates the input, and it can be dangerous. See this other question for the difference from Python3 and Python2 input(). When you change to raw_input(), be sure to save before calling the script

http://stackoverflow.com/comment/89017881
comment on: http://stackoverflow.com/q/51008386
score: 0
has text: pls define * does not work*, do you run cron as 'you' or as another user ?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88787502
comment on: http://stackoverflow.com/q/50893596
has text: Works fine for me too. Did you post the complete code?Error is shown in line 23. Please post the complete code so that error can be traced
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/50954777
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/50938144
type: Answer
has comment: http://stackoverflow.com/comment/88947323
has body: Although I probably would just use NumPy here, pretty similar to J. Martinot-Lagarde's answer, you don't actually have to. First, you can read a single row of comma-separated numbers with just the csv module: with open(path) as f: numbers = map(int, next(csv.reader(f)) … or just string operations: with open(path) as f: numbers = map(int, next(f).split(',')) And then you can interpolate that easily: def interpolate(numbers): last = None for number in numbers: if last is not None: yield (last+number)//2 yield number last=number If you want it to be fully general and reusable, just take a function argument and yield function(last, number), and replace None with sentinel = object(). And now, all you need to do is join the results and write them: with open(outpath, 'w') as f: f.write(','.join(map(str, interpolate(numbers)))) Are there any advantages to this solution? Well, other than the read/split and join/write, it's purely lazy. And we can write lazy split and join functions pretty easily (or just do it manually). So if you ever had to deal with a billion comma-separated numbers instead of a thousand, that's all you'd have to change. Here's a lazy split: def isplit(s, sep): start = 0 while True: nextpos = s.find(sep, start) if nextpos == -1: yield s[start:] return yield s[start:nextpos] start=nextpos+1 And you can use an mmap as a lazily-read string (well, bytes, but our data are pure ASCII, so that's fine): with open(path, 'rb') as f: with mmap.mmap(inf.fileno(), 0, access=mmap.ACCESS_READ) as mm: numbers = map(int, isplit(mm, b',')) And let's use a different solution for lazy writing, just for variety: def icsvwrite(f, seq, sep=','): first = next(seq, None) if not first: return f.write(first) for value in seq: f.write(sep) f.write(value) So, putting it all together: with open(inpath, 'rb') as inf, open(outpath, 'w') as outf: with mmap.mmap(inf.fileno(), 0, access=mmap.ACCESS_READ) as mm: numbers = map(int, isplit(mm, b',')) icsvwrite(outf, map(str, interpolate(numbe…
score: 1

http://stackoverflow.com/a/50936200
has comment: http://stackoverflow.com/comment/88871317
has comment: http://stackoverflow.com/comment/88871288
score: 0
has comment: http://stackoverflow.com/comment/88871244
type: Answer
has comment: http://stackoverflow.com/comment/88871167
has body: Important Step: Open Command Prompt in Windows And Type pip install python3-setuptools If First Step is throwing some Error To solve this,you need to let python know where the pip packages are to do this follow the instructions below First Go to Settings and select Project interpreter, now Click on Add button and switch to manage repositories option and now again press add button and type https://pypi.python.org/pypi in the box and save. Now Restart your pycharm and it will work.
answers question: http://stackoverflow.com/q/50936098
has comment: http://stackoverflow.com/comment/88871484
has comment: http://stackoverflow.com/comment/88871222

http://stackoverflow.com/q/50988918
has comment: http://stackoverflow.com/comment/88973615
favorite count: 0
has body: I am trying to create an ordered tuple list based on rows of information: team stat1 explain1 stat2 explain2 stat3 explain3 green +10 inc due to.. -8 dec due to.. +2 inc due to.. blue -6 dec due to.. +5 inc due to.. +8 inc due to.. red +5 inc due to.. +10 inc due to.. -2 dec due to.. I would like to create an ordered tuple list per team(by absolute value), so 'team' 'blue' would look like: tuple list based on above order: Abs value ordered tuple list: -6: dec due to.. 8: incr due to.. 5: inc due to.. -6: decr due to.. 8: inc due to.. 5: incr due to..
tagged with: python
type: AnsweredQuestion
score: 3
tagged with: list
accepted answer: http://stackoverflow.com/a/50989071
upvote count: 3
has comment: http://stackoverflow.com/comment/88972413
type: Question
has comment: http://stackoverflow.com/comment/88973536
has comment: http://stackoverflow.com/comment/88972652
has answer: http://stackoverflow.com/a/50989071
has comment: http://stackoverflow.com/comment/88972985
has title: Python Ordered Tuple list ranked by absolute value
has comment: http://stackoverflow.com/comment/88973032
tagged with: tuples
tagged with: pandas
has comment: http://stackoverflow.com/comment/88973350
answer count: 1
downvote count: 0

http://stackoverflow.com/q/50956373
score: 0
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/32194900
has body: I'm new to Python and have been struggling with this for hours now, so I thought perhaps someone within the community would be able to help. I have a self signed certificate from a 3rd party enterprise who is not a valid CA which is fine. I've created a .p12 and I'm SUCCESSFULLY able to connect to said 3rd party's HTTP server using C# and .net (great). Using the same .p12, I'm able to create a keystore, import the key, and successfully connect to the 3rd party's HTTP server using Java HttpsURLConnection (also great). Unfortunately, it is not trivial at all to do this in Python! Someone has pointed to this post here: generating cert for use with python requests getting PEM lib error But the answer on this question DOES NOT explain or help why Python is different at all. In C# and Java, I don't need the ca-certificates.crt and I'm not sure how or what the process is of how to create it for Python from a .p12. And I'm certain that I would still need to pass the crt.pem and key.pem which the answer does not use at all, which as I understand is specific to Python (as both C# and Java can use the .p12 instrinsically without any hacking) As such I have followed these instructions from IBM to split the .p12 into a key.pem and a cert.pem https://www.ibm.com/support/knowledgecenter/en/SSZRJV_10.1.0/admin_guide/pac_x509_web_services_python_convert.html I have tried the following Python http libraries to try to make the connection (as imports below): import requests import http.client.HTTPSConnection import httplib2 Code snippet using requests import requests r = requests.get(url, cert=('crt.pem', 'key_nopass.pem')) print(r.text) Code snippet using httplib2 (and from IBM example) https://www.ibm.com/support/knowledgecenter/SSZRJV_10.1.0/admin_guide/pac_x509_web_services_test.html import httplib2 http = httplib2.Http() http.add_certificate('key_nopass.pem', 'crt.pem', '') response, content = http.request(url, 'GET') print(content) Using any of these libraries, I get the followin…
has comment: http://stackoverflow.com/comment/88910813
answer count: 0
duplicate of: http://stackoverflow.com/q/32194900
has comment: http://stackoverflow.com/comment/88910872
type: Question
tagged with: ssl
has title: Python + self signed cert + HTTP not working but works in C#

http://stackoverflow.com/q/50978218
answer count: 1
accepted answer: http://stackoverflow.com/a/51092147
has body: I am using Flask and fbmq, documentation here:https://github.com/conbus/fbmq, for building a messenger bot.I have the correct access and verification codes but I am still getting a 404 NOT FOUND error. Here is my server.pt code: from flask import Flask, request from fbmq import Page app = Flask(__name__) page = Page() @app.route('/webhook', methods=['GET']) def validate(): if request.args.get('hub.mode', '') == 'subscribe' and \ request.args.get('hub.verify_token', '') == '': print("Validating webhook") return request.args.get('hub.challenge', '') else: return 'Failed validation. Make sure the validation tokens match.' @app.route('/webhook', methods=['POST']) def webhook(): payload = request.get_data(as_text=True) print(payload) page.handle_webhook(payload) return "ok" if __name__ == '__main__': app.run( port=5000, debug=True, threaded=True)
tagged with: webhooks
tagged with: python
tagged with: facebook-chatbot
has title: Facebook Messenger Bot webhook verification
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/51092147
tagged with: facebook-messenger
tagged with: flask
score: 0

buttonclick
type: Tag
tag name: buttonclick
tags question: http://stackoverflow.com/q/51006315

http://stackoverflow.com/q/51009203
score: 0
has body: I have two classes: ClassA and ClassB ClassA instantiates an instance from ClassB Is there way to get access inside ClassB to the actual value of the instance variables from ClassA ? The instance variable could change, so giving it to ClassB as a parameter is not the solution. class ClassA(): def __init__(self): self.var_from_A = 1 self.b = ClassB() class ClassB(): def __init__(self): # how to get access to self.var_from_A from ClasseA ?
has answer: http://stackoverflow.com/a/51009676
has comment: http://stackoverflow.com/comment/89011185
type: UnansweredQuestion
tagged with: python
has title: How to get access to the instance variables from an instatiating class
has answer: http://stackoverflow.com/a/51009372
type: Question
answer count: 2

http://stackoverflow.com/comment/88906489
has text: Yes exactly, as it is the discriminator it is trained to recognise if a pair of the initial real image and the labelled initial sketch or the real image with generated sketch are genuine or not. I want to be able to calculate the label too.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50909007

http://stackoverflow.com/comment/88902139
has text: Are you sure D is a two dimensional array? `IndexError: too many indices for array` probably means your array is either 1-D or it is `None`.
comment on: http://stackoverflow.com/a/50938600
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50954397
tagged with: python
has body: I created a JSON file to pass my required data to a web page. Everything is working perfectly. But Whenever I refresh or repeat the action on the same file, JSON send double, triple and so on. I think I need to clear the JSON file whenever I enter into the coding for api action to pass JSON file. How can I do it on Python. @app.route('/patient_cap') def Patient_cap_mat(): global numofCapability, MaxNumDis,capsArray,ListofPatCapability column_array=[] df2 = pd.read_csv('./datafiles/label_network.dat', sep='\s+', header=None) . .// set of coding for required values . . for i in range(len(result_array)): eachpatient=CapabilityMat(result_array[i],df.loc[i].tolist()) entry = {"patient":eachpatient.memid, "capability": eachpatient.capability} ListofPatCapability.append(entry) JsonList = json.dumps(ListofPatCapability) return JsonList How can I clear the json object whenever we call api 'patient_cap'?
type: Question
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/50954521
has title: Py: Why elements from JSON repeat for every action?
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/50954521

http://stackoverflow.com/q/50891485
score: -1
tagged with: text-files
has title: reading a text file in python and printing occurrence of a phrase
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88953011
has comment: http://stackoverflow.com/comment/88952720
has comment: http://stackoverflow.com/comment/88783987
has answer: http://stackoverflow.com/a/50978596
downvote count: 1
has body: I'm struggling to get my code to work. I've been supplied with some variables to work with: The variable P is my file path, designated as content/textfiles/empty.txt; while the variable S is my string, designated as parrot. The end goal is to find out how many times Parrot (S) appears in my text file (P). The following is the variables and information I have been supplied with, and immediately following is my crude code that is attempting to complete my task: import sys P= sys.argv[1] S= sys.argv[2] file = open(P,'r') data = file.read() count = 0 if S in P: count += 1 print(count) file.close() The primary issue is that I am supposed to have a return of 3 for output, but my code is only counting 1 occurrence, but I have no idea why.
type: Question
upvote count: 0
tagged with: string
has comment: http://stackoverflow.com/comment/88783715
favorite count: 0
answer count: 1
tagged with: python

http://stackoverflow.com/q/50940717
accepted answer: http://stackoverflow.com/a/51277799
has comment: http://stackoverflow.com/comment/88908918
has title: create subtracted dataframe using multiple values from the bottom rows
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/89533028
tagged with: dataframe
has body: I have an example df1 below...I need to create a new df_sub by subtracting values at the bottom of each column from the rest of the column. df_sub = i(every value in each column) - (a_squared * Temp + b * Temp + c)** Example df1.head() Temperature A1 A2 A3 A4 25.0 681.51 147.40 409.26 680.83 25.2 615.89 124.34 362.39 618.37 25.4 568.72 95.22 310.37 567.22 25.6 522.08 89.74 272.69 516.53 25.8 480.04 68.20 229.03 477.30 Example df1.tail() Temperature A1 A2 A3 A4 95.0 -102.14 6348.77 2276.56 -2545.60 a 15.26 10.67 -1.87 13.25 b -1016.94 -623.29 29.40 -902.77 c 16557.63 9044.62 715.07 14941.87 a_squared 232.95 113.95 3.53 175.65 This is what I had tried, and the error I get... df_sub = df1.iloc[:-4] - (Temp * df1.iloc[-1, :] + (Temp * df1.iloc[-3, :]) + df1.iloc[-2, :]) Temp is a list like: np.arange(25, 95.2, 0.2) ValueError: operands could not be broadcast together with shapes (96,) (351,) Any help would be appreciated!
has comment: http://stackoverflow.com/comment/89295941
has comment: http://stackoverflow.com/comment/88909241
has answer: http://stackoverflow.com/a/51277799
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/89278759
favorite count: 0
type: Question
tagged with: pandas
has comment: http://stackoverflow.com/comment/88908586
tagged with: python
score: 1

http://stackoverflow.com/comment/89112996
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50979587
has text: please open a new question regardless, so others would benefit.
type: AnswerComment

http://stackoverflow.com/q/50945626
has comment: http://stackoverflow.com/comment/88889645
type: Question
score: 0
has comment: http://stackoverflow.com/comment/88889534
has comment: http://stackoverflow.com/comment/88890975
has title: read_excel function is parsing the wrong columns?
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/88888818
has comment: http://stackoverflow.com/comment/88889183
has comment: http://stackoverflow.com/comment/88889239
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88889340
has body: I have the following table in excel Year Quarter Reg orgID name s1 s2 s3 I am trying to read this table into python, only taking the columns orgID and s3, to do this I have tried p = Path(directory) #read file in nf=pd.read_excel(p, parse_cols=[3,7]) but this is outputting just one column, but that column is Reg. Does anyone know why it would be selecting the wrong columns?
has comment: http://stackoverflow.com/comment/88889073

http://stackoverflow.com/q/50967512
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50967588
has comment: http://stackoverflow.com/comment/88931225
downvote count: 2
has title: local variable "hit" referenced before assignment
type: Question
score: -2
has body: I got this error i don't know why with an another dataset it works. I trying to compute a metrics for a recommender def _verify_hit_top_n(anime_id, recommended_anime, topn): try: index = next(i for i, c in enumerate(recommended_anime) if c == anime_id) except: index = -1 hit = int(index in range(0, topn)) return hit, index for anime_id in user_anime_watched_testset : hit_at_3, index_at_3 = _verify_hit_top_n(anime_id, valid_recs, 3) hits_at_3_count += hit_at_3 anime_metrics = {'hits@3_count':hits_at_3_count} UnboundLocalError Traceback (most recent call last) &lt;ipython-input-103-99d14e064672&gt; in &lt;module&gt;() 1 for anime_id in user_anime_watched_testset : ----&gt; 2 hit_at_3, index_at_3 = _verify_hit_top_n(anime_id, valid_recs, 3) 3 hits_at_3_count += hit_at_3 4 anime_metrics = {'hits@3_count':hits_at_3_count} &lt;ipython-input-102-844edc58db79&gt; in _verify_hit_top_n(anime_id, recommended_anime, topn) 16 except: 17 index = -1 ---&gt; 18 return hit, index 19 20 for anime_id in user_anime_watched_testset: UnboundLocalError: local variable 'hit' referenced before assignment
answer count: 2
has answer: http://stackoverflow.com/a/50967570
upvote count: 0
favorite count: 0

http://stackoverflow.com/comment/115392113
comment on: http://stackoverflow.com/a/65267295
type: Comment
score: 0
type: AnswerComment
has text: Whilst this question has no accepted answer, it was asked 2.5 years ago and has 2 submitted answers.

http://stackoverflow.com/comment/88770944
score: 0
has text: The 10 additional items are the same idea. They are codes for if two fingers are touching, as `0` means that two certain fingers are touching and `1` means that the two fingers are not touching each other. For example, the first item after the 5 original items tells me if the thumb and index are touching.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50884274

http://stackoverflow.com/a/50999322
has body: To send a character sequence to the Search field you have to induce WebDriverWait for the desired element to be clickable as follows: Code Block: from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.keys import Keys browser=webdriver.Firefox(executable_path=r'C:\WebDrivers\GeckoDriver\geckodriver-v0.20.1-win64\geckodriver.exe') browser.get('http://admin.chhs.edu.my/schooladmin/jw/login.php') assert "教务系统" in browser.title def login(): elem = browser.find_element_by_name('txtUserName') elem.send_keys('sportday') elem = browser.find_element_by_name('txtPassWord') elem.send_keys('123456') elem.send_keys(Keys.RETURN) def search(): elem2 = WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input#txtFind"))) elem2.send_keys('14066') elem2.send_keys(Keys.RETURN) login() search() Browser Snapshot:
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50997189

http://stackoverflow.com/comment/88941944
has text: you put a function in `builtins`?! I don't think I'd recommend that.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50972769
score: 1

http://stackoverflow.com/comment/88960321
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50982256
has text: Great and fast answer. I think I understand a little bit better now some concepts. Thank you!
type: AnswerComment

http://stackoverflow.com/q/50978309
has body: I have created many custom commands by extending the command class in setuptools python library. The commands are like Clean, RunTest (each individual class with their run(self) method). I have now created a RunAll Class which if also sub classing the Command class and needs to call other commands. Let me show some of my code so as to make it more clear. class Clean(Command): description = 'Cleans the build' user_options = [] def initialize_options(self): pass def finalize_options(self): pass def clean(self): print("Cleaning") def run(self): self.clean() There are some more classes like these like Runtests etc. which are of similar format. Now I create a class called as RunAll which runs all these commands (trying to simulate ant all command). So the code is like. class RunAll(Command): """ runs few specific commands mentioned """ description = 'Runs specific commands mentioned' user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): # init,clean,version,build,test,dist Clean().clean() Version().printVersion() RunTests().runtests() Dist().dist() Now when I run python setup.py runall I get the following error. File "C:\Users\rsareen\AppData\Local\Programs\Python\Python36\lib\site-packages\setuptools\__init__.py", line 129, in setup return distutils.core.setup(**attrs) File "C:\Users\rsareen\AppData\Local\Programs\Python\Python36\lib\distutils\core.py", line 148, in setup dist.run_commands() File "C:\Users\rsareen\AppData\Local\Programs\Python\Python36\lib\distutils\dist.py", line 955, in run_commands self.run_command(cmd) File "C:\Users\rsareen\AppData\Local\Programs\Python\Python36\lib\distutils\dist.py", line 974, in run_command cmd_obj.run() File ".\setup.py", line 58, in run Clean().clean() TypeError: __init__() missing 1 required positional argument: 'dist' Its not able to get the dist parameter in the Command class. Basically i am not able to instantiate the commands. But when i do python setup.py clean, it runs perf…
has answer: http://stackoverflow.com/a/50978482
accepted answer: http://stackoverflow.com/a/50978482
type: AnsweredQuestion
score: 1
tagged with: setuptools
type: Question
has title: A runall command in setup.py
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python-3.x
upvote count: 1
tagged with: python
tagged with: design-patterns

http://stackoverflow.com/comment/88844109
type: AnswerComment
comment on: http://stackoverflow.com/a/50908925
score: 0
type: Comment
has text: So I have a 2500 x 4000 pandas dataframe, if I try to export, it my Ram usages explodes (over 8GB). For small dataframes it works fine. Am I doing something wrong?

http://stackoverflow.com/a/51010842
score: 0
answers question: http://stackoverflow.com/q/51010502
has comment: http://stackoverflow.com/comment/89049850
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51010502
has body: It's super easy with pandas, but if you prefer not to use other modules, that's fine as well :) I've added the code for both pandas and for manually iterating over the data: import pandas as pd import csv def main_pandas(path_to_csv: str, target_path: str): df = pd.read_csv(path_to_csv, encoding='utf-8') df['tokens'] = df['Content'].apply(lambda x: len(x.split())) sub_df = df'ID', 'tokens' sub_df.to_csv(target_path, index=False) def main_manual(path_to_csv: str, target_path: str): with open(path_to_csv, 'r') as r_fp: csv_reader = csv.reader(r_fp) next(csv_reader) # Skip headers with open(target_path, 'w') as w_fp: csv_writer = csv.writer(w_fp) csv_writer.writerow(['Text ID', 'tokens']) # Write headers for line in csv_reader: text_id, text_content = line csv_writer.writerow([text_id, len(text_content.split())]) if __name__ == '__main__': main_manual('text.csv', 'tokens.csv')
type: Answer

http://stackoverflow.com/a/50882470
has comment: http://stackoverflow.com/comment/88825349
has comment: http://stackoverflow.com/comment/88826011
type: AcceptedAnswer
downvote count: 0
has body: The big villains here are axes.hold(False) and axes.cla(). They are responsible for clearing the axes and figure, which (generally) will reset the plot view. With those out of the way, you can properly use self.axes.autoscale(enable=False), which I recommend you put after your first plot in compute_initial_figure(), so the plot is at least somewhat scaled at the start. Then, to be able to clear your previous plots, you can create another attribute for the MyMplCanvas class, maybe self.plotted_line or something like that, initialized with None. Everytime you call self.axes.plot(...), assign the return value to self.plotted_line, like so: self.plotted_line, = self.axes.plot(...). Notice the comma after self.plotted_line, which is one of the ways to assign only the first return value, which is the one you're interested in. Lastly, right before each new plot, check and call if self.plotted_line is not None: self.plot.remove() which will effectively remove the previous plot. The canvas classes will look something like this (changes were minor). class MyMplCanvas(FigureCanvas): def __init__(self, parent=None, width=5, height=4, dpi=100): fig = Figure(figsize=(width, height), dpi=dpi) self.fig = fig ### self.axes = fig.add_subplot(111) self.plotted_line = None self.compute_initial_figure() FigureCanvas.__init__(self, fig) self.setParent(parent) FigureCanvas.setSizePolicy(self, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) def compute_initial_figure(self): pass class MyDynamicMplCanvas(MyMplCanvas): def __init__(self, *args, **kwargs): MyMplCanvas.__init__(self, *args, **kwargs) timer = QtCore.QTimer(self) timer.timeout.connect(self.update_figure) timer.start(1000) def compute_initial_figure(self): self.plotted_line, = self.axes.plot([0, 1, 2, 3], [1, 2, 0, 4], 'b') self.axes.autoscale(enable=False) def update_figure(self): l = [random.randint(0, 10) for i in range(4)] if self.plotted_line is not None: self.plotted_line.…
answers question: http://stackoverflow.com/q/50879977
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/50879977
upvote count: 2

http://stackoverflow.com/q/50933983
has comment: http://stackoverflow.com/comment/88868172
type: AnsweredQuestion
has body: I am very new to Python 3. I have written a script and used pyinstaller to convert it to an EXE. The script attempts to read from a text file named file.txt in the same directory as the EXE. This works just fine when running the EXE from task scheduler while the workstation is logged in and not locked. However, if I try to run the EXE from task scheduler with the user logged in and the workstation locked, I get the error: [Errno 2] No such file or directory: 'file.txt'. This is my python simplified down to the current error (literally just put this in a new python file and ran it the same way and get the same error): with open('file.txt', 'rb') as myfile: readfile = myfile.read() print(readfile) I have tried to search for this problem, but all I can find is how to lock/unlock a workstation with python or how to lock/unlock a file with python. I am fairly certain this isn't a python problem and may just be an intended effect of using task scheduler when the station is locked but I am hoping there is a setting I can change to allow access to files when the workstation is locked or something else.
tagged with: taskscheduler
type: Question
has title: Windows scheduled task python read file when computer locked
has answer: http://stackoverflow.com/a/50935129
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/88867997
tagged with: windows
tagged with: python
has comment: http://stackoverflow.com/comment/88868550
accepted answer: http://stackoverflow.com/a/50935129
has comment: http://stackoverflow.com/comment/88866687

http://stackoverflow.com/q/50867435
favorite count: 0
tagged with: python-3.x
has body: I am trying to get subnet for IP address I have. Eg : 1 Subnet mask : 255.255.255.0 Input : 192.178.2.55 Output : 192.178.2.0 2 Subnet mask : 255.255.0.0 Input : 192.178.2.55 Output : 192.178.0.0 Currently, the way I do it (for subnet 255.255.255.0) ip = '192.178.2.55' subnet = '.'.join(ip.split('.')[:2]) + '.0.0' subnet '192.178.0.0' I see python has ipaddress library. However I could not find a method that could do the above task. Bonus : Since ipaddress supports IPv4 and IPv6, if the same function could be used for both.
has answer: http://stackoverflow.com/a/50867508
accepted answer: http://stackoverflow.com/a/50867508
tagged with: python
tagged with: ip-address
type: AnsweredQuestion
downvote count: 0
type: Question
possible better answer: http://stackoverflow.com/a/50867500
score: 10
has answer: http://stackoverflow.com/a/50867500
has title: Get subnet from IP address
answer count: 2
upvote count: 10

http://stackoverflow.com/q/50886451
has title: Ploting nested lists in dictionary - python
possible better answer: http://stackoverflow.com/a/50887880
has body: My dataset is looking something like this: {'Berlin': [[1, 333]], 'London': [[1, 111], [2, 555]], 'Paris': [[1, 444], [2, 222], [3, 999]]} And for each city now I need to make scatter plot, for example, the plot of Paris should have on x-axis numbers: 1 2 3, and on the y-axis: 444 222 999. I have a really big dataset, so I would like to have 5 cities per plot. My code is looking something like this, but on the output I get empty plots. for town in dictionary_town: x=[] y=[] i+=1 save_plot = 'path'+str(i)+'.png' for list in town: x.append(list[0]) y.append(list[1]) plt.style.use('dark_background') plt.figure() plt.plot( kind='scatter',x = x, y=y,label=town, s=30,figsize=(50, 20), fontsize=25, alpha=0.5) plt.ylabel("Population", fontsize=50) plt.title(str(i), fontsize=50) legend = plt.legend(fontsize=30, markerscale=0.5, ncol=1) plt.savefig(save_plot) plt.close()
tagged with: scatter-plot
answer count: 2
tagged with: pandas
downvote count: 0
has answer: http://stackoverflow.com/a/50887728
favorite count: 0
accepted answer: http://stackoverflow.com/a/50887728
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50887880
tagged with: python
score: 2
upvote count: 2
type: Question
type: AnsweredQuestion

http://stackoverflow.com/q/50868523
has title: I'm using python 2.7. i tried all ways to setup the xlrd file, but still i'm getting the error: ImportError: No module named xlrd >>>
tagged with: python-2.7
score: 0
tagged with: python
answer count: 0
has body: import xlrd from lxml import etree I'm using python 2.7. i tried all ways to setup the xlrd file, but still i'm getting the error: ImportError: No module named xlrd >>> Also i'm unable to run pip from cmd prompt, though pip is installed.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88740072
has comment: http://stackoverflow.com/comment/88738975
has comment: http://stackoverflow.com/comment/88740085
has comment: http://stackoverflow.com/comment/88740025
type: Question

http://stackoverflow.com/comment/88783602
comment on: http://stackoverflow.com/q/50891402
has text: Why exactly don't you want to keep the token inside of the code? What exactly is the error? Does the app on heroku crash?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50982757
has comment: http://stackoverflow.com/comment/88961866
has comment: http://stackoverflow.com/comment/88980027
has comment: http://stackoverflow.com/comment/88966777
has answer: http://stackoverflow.com/a/51002517
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88961555
downvote count: 0
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88980062
has title: Django how to show available item only in CBV List view?
type: Question
has comment: http://stackoverflow.com/comment/88981806
has comment: http://stackoverflow.com/comment/88966924
has comment: http://stackoverflow.com/comment/88965355
tagged with: django
has comment: http://stackoverflow.com/comment/88961650
tagged with: python
has comment: http://stackoverflow.com/comment/88961730
has body: I have two models, Car and Booking. A Car is a ForeignKey field in Booking model. If Car is booked, it's still showing in the Car list. I have is_available_car model field in Car model set to default=True. If Car is booked, it will not show until it's unbooked. I have a booking form and if Car is booked, user cannot book it and it doesn't shown in the CarListView Help me please. Thank you. models.py class Booking(models.Model): booking_name = models.CharField(max_length=240, null=False) customer_name = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='book_customers' ) book_car = models.ForeignKey(Car, on_delete=models.CASCADE, related_name='book_car') booking_start_date = models.DateTimeField(auto_now_add=True, blank=False) booking_end_date = models.DateTimeField(blank=True, null=True) rental_price = models.IntegerField(blank=False, null=False) times_pick = models.TimeField(blank=True) is_approved = models.BooleanField(default=False) def __str__(self): return self.booking_name def get_absolute_url(self): return reverse("buggy_app:detail",kwargs={'pk':self.pk}) views.py class BookingView(FormView): template_name = 'buggy_app/booking.html' form_class = BookingForm model = Booking success_url = reverse_lazy('index') def form_valid(self, form): form.save() return super(BookingView, self).form_valid(form) def get_context_data(self, **kwargs): # kwargs['car'] is the car booking now! try: kwargs['car'] = Car.objects.get(id=self.request.GET.get('car', '')) except (Car.DoesNotExist, ValueError): kwargs['car'] = None return super(BookingView, self).get_context_data(**kwargs) def get_initial(self): initial = super(BookingView, self).get_initial() if 'car' in self.request.GET: try: initial['book_car'] = Car.objects.get(id=self.request.GET['car']) except (Car.DoesNotExist, ValueError): pass return initial class CarListView(ListView): context_object_name = 'cars' model = Car def get_queryset(self): qs = super(CarListView, self).get_queryset() qs = qs.filter(is_…
has comment: http://stackoverflow.com/comment/88997636
has comment: http://stackoverflow.com/comment/88981471
accepted answer: http://stackoverflow.com/a/51002517
has comment: http://stackoverflow.com/comment/88980458
tagged with: django-views
has comment: http://stackoverflow.com/comment/88965426
has comment: http://stackoverflow.com/comment/88971852
has comment: http://stackoverflow.com/comment/88966730
has comment: http://stackoverflow.com/comment/88983105
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/88966826
has comment: http://stackoverflow.com/comment/88960878
has comment: http://stackoverflow.com/comment/88960757
has comment: http://stackoverflow.com/comment/88997633
has comment: http://stackoverflow.com/comment/88966041
has comment: http://stackoverflow.com/comment/88961800
tagged with: django-models
has comment: http://stackoverflow.com/comment/88979958
has comment: http://stackoverflow.com/comment/88980171

http://stackoverflow.com/comment/88936513
type: QuestionComment
score: 0
has text: well read that line of the file and tell us what is there :)
comment on: http://stackoverflow.com/q/50969804
type: Comment

http://stackoverflow.com/a/51073529
has comment: http://stackoverflow.com/comment/90096702
has body: I changed your files a bit, for clarity. a.h: #pragma once void funcA(); a.cpp: #include <iostream> void funcA() { std::cout << __FILE__ << " " << __LINE__ << " " << __FUNCTION__ << std::endl; } a.i: %module a %{ #include "a.h" %} %include "a.h" b.h: #pragma once void funcB(); b.cpp: #include "a.h" #include <iostream> void funcB() { std::cout << __FILE__ << " " << __LINE__ << " " << __FUNCTION__ << std::endl; funcA(); } b.i: %module b %{ #include "b.h" %} %include "b.h" setup.py: from distutils.core import setup from distutils.extension import Extension a = "a" b = "b" ext_a = Extension("_" + a, [a + ".i", a + ".cpp"], swig_opts=("-c++",), extra_compile_args=["-g"]) ext_b = Extension("_" + b, [b + ".i", b + ".cpp"], swig_opts=("-c++",), extra_compile_args=["-g"]) setup( name="test", version="1.0", ext_modules=[ext_a, ext_b], py_modules=[a, b], ) What happens (simplified) when calling b.funcB (only the stacktrace, imports left aside). Each step invokes the next: funcB from module b (b.py) funcB from module _b (_b.so, or _b.cpython-35m-x86_64-linux-gnu.so) Everything from here happens in C (or C++) Current funcB is different than the one from b.cpp: it's generated by SWIG and its name is _wrap_funcB Previous bullet also applies to funcA and a.cpp funcB from b.cpp funcA from a.cpp The problem is that the code from step #4. is not in the module _b, and it will fail at runtime. But things are a little bit stranger: the failure (core dump) doesn't appear when funcB is called but at module (b -> _b) import time (I think this happens because of SWIG's behind the scene magic), as seen below. Output: [cfati@cfati-ubtu16x64-0:~/Work/Dev/StackOverflow/q050938128]> ~/sopr.sh ### Set shorter prompt to better fit when pasted in StackOverflow (or other) pages ### [064bit prompt]> ls a.cpp a.h a.i b.cpp b.h b.i setup.py [064bit prompt]> python3 setup.py build > /dev/null 2>&1 [064bit prompt]> echo $? 0 [064bit prompt]> ls a.cpp a.h a.i a.py a_wrap.cpp b.cpp b.h b.i b.py build b_wrap…
has comment: http://stackoverflow.com/comment/108833070
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/110253683
upvote count: 7
answers question: http://stackoverflow.com/q/50938128
score: 7

http://stackoverflow.com/comment/88971965
score: 0
has text: @FHTMitchell I felt like manipulating a string version of an handled type was kind of messy. I mean were talking about two iteration of the same language, They wanted to unified the two types. I really thought that `int(test)` would be supported. I guess I'm wrong...
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50988517

http://stackoverflow.com/a/50858259
has comment: http://stackoverflow.com/comment/88719206
accepted answer of: http://stackoverflow.com/q/50858009
has comment: http://stackoverflow.com/comment/125724543
upvote count: 18
score: 18
downvote count: 0
has body: I think you are looking to draw an antialiased outline. You can do that by setting the lineType parameter: cv2.circle(img,(H,V), S, (0,0,255), -1, lineType=cv2.LINE_AA)
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50858009
type: Answer

http://stackoverflow.com/q/50897837
has title: Python2.7. Access an HTTPS Website and retrieve content
linked to: http://stackoverflow.com/q/8049520
tagged with: ssl-certificate
answer count: 2
has answer: http://stackoverflow.com/a/50897890
duplicate of: http://stackoverflow.com/q/8049520
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/50897890
accepted answer: http://stackoverflow.com/a/50898260
tagged with: python
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88795370
upvote count: 2
tagged with: web-scraping
tagged with: python-requests
has body: Good Morning All, I've been trying to access a website through Python 2.7 that is HTTPS but have not been able to access the content, and days of research have not helped out. The website is: https://www.cioh.org.co/. In Python, I'd like to be able to access the page and retrieve all the HTML content. In the past, I'd use the ssl module and add the following lines of code at the top: import ssl ssl._create_default_https_context = ssl._create_unverified_context This time, that doesn't work and I get the error: SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:661) when using the requests module with requests.get('https://www.cioh.org.co/') From certain websites, some pointed out to use: import requests r = requests.get(URL, verify=False) print r.text I've tried that as well but it doesn't actually scrape the content. It simply retrieves the internal header information from the website as such: &lt;html&gt; &lt;head&gt; &lt;META NAME="robots" CONTENT="noindex,nofollow"&gt; &lt;script src="/_Incapsula_Resource?SWJIYLWA=5074a744e2e3d891814e9a2dace20bd4,719d34d31c8e3a6e6fffd425f7e032f3"&gt; &lt;/script&gt; &lt;body&gt; &lt;/body&gt;&lt;/html&gt; The printed response is nothing like the website. Through countless research, I've tried using the certifi module. I also installed OpenSSL and extracted .crt, .key, and .pem files (and tried using them) and still no luck. I can expand upon further research I've done if need be. The website, if using any browser can be easily accessed. Any help would be greatly appreciated. Side Note: This is my first time creating an account and asking a question. If I wasn't clear with anything, please let me know. Thanks in advance.
tagged with: https
type: Question
has answer: http://stackoverflow.com/a/50898260

http://stackoverflow.com/q/50913958
type: Question
has comment: http://stackoverflow.com/comment/88830042
has body: I don't know if I am just searching for the wrong terms but I cannot find any examples of code to do this. I have a surface that is almost flat but not quite and would like to "unfold" or "unwrap" it so that it is all in one plane while keeping the distance between points the same. From what I understand this process is called developing a surface, but all I can find are old mathematical papers on the process would be quite a bit of work trying to recreate. Can't really provide any code for it but I have data in the form of points like coords = [(x_1, y_1, z_1), (x_2, y_2, z_2),..., (x_n, y_n, z_n)] It doesn't seem like it should be that hard to do but maybe I am mistaken, any input?
tagged with: python
has comment: http://stackoverflow.com/comment/88828053
has comment: http://stackoverflow.com/comment/88828313
upvote count: 2
tagged with: plane
tagged with: projection
tagged with: 3d
has title: Projecting a 3D surface onto a 2D plane (unfolding/unwrapping) in Python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88829119
tagged with: surface
score: 2
answer count: 0
downvote count: 0
favorite count: 0

http://stackoverflow.com/q/50920360
favorite count: 0
has title: boto3 version of list-objects-v2 --query command in AWS CLI
tagged with: python
tagged with: python-3.x
upvote count: 3
type: UnansweredQuestion
score: 3
has body: Would like to know the python boto3 code for below AWS CLI aws s3api list-objects-v2 \ --bucket myBucket \ --prefix path1/path2 \ --query 'reverse(sort_by(Contents,&amp;LastModified))[0]' i didnt see any query option for list_objects_v2 https://boto3.readthedocs.io/en/stable/reference/services/s3.html#S3.Client.list_objects_v2
tagged with: amazon-s3
has answer: http://stackoverflow.com/a/50920463
type: Question
answer count: 1
downvote count: 0
tagged with: boto3
tagged with: amazon-web-services

http://stackoverflow.com/a/51009922
score: 3
has comment: http://stackoverflow.com/comment/89037611
has comment: http://stackoverflow.com/comment/89045060
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89047719
type: Answer
has body: You can combine your two examples and the following should work: query_tag = Entry.select(Entry.tag_name).distinct() And the template: {% for entry in object_list %} &lt;p&gt;{{ entry.tag_name }}&lt;/p&gt; {% endfor %} Because, even though you've only selected one column, Peewee will still be returning Entry objects. The Entry objects will only have the "tag_name" field populated, though.
accepted answer of: http://stackoverflow.com/q/50999447
upvote count: 3
answers question: http://stackoverflow.com/q/50999447

http://stackoverflow.com/q/50954671
score: 0
has comment: http://stackoverflow.com/comment/88906972
answer count: 1
has comment: http://stackoverflow.com/comment/88907197
has answer: http://stackoverflow.com/a/50954726
has title: Python call inner function
type: UnansweredQuestion
tagged with: python
type: Question
has body: I have the following problem: I have a function that holds another function inside (see code bellow). I need to call the function getFastaEntry with a parameter filename set in the top level function.I tried to call it with generate_fasta_reader(filename).getFastaEntry(), but I get the error message "function object has no attribute getFastaEntry()". Can anybody tell me how I can call the inner function? def generate_fasta_reader(filename, gzipped=False, strip=True): def getFastaEntry(): filehandle = None

http://stackoverflow.com/a/50965381
downvote count: 0
has comment: http://stackoverflow.com/comment/88927130
type: Answer
has body: Try using urllib module. Ex: import urllib def php(script_path): urlData = urllib.urlopen(script_path) return urlData.read()
upvote count: 3
accepted answer of: http://stackoverflow.com/q/50965278
answers question: http://stackoverflow.com/q/50965278
score: 3
type: AcceptedAnswer

http://stackoverflow.com/q/50907696
answer count: 1
accepted answer: http://stackoverflow.com/a/50916635
has comment: http://stackoverflow.com/comment/88815623
tagged with: string
has title: Clustering similar texts using Affinity Propagation and creating a cluster plot
favorite count: 0
has body: I have a list of universities to be clustered based on similarity. For example, this string "University of Melbourne" and this string "University of Meelbourne" is the same, but has a spelling error. I would like to group these similar strings together using Affinity Propagation (Scikit Learn) technique. Do I need to transform the Strings first, using Word2VEC before applying Affinity Propagation on SciKit learn ? Is there a good tutorial which could show me how to accomplish this?
tagged with: python
has comment: http://stackoverflow.com/comment/88815266
score: -1
tagged with: text
type: AnsweredQuestion
downvote count: 1
has answer: http://stackoverflow.com/a/50916635
type: Question
tagged with: cluster-analysis
has comment: http://stackoverflow.com/comment/88815670
upvote count: 0

http://stackoverflow.com/q/50898115
has title: Python return extra value from decorator
type: Question
score: 1
upvote count: 1
downvote count: 0
answer count: 1
tagged with: decorator
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: I have some functions and I want to do some computation based on the argument values passed to it in a decorator. I am able to achieve this but the decorator populates an important object which I would like to reuse later on. eg.. def my_awesome_decorator(*d): how_do_i_return_this_object_which_got_created_here def wrapping_function(func): def wrapper(*args, **kwargs): ... return wrapper return wrapping_function class A: @my_awesome_decorator(d) def fun(a, b, c): ... I want the object to be easily accessible using object_A.how_do_i_return_this_object_which_got_created_here
tagged with: python-decorators
has answer: http://stackoverflow.com/a/50898209

http://stackoverflow.com/a/50981719
has comment: http://stackoverflow.com/comment/88963586
downvote count: 0
score: 4
type: Answer
upvote count: 4
has comment: http://stackoverflow.com/comment/88963387
has comment: http://stackoverflow.com/comment/88969646
has comment: http://stackoverflow.com/comment/88959654
has comment: http://stackoverflow.com/comment/88963264
has comment: http://stackoverflow.com/comment/88963042
has body: Note that this is is very broadly formulated, and your question should be put on hold probably, but I try to give a brief summary of what you are trying to ask: "How does a real production system work?" Well, it always depends on the scale of your product, and in what way you are using ML/AI in your system. For the most parts, you would deploy a model on your server or app. Note that deployment does NOT lineraly scale with the amount of training data you have. Rather, the size of your network is solely determined by the number of activations in your network. Note that, after training, you might not even need as much storage space, since for example CNNs have a very limited number of connections, while retaining a much larger number during training. I can highly recommend Roger Grosse's slides on the size of a network. This also directly relates to the second point. "How to avoid re-training?" From what I am aware of, most systems will not be retrained on a regular basis, at least for the smaller scale. This means that a network will mostly run in inference mode only, which has the aforementioned benefit of what I mentioned about the size of the network (and the time it takes to compute a result). Then again, this also highly depends on the specific task for which you are deploying a ML model. Image classification on "standard categories" have the benefit of already delivering quite substantial models (AlexNet, Inception, ResNet,...), whereas a model for machine translation mostly depends on your specific domain and vocabulary. "How would I go about re-training?" This is actually the tricky part, which has a significant field called "bandit learning" behind it. The problem is that most of your incoming "new" data will be unlabeled, i.e. cannot be used for the direct integration into a new training phase. Instead, you rely on feedback from users to give you a sense of what was wrong or right. Then again, not every user has the same ratings for the same machine transla…
answers question: http://stackoverflow.com/q/50981478
has comment: http://stackoverflow.com/comment/88963690

http://stackoverflow.com/q/50964878
has body: I am running Windows 10 with Anaconda 3. I attempted to get to the Anaconda Navigator through clicking on navigator app in Explorer (Anaconda3\pkgs\anaconda-navigator-1.8.7-py36_0) but that only brings up a flash of what I assume is the command window (because it's too fast to see) and then nothing happens. I can use the Anaconda prompt and so I tried running navigator using 'anaconda-navigator' and it gives error line: ".....is not recognized as an internal or external command, operable program or batch file." I tried typing 'jupyter notebook' into the command line but the message is: Error executing Jupyter command 'notebook': [Errno 'jupyter-notebook' not found] 2 This has happened multiple times with me uninstalling and reinstalling Anaconda. How do I fix this as it seems to be a serious problem as almost nothing works?
has answer: http://stackoverflow.com/a/55225056
score: 2
has title: Can't run Anaconda from command line (or anywhere else)
tagged with: anaconda
type: Question
answer count: 3
has answer: http://stackoverflow.com/a/57693472
has answer: http://stackoverflow.com/a/50968593
downvote count: 0
tagged with: python-3.6
favorite count: 0
tagged with: python
tagged with: jupyter-notebook
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/comment/88738598
type: QuestionComment
has text: See the [mcve] guidelines -- a good code sample in a question will be the shortest possible thing that lets others reproduce a clear problem, with actual and desired output clearly distinguished. At least 90% of the code gives no appearance of having anything to do with the question.
score: 2
type: Comment
comment on: http://stackoverflow.com/q/50868261

http://stackoverflow.com/comment/88778553
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50888630
has text: use http://regex101.com or similar sites - try `r'(05\d+-?\d{7})'` if you include groups aka (...) they will dictate whats matched
score: 0

http://stackoverflow.com/q/50935433
has title: Can't retweet with tweepy - Python
type: UnansweredQuestion
tagged with: python
tagged with: tweepy
tagged with: twitter
has answer: http://stackoverflow.com/a/50935525
type: Question
has body: i'm trying to create a bot to retweet #dogs. This is my code import tweepy consumer_key = 'XXXXXXXXX' consumer_secret = 'XXXXXXXXXXXXXXXXXXXXXXXX' access_token = 'XXXXXXXXXXXXXXXXXXXXXXXXXXX' access_token_secret = 'XXXXXXXXXXXXXXXXXXXXXX' auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) user = api.me() print(user.name) def main(): search = ('#dogs') for tweet in tweepy.Cursor(api.search, search).items(1): try: tweet.retweet() print('Tweet Retweeted') except tweepy.TweepError as e: print(e.reason) except StopIteration: break main() When i run it, i get my username from (user.name) but it never sends the retweet. CMD output: C:\Users\xd\Desktop&gt;python rt_bot.py Dom
score: 0
answer count: 1

http://stackoverflow.com/q/50979892
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88963109
has comment: http://stackoverflow.com/comment/88958253
score: 0
has body: I'm processing the LUNA16 dataset. This data set has annotations.csv which contains x,y,z coordinates and the diameter of nodules related to each patient. Usually a 3D CT scan consists of different number of slices but these annotations are provided to the scan but not to slices. So I need to annotate these slices based on the nodule location and the diameter. But I was unable to find any resources to do this. Cn someone help me to how to start this PS: https://luna16.grand-challenge.org/data/ - link for the data set and the annotations.csv consists all the location with nodule diameter
favorite count: 0
has title: LUNA16 slice annotations
type: UnansweredQuestion
tagged with: python
answer count: 0
upvote count: 1

http://stackoverflow.com/q/50876767
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/88774211
has comment: http://stackoverflow.com/comment/88759237
type: Question
tagged with: python
linked to: http://stackoverflow.com/q/37445865
tagged with: gmail-api
tagged with: python-3.x
has title: How to get content['payload']['body']['data'] first mail by gmail api
has body: I'm trying to get mail body by gmail api. message = self.service.users().messages().get(userId=user, id=i,format='full').execute() When I put my last email Id. Always I can't find contents in content['payload']['body']['data'] It's shows like this. "body": { "size": 0 } Of course it has message body. I can get sumally by content['snippet'] ,but I can't get the message body body. If you have any idea about this, please help me.
upvote count: 2
answer count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88792156
has answer: http://stackoverflow.com/a/50971564
score: 2

http://stackoverflow.com/comment/89001681
type: AnswerComment
has text: Sorry. My fault. Don't pass `self` to `super().__init__()`. Answer fixed.
type: Comment
comment on: http://stackoverflow.com/a/50995466
score: 1

http://stackoverflow.com/q/50939402
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
upvote count: 0
has comment: http://stackoverflow.com/comment/88877224
has title: TypeError: 'range' object does not support item assignment how to fix this
type: Question
tagged with: opencv
has comment: http://stackoverflow.com/comment/88876998
score: -2
has answer: http://stackoverflow.com/a/50939498
downvote count: 2
answer count: 1
has body: avail = range(n_connections) for i in range(0,n_entities): for j in range(0,n_connections): if avail[j] != -1: #checking availability if (((dat[j][1] == 1)|((dat[j][1] == 11))) &amp; (dat[j][2] == i)): if ((dat[j][3] == 3)|(dat[j][3] == 13)): avail[j] = -1 # here error is coming how to fix this # n_connections = len(connectionx - 1) for k in range (0,n_connections): if avail[k] != -1: #checking availability if (((dat[k][1] == 3)|((dat[k][1] == 13))) &amp; (dat[k][2] == dat[j][4])): avail[k] = -1 # booking
favorite count: 0

http://stackoverflow.com/a/50988814
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 2
has body: You can use check equality of your series with a shifted version of itself via pd.Series.shift. Note the first item in the series must be manually set to False, if this is a requirement. df['change'] = df['X'] != df['X'].shift() df['change'].iat[0] = False print(df) ID X change 0 1 0 False 1 2 0 False 2 3 1 True 3 4 1 False 4 7334 -19 True 5 7335 -19 False 6 7336 -20 True 7 7337 -20 False
score: 2
answers question: http://stackoverflow.com/q/50988726
accepted answer of: http://stackoverflow.com/q/50988726

http://stackoverflow.com/q/50860417
type: UnansweredQuestion
tagged with: python
answer count: 0
score: 1
upvote count: 1
type: Question
tagged with: python-2.5
has title: How to use pymouse on linux?
downvote count: 0
tagged with: python-2.x
has body: I have installed pymouse and xlib in python2.5. However, when I run pip list, only pymouse can be seen, and when I import pymouse, it says: no module named pymouse How can I fix this?
favorite count: 0
tagged with: linux

http://stackoverflow.com/comment/88830428
score: 1
type: Comment
type: QuestionComment
has text: You could check out the branch `release_4.3`.
comment on: http://stackoverflow.com/q/50888389

http://stackoverflow.com/comment/88815900
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50906624
type: QuestionComment
has text: Well, take a look [here](https://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html). You'll need to add a CRLF at the end of your line to say the least. "*The Request-Line begins with a method token, followed by the Request-URI and the protocol version, and ending with CRLF. The elements are separated by SP characters. No CR or LF is allowed except in the final CRLF sequence.*"

http://stackoverflow.com/a/50857136
has body: my_string = """Strings are gameon amongst gameon the most popular data types in Python. We can create the strings by enclosing characters briton in quotes. Python treats briton single quotes the same as double quotes.""" di={} def count_words(string): for word in string.split(): if word.endswith("on") == True: if word in di: di[word]+=1 else: di[word]=1 string = string.replace(word,'') #print(string) count_words(my_string) for i in di: print(i,di[i]) You can use a dictionary to achieve the same.
upvote count: 1
has comment: http://stackoverflow.com/comment/88740315
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88729676
accepted answer of: http://stackoverflow.com/q/50857000
answers question: http://stackoverflow.com/q/50857000
type: Answer
score: 1

http://stackoverflow.com/comment/88929534
has text: They should be left as is without change.
comment on: http://stackoverflow.com/q/50966579
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50920964
tagged with: statistics
has body: I got a question like this: Question screenshot. I've been working on it with Python but the result seems dubious. Could you please check what's wrong with the code? import numpy as np import statsmodels.api as sm import statsmodels.formula.api as smf sig = 1 # standard deviation of the distributions nsim = 100 # number of simulations tvec = [10, 25, 50, 100, 250, 1000] # how many different inputs are used? store the number in the vector. nvec = [1, 2, 3, 5, 10] # how many observations for each sample? holding_place = np.zeros((nsim, len(tvec), len(nvec))) # stores the rsquared number of the regression. for isim in range(nsim): for tdx, t in enumerate(tvec): y = np.zeros((t, 1)) for i in range(t): # y[0] = 0 + np.random.normal(0, sig) y[i] = y[i-1] + np.random.normal(0, sig) # get new numbers for ndx, n in enumerate(nvec): x = np.zeros((t, n)) for i in range(t): x[i, ndx] = x[i-1, ndx] + np.random.normal(0, sig) x = sm.add_constant(x) model = smf.OLS(y, x).fit() holding_place[isim, tdx, ndx] = model.rsquared print(holding_place.mean(0)) # the average rsquared for the (n,t) combination
tagged with: python
answer count: 0
type: UnansweredQuestion
tagged with: regression
has comment: http://stackoverflow.com/comment/88842035
tagged with: statsmodels
has comment: http://stackoverflow.com/comment/88856071
type: Question
tagged with: numpy
score: 0
has title: What seems wrong with my linear regression statsmodel?

http://stackoverflow.com/comment/88993078
comment on: http://stackoverflow.com/a/50999309
type: AnswerComment
score: 0
type: Comment
has text: @EirNym Do you not see that `seq = PySequence_Fast`, or do you not know [what that function does](https://docs.python.org/3.7/c-api/sequence.html#c.PySequence_Fast)? (Also, you're looking at `bytes.join`, not `str.join`, but [that does the same thing](https://github.com/python/cpython/blob/6f0eb93183519024cb360162bdd81b9faec97ba6/Objects/unicodeobject.c#L9870).)

http://stackoverflow.com/comment/88754665
comment on: http://stackoverflow.com/q/50875885
score: 0
type: QuestionComment
type: Comment
has text: pd.to_datetime doesn't work. It still shows index in dataframe.

http://stackoverflow.com/a/50895847
answers question: http://stackoverflow.com/q/50895833
upvote count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/88791641
type: Answer
score: 1
has comment: http://stackoverflow.com/comment/88791935
has body: f = np.sin(x) assigns the return value of np.sin(x) (which can't even be calculated because x is not defined) to f. Even if x was defined, f(0.3) would have failed since a float is not callable. You meant to do f = np.sin. import numpy as np f = np.sin print(f(0.3)) # 0.295520206661

http://stackoverflow.com/q/50935098
type: Question
possible better answer: http://stackoverflow.com/a/50935531
has answer: http://stackoverflow.com/a/50935531
tagged with: dataframe
has comment: http://stackoverflow.com/comment/88869443
answer count: 2
has comment: http://stackoverflow.com/comment/88870017
tagged with: pandas-groupby
has answer: http://stackoverflow.com/a/50935517
tagged with: pandas
downvote count: 0
has body: I'm trying to make a calculation on multiple rows for every row in a dataframe. My current solution takes almost 2 hours for 200k rows. so it's pretty inefficient, I'm hoping groupby or some other pandas methods can help me here. my data looks like this for example (you can ignore the dates for now): id group start_date end_date three_yrs_ago_date days_missing 01 23 2005-01-01 2006-01-01 2002-01-01 1 02 23 2006-01-06 2007-01-06 2003-01-06 6 03 23 2007-01-15 2008-01-15 2004-01-15 9 07 17 2014-01-01 2015-02-01 2011-01-01 2 07 23 2015-01-01 2016-02-01 2012-01-01 4 so the goal here is to group everything by its group number and then add up all the days_missing of all the other rows in that group that occurred within the last 3 years. That is to say the other rows start_date is at or after the current row's three_yrs_ago_date, and at or before the current row's end_date. That's a mouthful, but its basically three criteria. so that if this were the whole dataset we'd get this result (dropping the date columns): id group days_missing days_missing_in_last_three_years 01 23 1 1 # no change: no prior years 02 23 6 7 03 23 9 16 07 17 2 2 # no change: only member of it's group 07 23 4 4 # no change: other group members more than 3 years ago I'll show you the code I currently have, but it's slow. I go through the dataframe row by row, creating a temporary dataframe containing all it's group members, then I whittle those group members down to only the ones within the date criteria. It's not pretty: days=[] for index, row in tqdm(df.iterrows()): # moderately slow (~2 hour): temp = df[df['group'] == row['group']] temp = temp[temp['start_date'] &gt;= row['three_yrs_ago_date']] temp = temp[temp['end_date'] &lt;= row['start_date']] add = temp['days_missing'].sum() + row['days_missing'] days.append(add) df['days_missing_in_last_three_years'] = days I tried 2 other approaches but neither was successful: # very slow (~3 hours): cov.append(df[(df['group'] == row['group']) &amp; (df['start…
favorite count: 0
accepted answer: http://stackoverflow.com/a/50935517
has title: pandas speed up multi-row calculation by using groupby
upvote count: 2
tagged with: python
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88870030

http://stackoverflow.com/q/50878885
has answer: http://stackoverflow.com/a/50893452
score: 3
downvote count: 0
favorite count: 0
has body: I am new in machine learning area. i am trying to run python program on browser by converting trained model in tensorflow js. this attention_ocr is related to OCR written in python. i have generated HDF5/H5 file and converted that in web specific format with tensorflowjs_converter[ref]. I follow all instruction given in this document but at the time of running in browser it throwing me error (refer screenshot) I am looking for solution to remove this error...! Referance : tensorflow.org How to import a TensorFlow SavedModel into TensorFlow.js Importing a Keras model into TensorFlow.js
tagged with: tensorflow.js
has comment: http://stackoverflow.com/comment/88760190
type: Question
answer count: 2
tagged with: python
has title: "Unknown layer: Lambda" in tensorflowjs on browser
upvote count: 3
has comment: http://stackoverflow.com/comment/89141132
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/62583515

http://stackoverflow.com/comment/88845133
has text: @roubabeainy try 'server.bind(("192.168.1.2", 5555))'
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50891089

http://stackoverflow.com/comment/89001435
comment on: http://stackoverflow.com/a/50954493
type: AnswerComment
score: 0
type: Comment
has text: @GustavoAmarante I've edited the answer to show the total line. See how your code compares with mine: if it's the same and you still can't see the line I think you're at the point of asking a new question.

http://stackoverflow.com/q/50861893
tagged with: python
has comment: http://stackoverflow.com/comment/88726480
answer count: 0
has comment: http://stackoverflow.com/comment/88726463
has title: Python how to print without overrides something we input when multithreading
type: Question
has comment: http://stackoverflow.com/comment/88726343
upvote count: 5
downvote count: 0
has body: I'm trying to make chat like app using python, but if the opposite party send a text while im typing something, it messed up. My codes are like this: import threading import time import sys def printf(str, *args): print(str % args, end='') def printwait(): global End while not End: time.sleep(3) print(' ') print('waiting respond') def reqinput(): global End while not End: name = input("Input your name:") End=name=='@end' End=False t1=threading.Thread(target=printwait) t2=threading.Thread(target=reqinput) t1.start() t2.start() t1.join() t2.join() print('done') when im in middle of typing and then the time sleep expires it messed it up like this: Input your name:waiting respond im trying twaiting respond o typwaiting respond e somethingwaiting respond here Input your name:waiting respond waiting respond waiting respond waiting respond waiting respond waiting respond waiting respond @waiting respond end waiting respond done while i want it to just print the 'waiting respond' on the upper line or just move whatever im trying to type to after the 'waiting respond'
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
score: 5
tagged with: code-formatting

http://stackoverflow.com/comment/88840611
comment on: http://stackoverflow.com/a/50911407
type: Comment
has text: Sorry, I had a mistake in the for loop. `String` and `int` cannot be concatenated like this. So the code is edited. If it won't work try to print one element `print(tickers[0].text)`
score: 0
type: AnswerComment

http://stackoverflow.com/q/50878949
tagged with: pandas
has answer: http://stackoverflow.com/a/50878992
tagged with: python
downvote count: 4
has title: if x['column 1] = y['column 1'] then replace that value with value in y['column 2'] in python or R
upvote count: 0
type: UnansweredQuestion
score: -4
has body: I have a large data set that is updated daily but the system where I'm getting the data from alters some of the values. I need to correct those values in the master data so it matches other reports. I identified those values and created a data frame with the correct values in another column. I would just like to replace the 50 names with the corrected name in Python. if x['column 1] == y['column 1'] then replace that value with value in y['column 2']
has answer: http://stackoverflow.com/a/50879064
tagged with: dataframe
type: Question
answer count: 2
favorite count: 0

http://stackoverflow.com/comment/89000613
type: QuestionComment
comment on: http://stackoverflow.com/q/51002844
score: 0
has text: still do nothing
type: Comment

http://stackoverflow.com/comment/88851550
comment on: http://stackoverflow.com/a/50925676
type: AnswerComment
score: 0
type: Comment
has text: where ? Not sure I understand your answer, sry

http://stackoverflow.com/a/50927664
score: 1
answers question: http://stackoverflow.com/q/50927581
upvote count: 1
has body: You can do it like so: with open(inputfile) as f: for line in f: if "[ word ]" in line: line = f.readline() # 1 reassigns line to the next line than the one used by the if comparison.
type: Answer
downvote count: 0

http://stackoverflow.com/comment/88792480
comment on: http://stackoverflow.com/a/50889287
has text: What I try to do is to run `sniff` without any open window.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/50975699
downvote count: 0
has body: Python2 performs floor division on ints, whereas python3 performs float division on ints. If you are trying to write a script file, say stack.sh, to execute your python file, say file_with_python_code.py , you may be interested in the following: Designate one file as your script file. We are calling this stack.sh. Here is the entire contents of that file: #!/bin/sh python3 file_with_python_code.py The shebang line lets us specify which shell we want to use to execute the following line. Then you just type whatever you would normally type on the command line to execute you python program. In this case: python3 file_with_python_code.py . Then run chmod 700 stack.sh to ensure you have permission to execute the script. Finally, run the script: ./stack.sh Hope that helps. Good luck! Bonus Info: if your python file accepts other files as input, you can use positional parameters inside your script file. For example, if your file_with_python_code.py file took input.txt as an argument, like this: python3 file_with_python_code.py input.txt You could change your script file to include the position parameter "$1": python3 file_with_python_code.py "$1" Then run the script as follows: ./stack.sh &lt;any input file&gt; Example: ./stack.sh input.txt
type: Answer
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/88948433
answers question: http://stackoverflow.com/q/50970475

http://stackoverflow.com/a/50877539
upvote count: 1
type: Answer
downvote count: 0
score: 1
has body: You can achieve that network architecture easily with the functional API and not use Sequential at all: InA, InB, InC = [Input(shape=(4,), dtype='int32') for _ in range(3)] netA = Dense(4, activation="relu")(InA) netA = Dense(3, activation="relu")(netA) netB = Dense(4, activation="relu")(InB) netB = Dense(3, activation="relu")(netB) netMergeAB = concatenate([netA, netB]) netMergeAB = Dense(1, activation="relu")(netMergeAB) fullConcat = concatenate([netMergeAB, InC]) out = Dense(10, activation="relu")(fullConcat) out = Dense(6, activation="relu")(out) out = Dense(4, activation="relu")(out) out = Dense(1, activation="relu")(out) model = Model([InA, InB, InC], out) You might need to adjust it slightly but the overall idea should be clear.
answers question: http://stackoverflow.com/q/50876172
has comment: http://stackoverflow.com/comment/88809414

http://stackoverflow.com/q/50882282
upvote count: 3
tagged with: deep-learning
favorite count: 0
has answer: http://stackoverflow.com/a/50883668
has answer: http://stackoverflow.com/a/57020676
linked to: http://stackoverflow.com/q/34755244
type: UnansweredQuestion
tagged with: python
has title: TensorFlow: bincount with axis option
tagged with: vectorization
answer count: 4
score: 3
downvote count: 0
tagged with: machine-learning
has answer: http://stackoverflow.com/a/50882752
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/54113574
has body: In TensorFlow, I can get the count of each element in an array with tf.bincount: x = tf.placeholder(tf.int32, [None]) freq = tf.bincount(x) tf.Session().run(freq, feed_dict = {x:[2,3,1,3,7]}) this returns Out[45]: array([0, 1, 1, 2, 0, 0, 0, 1], dtype=int32) Is there a way to do this on a 2D tensor? i.e. x = tf.placeholder(tf.int32, [None, None]) freq = tf.axis_bincount(x, axis = 1) tf.Session().run(freq, feed_dict = {x:[[2,3,1,3,7],[1,1,2,2,3]]}) that returns [[0, 1, 1, 2, 0, 0, 0, 1],[0, 2, 2, 1, 0, 0, 0, 0]]

http://stackoverflow.com/a/50879623
type: AcceptedAnswer
type: Answer
has body: s = """&gt;EU &gt;Please spread this like the plague. """ print(' '.join(s.replace('&gt;','').replace('.','').replace('\n','.').split())) Out[ ]: EU. Please spread this like the plague. Note, that this required I manually remove the blank lines. Another way to go would be to use regular expressions. import re s = re.sub(r"&gt;", '', s) s = re.sub(r" {2}", '', s) s = re.sub(r"\.", '', s) s = re.sub(r"\n\n", '.', s) s = re.sub(r" \n", '', s) s = re.sub(r"\n", '.', s) print(s) Out[ ]: EU. Please spread this like the plague.
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/50879291
answers question: http://stackoverflow.com/q/50879291
upvote count: 1

http://stackoverflow.com/comment/134909495
score: 0
type: Comment
has text: `action="append"` stores elements in a list. https://docs.python.org/3/library/argparse.html#action
comment on: http://stackoverflow.com/a/50965772
type: AnswerComment

http://stackoverflow.com/q/50978994
tagged with: python-2.7
has title: Multiple timed functions on a single thread
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/50979374
tagged with: python-multithreading
type: UnansweredQuestion
tagged with: multithreading
tagged with: python
score: 1
upvote count: 1
has body: I am reading the docs on python threading and the timer subclass and I do not quite understand how it would work if I want to run two (or more) timed class methods at different rates on the same thread. For example, I have an I/O serial device that I want to periodically read (if any data), write any input messages from outside modules, and periodically write a predefined device specific heartbeat message. This is all wrapped in a custom class. I/O messages are stored in two separate class queue objects. Do I need to create three threading.Timer objects for each function, or can I somehow use one thread that switches? import serial, threading, Queue # the exact syntax below may be incorrect class MySerialDevice: def __init__(): # Some other modules will be appending to this (through a class method) self.write_queue = Queue() self.read_queue = Queue() self.port = serial.Serial() # check for incoming data every 20ms self.thread1 = threading.Timer(0.02, self.read) # check for outgoing data every 20ms self.thread2 = threading.Timer(0.02, self.write) # Send the heaertbeat every 1 second self.thread3 = threading.Timer(1, self.heartbeat) # what do I do here??? # can I make all three tasks on a single thread, that just continuously loops # and "if incoming data, read, if outgoing data, write, heartbeat??? def read(self): # checks for actual data, appending to queue are ommited self.port.read() def write(self): # checks for data in queue ommitted self.port.write(self.write_queue[0]) def heartbeat(self): self.port.write("Device Heartbeat message)"
has comment: http://stackoverflow.com/comment/88953836
type: Question

boxplot
tags question: http://stackoverflow.com/q/50971091
tags question: http://stackoverflow.com/q/50963960
tag name: boxplot
tags question: http://stackoverflow.com/q/50890267
tags question: http://stackoverflow.com/q/50996368
type: Tag

http://stackoverflow.com/comment/126048787
type: AnswerComment
type: Comment
has text: For virtual environments that encapsulate more than just Python dependencies (like Python itself), check out nixpkgs/nix-shell (also works on macOS). Docker on macOS for development/hot reloading of code using volumes is slow because on macOS, Docker runs inside a VM - and files/file system events need to be translated from the macOS file system to ext4 or similar.
comment on: http://stackoverflow.com/a/50975143
score: 0

http://stackoverflow.com/a/50977172
has body: Here are some more ways to do the same thing. In terms of readability, numpy.ndarray.flatten is more straightforward. Input arrays: In [207]: arr1 Out[207]: array([[0.34, 0.26, 0.76], [0.79, 0.82, 0.37], [0.93, 0.87, 0.94]]) In [208]: arr2 Out[208]: array([[0.21, 0.73, 0.69], [0.35, 0.24, 0.53], [0.01, 0.42, 0.5 ]]) As a first step, flatten them: In [209]: arr1_flattened = arr1.flatten()[:, np.newaxis] In [210]: arr1_flattened Out[210]: array([[0.34], [0.26], [0.76], [0.79], [0.82], [0.37], [0.93], [0.87], [0.94]]) In [211]: arr2_flattened = arr2.flatten()[:, np.newaxis] In [212]: arr2_flattened Out[212]: array([[0.21], [0.73], [0.69], [0.35], [0.24], [0.53], [0.01], [0.42], [0.5 ]]) Then concatenate or stack them: # just horizontally stack (np.hstack) the flattened arrays In [213]: np.hstack([arr1_flattened, arr2_flattened]) Out[213]: array([[0.34, 0.21], [0.26, 0.73], [0.76, 0.69], [0.79, 0.35], [0.82, 0.24], [0.37, 0.53], [0.93, 0.01], [0.87, 0.42], [0.94, 0.5 ]]) In one-line: In [205]: np.hstack([arr1.flatten()[:, None], arr2.flatten()[:, None]]) Out[205]: array([[0.34, 0.21], [0.26, 0.73], [0.76, 0.69], [0.79, 0.35], [0.82, 0.24], [0.37, 0.53], [0.93, 0.01], [0.87, 0.42], [0.94, 0.5 ]]) # same thing can be done using np.concatenate In [206]: np.concatenate([arr1.flatten()[:, None], arr2.flatten()[:, None]], axis=1) Out[206]: array([[0.34, 0.21], [0.26, 0.73], [0.76, 0.69], [0.79, 0.35], [0.82, 0.24], [0.37, 0.53], [0.93, 0.01], [0.87, 0.42], [0.94, 0.5 ]]) Note that all the stacking methods (stack, hstack, vstack, dstack, column_stack), call numpy.concatenate() under the hood.
score: 0
answers question: http://stackoverflow.com/q/50974645
type: Answer

http://stackoverflow.com/comment/88757652
type: QuestionComment
comment on: http://stackoverflow.com/q/50877714
score: 1
has text: you're trying to say that a string is a function when it clearly isn't
type: Comment

http://stackoverflow.com/comment/88756402
type: Comment
type: AnswerComment
has text: I've never really used Vectors. Do I have to make Vector 2 a variable?
comment on: http://stackoverflow.com/a/50861193
score: 0

http://stackoverflow.com/a/50904796
has body: Uhm, it seems I have been able to solve the error by adding this code to my class: def mouse_event(self, size, event, button, col, row, focus): pass Now, when I click on the surface of the terminal, the cursor doesn't disappear anymore. That's exactly what I was looking for.
score: 0
answers question: http://stackoverflow.com/q/50890421
type: Answer

http://stackoverflow.com/q/50895128
accepted answer: http://stackoverflow.com/a/50895129
answer count: 1
has body: Solution below If you are just interested in solving this problem, you can skip to my answer below. Original question I'm using tensorflow for reinforcement learning. A swarm of agents uses the model in parallel and one central entity trains it on the collected data. I had found here: Is it thread-safe when using tf.Session in inference service? that tensorflow sessions are threadsafe. So I simply let the prediction and updating run in parallel. But now I would like to change the setup. Instead of updating and training on one single model, I now need to keep two models. One is used for prediction and the second one is trained. After some training steps the weights from the second one are copied over to the first. Below is a minimal example in keras. For multiprocessing, it is recommended to finalize the graph, but then I can't copy weights: # the usual imports import numpy as np import tensorflow as tf from keras.models import * from keras.layers import * # set up the first model i = Input(shape=(10,)) b = Dense(1)(i) prediction_model = Model(inputs=i, outputs=b) # set up the second model i2 = Input(shape=(10,)) b2 = Dense(1)(i2) training_model = Model(inputs=i2, outputs=b2) # look at this code, to check if the weights are the same # here the output is different prediction_model.predict(np.ones((1, 10))) training_model.predict(np.ones((1, 10))) # now to use them in multiprocessing, the following is necessary prediction_model._make_predict_function() training_model._make_predict_function() sess = tf.Session() sess.run(tf.global_variables_initializer()) default_graph = tf.get_default_graph() # the following line is the critical part # if this is uncommented, the two options below both fail # default_graph.finalize() # option 1, use keras methods to update the weights prediction_model.set_weights(training_model.get_weights()) # option 2, use tensorflow to update the weights update_ops = [tf.assign(to_var, from_var) for to_var, from_var in zip(prediction_model.trainable…
tagged with: keras
has title: tensorflow: assigning weights after finalizing graph
has answer: http://stackoverflow.com/a/50895129
tagged with: python
tagged with: keras-2
type: AnsweredQuestion
tagged with: tensorflow
type: Question
linked to: http://stackoverflow.com/q/38694111
score: 0

http://stackoverflow.com/q/50952938
type: Question
has body: I have a simple form that asks the user to input an email. My goal is to send that email back into Python so that I can append it to a text file. HTML: &lt;form method="post" target="frame"&gt; &lt;input name="email" value="{{request.form.text}}" id="email"&gt; &lt;input type="submit" value="Sign Up"&gt; &lt;/form&gt; Flask: @app.route('/', methods=['GET', 'POST']) def my_form(): if request.method == "POST": inputed_email = request.form.get('email') return inputed_email return render_template("my-form.html") Whenever I enter an email into the form, I get this error: What is preventing the form data from being sent back into Python? Any help is appreciated. Thank you!
linked to: http://stackoverflow.com/q/17309889
tagged with: forms
duplicate of: http://stackoverflow.com/q/32722143
tagged with: post
downvote count: 0
tagged with: web
tagged with: flask
favorite count: 0
has title: Flask Post Error 500 (Internal Server Error)
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/17309889
tagged with: python
score: 2
answer count: 0
upvote count: 2
duplicate of: http://stackoverflow.com/q/21406057

http://stackoverflow.com/comment/88730507
has text: You will get non-empty checks for free for almost everything except direct descendants from `object` and such. In case if length is enough - you can test `\__len__` of your types. Read `Data Model`.
score: 1
comment on: http://stackoverflow.com/a/50863867
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/106930910
comment on: http://stackoverflow.com/a/52724994
type: AnswerComment
has text: beautiful works like a charm !
type: Comment
score: 0

http://stackoverflow.com/q/50870912
has answer: http://stackoverflow.com/a/50871182
has comment: http://stackoverflow.com/comment/88743726
has body: I'm confused with a statement, found in post here: with open('cover.tex','w') as f: f.write(content%args.__dict__) What exactly is content%args.__dict__? Is this Python 2.7? Quick googling/asking did not help. Update: one suggestion is that % is modulo division, by how is it applicable to a string?
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
upvote count: 1
downvote count: 1
type: Question
has title: What is content%args.__dict__?
accepted answer: http://stackoverflow.com/a/50871182
linked to: http://stackoverflow.com/q/50856325
linked to: http://stackoverflow.com/q/4432208
tagged with: python-2.7
score: 0
answer count: 1
favorite count: 0

http://stackoverflow.com/a/51012235
type: AcceptedAnswer
has body: The problem is that your copying rules have this form: $(ENTDIR)/mifunction.py: $(ENTDIR) cp /home/user/Documents/python/$(ENTDIR)/mifunction.py ./$(ENTDIR) Notice that the destination directory is a prerequisite. Make will consider the target out of date if the directory has a later timestamp than the target, and the OS updates the timestamp of the directory when a file is added to it (or removed). Since this makefile copies other files to that directory, this target will appear to be out of date the next time you run Make. There is more than one way to solve this. The simplest is to change the prerequisite to an order-only prerequisite by adding a pipe ('|'): $(ENTDIR)/mifunction.py: | $(ENTDIR) cp /home/user/Documents/python/$(ENTDIR)/mifunction.py ./$(ENTDIR) Once you confirm that this works, you can work on other improvements. You might consider using the original files as prerequisites: $(ENTDIR)/mifunction.py: /home/user/Documents/python/$(ENTDIR)/mifunction.py | $(ENTDIR) cp /home/user/Documents/python/$(ENTDIR)/mifunction.py ./$(ENTDIR) This looks ungainly until you introduce automatic variables: $(ENTDIR)/mifunction.py: /home/user/Documents/python/$(ENTDIR)/mifunction.py | $(ENTDIR) cp $&lt; $@ Whether or not you do that, you can introduce another variable: PYTHON_DIR := /home/user/Documents/python which will remove a lot of redundancy. Further improvements are possible, but that's probably enough for now.
type: Answer
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51010521
answers question: http://stackoverflow.com/q/51010521
upvote count: 2

http://stackoverflow.com/a/50906599
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50906210
has comment: http://stackoverflow.com/comment/121733675
downvote count: 0
score: 28
accepted answer of: http://stackoverflow.com/q/50906210
upvote count: 28
type: Answer
has comment: http://stackoverflow.com/comment/88813214
has body: Note that you are printing a sparse matrix so the output looks different compared to printing a standard dense matrix. See below the main components: The tuple represents: (document_id, token_id) The value following the tuple represents the tf-idf score of a given token in a given document The tuples that are not there have a tf-idf score of 0 If you want to find what token the token_id corresponds to, check the get_feature_names method.

http://stackoverflow.com/comment/88835488
has text: I think something like scheduled tasks. Maybe I have formulated not so clear. Code should work not between (before/after) requests, but independently from requests, so it's doing own job during server lifetime and http requests asks it for something while executed.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50917614
score: 0

http://stackoverflow.com/comment/90038003
comment on: http://stackoverflow.com/a/51000045
has text: @mohsendppp if csv conversion of all is what you want, then in this case I would read it in the chunks you can handle. Name the files differently by adding a numerical extension. Only write the header when creating the first file, so add `header=False` after the first. When you have all csv files, simply concat them into 1 file
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89239596
score: 0
type: AnswerComment
type: Comment
has text: @Napu, Thanks for your input. The problem is that the Tensorflow bindings are not defined in Raspbian. Without those bindings, it is not possible "import tensorflow as tf".
comment on: http://stackoverflow.com/a/51093144

http://stackoverflow.com/a/50879865
type: Answer
has body: (Spyder maintainer here) This line in your error /usr/lib/python2.7/dist-packages/spyderlib/start_app.py means that you're using a very, very old Spyder version (2.3, released three years ago). Our recommendation to get our latest version (3.2.8) is to download and install Anaconda, instead of using the packages from your Linux distribution (which can be terrible outdated, like in this case).
has comment: http://stackoverflow.com/comment/88773115
has comment: http://stackoverflow.com/comment/88859493
has comment: http://stackoverflow.com/comment/88780338
score: 0
has comment: http://stackoverflow.com/comment/88771372
has comment: http://stackoverflow.com/comment/88766205
has comment: http://stackoverflow.com/comment/88763623
answers question: http://stackoverflow.com/q/50879241
has comment: http://stackoverflow.com/comment/88857207

http://stackoverflow.com/q/50994051
score: 1
has comment: http://stackoverflow.com/comment/88982955
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/88982804
has body: All a specific letter, let's say 'A', needs to be replaced in all parentheses. For example, A. (AbbAAbb) .A. (bbAbbAbA) .A. (bbbbAbbbb) I want to replace all 'A' in the parenthese with '' to end up like this: A. (bbbb) .A. (bbbbb) .A. (bbbbbbbb) Any possible to do this in only regular expression?
has comment: http://stackoverflow.com/comment/88983733
has comment: http://stackoverflow.com/comment/88982900
has comment: http://stackoverflow.com/comment/88983007
has comment: http://stackoverflow.com/comment/88982945
has answer: http://stackoverflow.com/a/50994342
tagged with: regex
favorite count: 0
possible better answer: http://stackoverflow.com/a/50994231
has comment: http://stackoverflow.com/comment/88982724
has answer: http://stackoverflow.com/a/50994231
upvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/88982699
downvote count: 1
has title: Replace paticular element inside all parentheses
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50994342

http://stackoverflow.com/comment/88911828
score: 0
has text: @BowlingHawk95 That sounds like the inverse of the two prior posts...?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50956798

http://stackoverflow.com/q/50889192
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/50941336
score: 0
answer count: 1
has body: I compiled tensorflow from source with MKL in order to accelerate my DNN learning progress. And I have a ResNet model which is copy from tensorflow/models. The dataset is CIFAR-10. When I run the model with channels last format, everything goes ok. But in order to use MKL which is said only accelerate only for channels first format, I add some code to transpose the data into NCHW format, and run it. Then I get: Caused by op 'stage/residual_v1/conv2d/Conv2D', defined at: File "main.py", line 182, in &lt;module&gt; main(args) File "main.py", line 83, in main tf.estimator.train_and_evaluate(estimator, train_spec, eval_spec) File "/home/holmescn/.pyenv/versions/anaconda35.2.0/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/estimator/training.py", line 447, in train_and_evaluate return executor.run() File "/home/holmescn/.pyenv/versions/anaconda3-5.2.0/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/estimator/training.py", line 531, in run return self.run_local() File "/home/holmescn/.pyenv/versions/anaconda3-5.2.0/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/estimator/training.py", line 669, in run_local hooks=train_hooks) File "/home/holmescn/.pyenv/versions/anaconda3-5.2.0/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/estimator/estimator.py", line 366, in train loss = self._train_model(input_fn, hooks, saving_listeners) File "/home/holmescn/.pyenv/versions/anaconda3-5.2.0/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/estimator/estimator.py", line 1119, in _train_model return self._train_model_default(input_fn, hooks, saving_listeners) File "/home/holmescn/.pyenv/versions/anaconda3-5.2.0/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/estimator/estimator.py", line 1132, in _train_model_default features, labels, model_fn_lib.ModeKeys.TRAIN, self.config) File "/home/holmescn/.pyenv/versions/anaconda3-5.2.0/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/estimator/esti…
type: UnansweredQuestion
tagged with: python
has title: input and filter must have the same depth: 32 vs 16 when using MKL and channels first format

http://stackoverflow.com/q/51001928
linked to: http://stackoverflow.com/q/9835762
accepted answer: http://stackoverflow.com/a/51002758
tagged with: python
favorite count: 0
score: -1
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/88998281
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88997838
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88997682
has comment: http://stackoverflow.com/comment/88998154
upvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/51002758
has title: 2 questions on Python : created table & fail to find duplicates in rows
has body: I have this data set which is in this format in this way in csv file: 1st question : I am trying to find duplicates rows in the table just created in python below? I did try to use the set function to run the rows and the output I got is no duplicates even though there is a duplicate row in the data set. 2nd question: is it possible to reference this table as i realized that it becomes a table when I print?So that I can use it on the next step for calculation purpose. COL_1_WIDTH = 10 COL_2_WIDTH = 35 for row in data: IC1 = len(str(row[0])) IC2 = len(str(row[1])) print( str(row[0])+ str( (COL_1_WIDTH-IC1) *' ') +\ str(row[1]) + str( (COL_2_WIDTH-IC2) *' ') +\ str(row[2])) for row in data: if len(set(row)) !=len(row): print ('duplicates: ', row) else: print ('no duplicates:', row) P.s. Permit to use built in function &amp; numpy only. Grateful for any ideas. Thank you!

class-variables
tag name: class-variables
tags question: http://stackoverflow.com/q/50950574
type: Tag
tags question: http://stackoverflow.com/q/50981037

buildpack
tag name: buildpack
type: Tag
tags question: http://stackoverflow.com/q/50932087

http://stackoverflow.com/q/50896847
has comment: http://stackoverflow.com/comment/88793477
downvote count: 1
linked to: http://stackoverflow.com/q/2400262
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88794935
type: Question
possible better answer: http://stackoverflow.com/a/50897623
has answer: http://stackoverflow.com/a/50897623
has comment: http://stackoverflow.com/comment/88793460
has answer: http://stackoverflow.com/a/50898345
favorite count: 0
has comment: http://stackoverflow.com/comment/88793872
has comment: http://stackoverflow.com/comment/88794893
has answer: http://stackoverflow.com/a/50897603
answer count: 3
has body: I want to come out of the loop immediately after pressing the stop button. But with this code, i could able to come out only after executing current iteration and next iteration. It is very important for my application since iam going to use this for automating instruments, where operations have to be stopped immediately after pressing stop button. # -*- coding: utf-8 -*- """ Created on Sun Jun 17 17:01:12 2018 @author: Lachu """ import time from tkinter import * from tkinter import ttk root=Tk() def start(): global stop_button_state for i in range(1,20): if (stop_button_state==True): break else: print('Iteration started') print('Iteration number: ', i) root.update() time.sleep(10) print('Iteration completed \n') def stop_fun(): global stop_button_state stop_button_state=True start=ttk.Button(root, text="Start", command=start).grid(row=0,column=0,padx=10,pady=10) p=ttk.Button(root, text="Stop", command=stop_fun).grid(row=1,column=0) stop_button_state=False root.mainloop()
accepted answer: http://stackoverflow.com/a/50898345
tagged with: python
tagged with: tkinter
upvote count: 3
has title: How to kill time.sleep() in python 3 while compiler is sleeping

http://stackoverflow.com/comment/88969234
comment on: http://stackoverflow.com/a/50979488
type: Comment
has text: I have not gotten a chance to test it yet, but it should work based on the api docs.
score: 0
type: AnswerComment

http://stackoverflow.com/a/50913653
type: Answer
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50913322
has body: Using collections.defaultdict followed by a dictionary comprehension: d = {((0,0), 'A'): 0.0, ((0,0), 'B'): 0.7, ((2,4), 'C'): 0.2} from collections import defaultdict res = defaultdict(list) for (k1, k2), v in d.items(): res[k1].append(v) max_vals = {k: max(v) for k, v in res.items()} print(max_vals) {(0, 0): 0.7, (2, 4): 0.2}

http://stackoverflow.com/comment/88893701
has text: Looks like a bug.
type: Comment
comment on: http://stackoverflow.com/q/50948032
score: 0
type: QuestionComment

http://stackoverflow.com/a/50957160
type: Answer
has comment: http://stackoverflow.com/comment/88913701
answers question: http://stackoverflow.com/q/50957098
has body: Unfortunately there is no method to do that but maybe view last restart shell option may help you.
has comment: http://stackoverflow.com/comment/88938067
score: 0
has comment: http://stackoverflow.com/comment/88912018

http://stackoverflow.com/q/50995499
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88985623
tagged with: line
score: 2
tagged with: pixel
has comment: http://stackoverflow.com/comment/88985790
tagged with: coordinates
type: Question
tagged with: point
answer count: 1
downvote count: 0
has title: Generating pixel values of line connecting 2 points
has body: I am having some troubles trying to connect separate points in my picture (see below). Right now, the code I have is as follows: first_time = resulting_coords[0:40] for i in range(len(first_time)): if(i &lt; (len(first_time))-1): cv2.line(copy_test_image[0], (resulting_coords[i,0],resulting_coords[i,1]), (resulting_coords[i+1,0],resulting_coords[i+1,1]), (0,0,225), 2) elif(i&gt;=(len(first_time))-1): # print(i) cv2.line(copy_test_image[0], (resulting_coords[i,0],resulting_coords[i,1]), (resulting_coords[0,0],resulting_coords[0,1]), (0,0,225), 2) Which actually gives the result I want: Results in But I cannot extract the coordinates of the pixels of these lines. I tried using a rather complicated function which uses the P1(x1,y1) and P2(x2,y2) points and connects them with a line with pixel coords: def pixels_in_shape(x1, y1, x2, y2, img): P1=[x1,y1] P2=[x2,y2] #define local variables for readability imageH = img.shape[0] imageW = img.shape[1] P1X = int(P1[0]) P1Y = int(P1[1]) P2X = int(P2[0]) P2Y = int(P2[1]) #difference and absolute difference between points #used to calculate slope and relative location between points dX = P2X - P1X dY = P2Y - P1Y dXa = np.abs(dX) dYa = np.abs(dY) #predefine numpy array for output based on distance between points itbuffer = np.zeros(shape=(int(np.maximum(dYa,dXa)),3),dtype=np.float32) itbuffer.fill(np.nan) #Obtain coordinates along the line using a form of Bresenham's algorithm negY = P1Y &gt; P2Y negX = P1X &gt; P2X if P1X == P2X: #vertical line segment itbuffer[:,0] = P1X if negY: itbuffer[:,1] = np.arange(P1Y,P1Y - dYa,-1) else: itbuffer[:,1] = np.arange(P1Y,P1Y + dYa) elif P1Y == P2Y: #horizontal line segment itbuffer[:,1] = P1Y if negX: itbuffer[:,0] = np.arange(P1X,P1X-dXa,-1) else: itbuffer[:,0] = np.arange(P1X,P1X+dXa) else: #diagonal line segment steepSlope = dYa &gt; dXa if steepSlope: slope=dX/dY if negY: itbuffer[:,1] = np.arange(P1Y,P1Y-dYa,-1) else: itbuffer[:,1] = np.arange(P1Y,P1Y+dYa) itbuffer[:,0] = (slope*(itbuf…
linked to: http://stackoverflow.com/q/2734714
has answer: http://stackoverflow.com/a/74762835
favorite count: 0
has comment: http://stackoverflow.com/comment/88985589
upvote count: 2

http://stackoverflow.com/comment/88930003
has text: So you should replace it by `response.css(' ul.dotted-list li::text').extract()`. Yes if you want to get more infomartion you can just put it in `youritem` e.g `youritem['title']=response.xpath('//h1[@itemprop="name"]/text()').extract_first()`
comment on: http://stackoverflow.com/a/50965873
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/50992502
has comment: http://stackoverflow.com/comment/88982776
has comment: http://stackoverflow.com/comment/88982877
score: 0
has body: Try this XPATH : //div[@id='autocplt_wrap']//descendant::span[@class='word']//a[text()='汤'] CSS_SELECTOR for grabbing those two element would be : ol.lst_defin&gt;li span.cn UPDATE : from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC driver = webdriver.Chrome(executable_path = r'D:/Automation/chromedriver.exe') driver.get("http://ce.linedict.com/#/cnen/home") input = driver.find_element_by_css_selector("input[type='text']") input.send_keys("汤") input.send_keys(Keys.RETURN) asian_text= WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.XPATH,"//div[@id='autocplt_wrap']//descendant::span[@class='word']//a[text()='汤']"))) asian_text.click(); WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.CSS_SELECTOR, 'ol.lst_defin&gt;li span.cn'))) definition_list = driver.find_elements_by_css_selector('ol.lst_defin&gt;li span.cn') print(len(definition_list)) for element in definition_list : print(element.text) This will print : [??] hot water soup
has comment: http://stackoverflow.com/comment/88980006
has comment: http://stackoverflow.com/comment/88979775
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88980267
has comment: http://stackoverflow.com/comment/88980312
has comment: http://stackoverflow.com/comment/88980389
has comment: http://stackoverflow.com/comment/88980468
has comment: http://stackoverflow.com/comment/88982913
type: Answer
has comment: http://stackoverflow.com/comment/88980379
has comment: http://stackoverflow.com/comment/88979858
has comment: http://stackoverflow.com/comment/88982932
has comment: http://stackoverflow.com/comment/88980168
has comment: http://stackoverflow.com/comment/88980438
has comment: http://stackoverflow.com/comment/88980066
accepted answer of: http://stackoverflow.com/q/50992042
has comment: http://stackoverflow.com/comment/88979808
has comment: http://stackoverflow.com/comment/88981178
answers question: http://stackoverflow.com/q/50992042
has comment: http://stackoverflow.com/comment/88979957
has comment: http://stackoverflow.com/comment/88982903

http://stackoverflow.com/a/55025083
has body: A json recursive tree can have several roots and the leafs should not have to mandatory specify void childrens. For example, here is a tree with two roots 'a' and 'b', and nodes which only have a 'level' data which is the node depth ('children' is optional): json_struct = [ { 'level': 'a0', 'children': [{'level': 'a0.1', 'children': [{'level': 'a0.1.1', 'children': []}]}, {'level': 'a0.2', 'children': [ {'level': 'a0.2.1', 'children': [ {'level': 'a0.2.1.1'}, {'level': 'a0.2.1.2'}, {'level': 'a0.2.1.3'}, {'level': 'a0.2.1.4', 'children': [{'level': 'a0.2.1.4.1'}, {'level': 'a0.2.1.4.2'}]} ] } ] }, {'level': 'a0.3', 'children': []}, {'level': 'a0.4', 'children': [{'level': 'a0.4.1'}, {'level': 'a0.4.2', 'children': []}]} ] }, { 'level': 'b0', 'children': [{'level': 'b0.1', 'children': [{'level': 'b0.1.1'}]}, {'level': 'b0.2', 'children': [{'level': 'b0.2.1', 'children': [ {'level': 'b0.2.1.1'}, {'level': 'b0.2.1.2'}, {'level': 'b0.2.1.3', 'children': [{'level': 'b0.2.1.3.1'}, {'level': 'b0.2.1.3.2'}]}, {'level': 'b0.2.1.4'} ] }]}, {'level': 'b0.3'} ] } ] The code must return the leaves and complete branch path until each leave: def flatten_json_tree(nodes, lower_nodes_key='children', path=[]): if not nodes: # void node yield path # so it is a leaf for node in nodes: # go on into each branch of the tree level = node['level'] # get node datas try: lower_nodes = node[lower_nodes_key] # search for lower nodes except KeyError: lower_nodes = [] # no lower nodes yield from flatten_json_tree(lower_nodes, lower_nodes_key, path + [level]) # continue to explore the branch until leaf if __name__ == "__main__": for path in list(flatten_json_tree(json_struct)): leaf = path[-1:][0] complete_path = '' for node in path: complete_path += node + (' -&gt; ' if node is not leaf else '') print("LEAF: {:20s} PATH: {}".format(leaf, complete_path)) It displays: LEAF: a0.1.1 PATH: a0 -> a0.1 -> a0.1.1 LEAF: a0.2.1.1 PATH: a0 -> a0.2 -> a0.2.1 -> a0.2.1.1 LEAF: a0.2.1.2 PATH: a0 -> a0.2 -> a0.…
type: Answer
answers question: http://stackoverflow.com/q/50951803
score: 0

http://stackoverflow.com/comment/88713969
comment on: http://stackoverflow.com/q/50855654
has text: what is the issue? expected output/output you're getting? of course a [mcve] would be the best (not easy with excel as input, though)
score: 1
type: QuestionComment
type: Comment

http://stackoverflow.com/q/50866141
has comment: http://stackoverflow.com/comment/88734874
type: AnsweredQuestion
has title: the convention how connecting lines connect the dots
upvote count: 1
downvote count: 1
tagged with: plot
type: Question
accepted answer: http://stackoverflow.com/a/50866547
has body: I have two matrix, x and y. x has size of 10 rows and 50 columns, and so is y. My data is row-to-row paired. It means that the x[0][:] &lt;-&gt; y[0][:] x[1][:] &lt;-&gt; y[1][:] x[2][:] &lt;-&gt; y[2][:] ...... x[49][:] &lt;-&gt; y[0][:] When I use following command to do the plot, the plot(x[:][:],y[:][:],'b-o') or plot(x,y,'b-o') to do the plot, the '-' connects the dots in horizontal direction like following: However, when I do only plot one row of signal: plot(x[0][:],y[0][:],'b-o') it looks correct: I would like for the '-' to connect the dots in a horizontal fashion. Something like this: in stead of doing a for loop, how do I do it in matrix format? Thanks.
has comment: http://stackoverflow.com/comment/88734771
has comment: http://stackoverflow.com/comment/88734761
score: 0
tagged with: vector
tagged with: matrix
has comment: http://stackoverflow.com/comment/88734976
tagged with: arrays
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50866547
has comment: http://stackoverflow.com/comment/88734749
tagged with: python
has comment: http://stackoverflow.com/comment/88734849

http://stackoverflow.com/comment/88948217
comment on: http://stackoverflow.com/q/50976041
score: 0
has text: try to remove them and see what happens
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50930860
downvote count: 0
has body: So, you really need to do 2 things here: df.to_dict() Convert this to nested dictionary. df.to_dict(orient='index') gives you a dictionary with the index as keys; it looks like this: &gt;&gt;&gt; df.to_dict(orient='index') {'entry1': {('A', 0, 0): 274.0, ('A', 0, 1): 19.0, ('A', 1, 0): 67.0, ('A', 1, 1): 12.0, ('B', 0, 0): 83.0, ('B', 0, 1): 45.0}, 'entry2': {('A', 0, 0): 254.0, ('A', 0, 1): 11.0, ('A', 1, 0): 58.0, ('A', 1, 1): 11.0, ('B', 0, 0): 76.0, ('B', 0, 1): 56.0}} Now you need to nest this. Here's a trick from Martijn Pieters to do that: def nest(d: dict) -&gt; dict: result = {} for key, value in d.items(): target = result for k in key[:-1]: # traverse all keys but the last target = target.setdefault(k, {}) target[key[-1]] = value return result Putting this all together: def df_to_nested_dict(df: pd.DataFrame) -&gt; dict: d = df.to_dict(orient='index') return {k: nest(v) for k, v in d.items()} Output: &gt;&gt;&gt; df_to_nested_dict(df) {'entry1': {'A': {0: {0: 274.0, 1: 19.0}, 1: {0: 67.0, 1: 12.0}}, 'B': {0: {0: 83.0, 1: 45.0}}}, 'entry2': {'A': {0: {0: 254.0, 1: 11.0}, 1: {0: 58.0, 1: 11.0}}, 'B': {0: {0: 76.0, 1: 56.0}}}}
score: 17
type: AcceptedAnswer
upvote count: 17
has comment: http://stackoverflow.com/comment/88892180
accepted answer of: http://stackoverflow.com/q/50929768
type: Answer
answers question: http://stackoverflow.com/q/50929768
has comment: http://stackoverflow.com/comment/88866046

http://stackoverflow.com/a/52231794
has comment: http://stackoverflow.com/comment/126184033
upvote count: 157
downvote count: 2
answers question: http://stackoverflow.com/q/50951955
has comment: http://stackoverflow.com/comment/121487565
has comment: http://stackoverflow.com/comment/139459686
has comment: http://stackoverflow.com/comment/133973578
score: 155
has body: First you should install binary: On Linux sudo apt-get update sudo apt-get install libleptonica-dev tesseract-ocr tesseract-ocr-dev libtesseract-dev python3-pil tesseract-ocr-eng tesseract-ocr-script-latn On Mac brew install tesseract On Windows download binary from https://github.com/UB-Mannheim/tesseract/wiki. then add pytesseract.pytesseract.tesseract_cmd = 'C:\Program Files (x86)\Tesseract-OCR\tesseract.exe' to your script. Then you should install python package using pip: pip install tesseract pip install tesseract-ocr references: https://pypi.org/project/pytesseract/ (INSTALLATION section) and https://tesseract-ocr.github.io/tessdoc/Installation.html
has comment: http://stackoverflow.com/comment/129127585
type: Answer
has comment: http://stackoverflow.com/comment/125981640

http://stackoverflow.com/a/50964700
downvote count: 0
answers question: http://stackoverflow.com/q/50945561
score: 1
type: Answer
upvote count: 1
has body: File was corrupted and re-downloading resolved

http://stackoverflow.com/q/50968127
answer count: 1
tagged with: web
has body: I am using python scrapy module scraping a web page and got the following response: if (typeof addMoreNewsResults == \'function\') { \r\n addMoreNewsResults( {\r\n\t\tblob: \'3DP.AX\',\r\n sortBy: \'date\',\r\n dateRange: \'all\',\r\n totalResultNumber: 2,\r\n totalResultNumberStr: "2",\r\n news: [ \r\n ]} ); \r\n } There are lots of escaped sequences there. I want to remove all of them like \' \r. I am wondering there should be some easy to use package to remove those sequences but was unable to find one. Any recommendation? Update: Instead of regex or manually replace, I want some recommendations of more powerful package to do this. I think this is a pretty common task and should be some packages have this function:P
tagged with: beautifulsoup
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50968691
tagged with: python
has comment: http://stackoverflow.com/comment/88934224
tagged with: scrapy
type: Question
has title: Easy way to remove escaped sequences from web / javascript content
score: 0

http://stackoverflow.com/comment/88946451
comment on: http://stackoverflow.com/q/50886719
score: 0
has text: @CristiFati no, just trying to automate a web based game
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88838991
comment on: http://stackoverflow.com/q/50919509
type: Comment
type: QuestionComment
score: 1
has text: This isn't really a regex problem: `if line.startswith('hum') and line.endswith('001') and '-' not in line: print(line)`

http://stackoverflow.com/q/50911147
tagged with: pyside
type: Question
has title: Auto resize QTableWidget pyside
upvote count: 1
favorite count: 0
has body: I have a simple code that Creates a QTableWidget. Problem is when I resize the window, columns of QTableWidget are not automatically adjusted to fit entire screen Please find the snippet below: from PySide.QtCore import * from PySide.QtGui import * import sys app = QApplication(sys.argv) table = QTableWidget(1,3) table.show() sys.exit(app.exec_())
answer count: 1
has answer: http://stackoverflow.com/a/50915271
accepted answer: http://stackoverflow.com/a/50915271
tagged with: python
tagged with: qtablewidget
type: AnsweredQuestion
downvote count: 0
score: 1

http://stackoverflow.com/q/50948777
has comment: http://stackoverflow.com/comment/88966404
answer count: 1
tagged with: flask
has body: I am working on a service wherein we have to store the user data in DB and send an email to the user as a notification and return the success response and it is taking some time to complete this process. As Python script execute synchronously I want to run this process asynchronously, for example, user details are stored and return the success response and then mail process has to be done asynchronously (later after returning the success response) such that the overall response should not depend on this mail execution def userregistration(details): #store user details result = storeuserdb(details) print("storeuserdb result", result) result["status"] == True: sendmailtouser() #have to be asynchronously return result def storeuserdb(details) #store code goes here def sendmailtouser() #email code goes here Is there any chance to run again after returning the response to service? Like this def userregistration(details): #store user details result = storeuserdb(details) print("storeuserdb result", result) return result result["status"] == True: sendmailtouser() #have to be asynchronously
score: 0
has answer: http://stackoverflow.com/a/50949978
tagged with: python
tagged with: python-3.x
type: UnansweredQuestion
has title: Asynchronous Service Calls Python
tagged with: mysql
has comment: http://stackoverflow.com/comment/88896455
type: Question
tagged with: smtplib

http://stackoverflow.com/comment/88939967
type: QuestionComment
has text: @TheImpaler no i am not using any salt. atmI am just trying to generate a matching hash. As soon as this works I will include the salt. Also DBMS_CRYPTO.RANDOMBYTES() returns RAW so this schould be bytes and in bytes.fromhex(h) i get a bytes object in python
comment on: http://stackoverflow.com/q/50970937
score: 0
type: Comment

http://stackoverflow.com/a/50977205
answers question: http://stackoverflow.com/q/50977130
has body: They iterate over the iterator identically, but you're checking in at different points. Because dicts are mutable, and you always yield the same dict, you should expect everything you yield to be identical. In your first example, you are looking at the dict as it is changing. Instead consider g = generator({'a': None}) a = next(g) b = next(g) c = next(g) print(a, b, c) # {'a': 2} {'a': 2} {'a': 2}
upvote count: 3
type: Answer
score: 3
downvote count: 0

http://stackoverflow.com/q/50960903
favorite count: 0
tagged with: python-3.x
has body: My folder contains .jpg files in folder. I need to fetch only the characters from the file names. I removed all the non alphabets but it resulted in a single string without spaces Input: Boston_terrier_02303.jpg Desired Output: Boston terrier
upvote count: 2
accepted answer: http://stackoverflow.com/a/50961037
tagged with: python
type: AnsweredQuestion
type: Question
downvote count: 4
score: -2
has title: A folder contains files of dog breeds like `Boston_terrier_02303.jpg`. I want to remove the numeric parts and also the `_`. How do I achieve this?
has answer: http://stackoverflow.com/a/50961037
linked to: http://stackoverflow.com/q/34214139
answer count: 1

glade
tags question: http://stackoverflow.com/q/51010820
type: Tag
tag name: glade

http://stackoverflow.com/comment/88956514
score: 0
has text: thank you for your help! very helpful!
type: Comment
comment on: http://stackoverflow.com/a/50980465
type: AnswerComment

http://stackoverflow.com/q/50886999
tagged with: python
has title: Using semi-transparent palettes in bokeh
has comment: http://stackoverflow.com/comment/88775587
type: UnansweredQuestion
type: Question
tagged with: bokeh
has comment: http://stackoverflow.com/comment/88782053
score: 0
has body: I would like to create a color palette in bokeh that has varying alpha values, so some colors are semi-transparent. I tried to pass some RGBA value as hex (#33eedd777) or CSS colors (rgba(129, 23, 43, 90)) as a palette but bokeh raised a ValueError. Here is a code example: import numpy as np from bokeh.io import output_file, show from bokeh.plotting import figure from bokeh.transform import linear_cmap from bokeh.util.hex import hexbin n = 50000 x = np.random.standard_normal(n) y = np.random.standard_normal(n) bins = hexbin(x, y, 0.1) p = figure(tools="wheel_zoom,reset", match_aspect=True, background_fill_color='#440154') p.grid.visible = False cm = ['#08459400', '#f7fbffff'] cm = ['rgba(80, 80, 80, 10)', 'rgba(8, 8, 8, 255)', ] p.hex_tile(q="q", r="r", size=0.1, line_color=None, source=bins, fill_color=linear_cmap('counts', cm, 0, max(bins.counts))) show(p)
answer count: 1
tagged with: data-visualization
has answer: http://stackoverflow.com/a/50900704

http://stackoverflow.com/comment/88997823
comment on: http://stackoverflow.com/q/51001489
score: 0
type: Comment
type: QuestionComment
has text: try enabling debug log level to see whats happening https://stackoverflow.com/questions/23254013/http-digest-basic-auth-with-python-requests-module

http://stackoverflow.com/comment/88800319
has text: @Jon, That's a completely different question. In that case you'd use `pd.DataFrame.apply`. Which has a different syntax and a different purpose. I've rolled back your question because you shouldn't *change* your question once it's been answered. Feel free to ask a new question if you're stuck on `pd.DataFrame.apply`.
score: 0
comment on: http://stackoverflow.com/a/50899698
type: AnswerComment
type: Comment

http://stackoverflow.com/a/50912265
type: Answer
has body: Your post should also have headers (not just a payload). Importantly for this one, the __requestverificationtoken is likely the site's csrf token which is meant to improve security. payload = {"associateAccount":"false", "email":"myemail@email.com", "pin":"1234567890"} headers = { "__requestverificationtoken": "_Q4aj4hNp5uOMv6EbrD8KRQA85nsLLKRQIAC8m2PHNAvI2OHfUrtW11MANIjJVWWhqFJTjq1wHGMhCLj4AyLYCUcEqA1", "accept": "application/json, text/javascript", "accept-encoding": "gzip, deflate, br", "accept-language": "en-US,en;q=0.9", "content-type": "application/json", "x-requested-with": "XMLHttpRequest" } LOGIN_URL = 'https://www.puregym.com/api/members/login/' # Use 'with' to ensure the session context is closed after use. with requests.Session() as s: p = s.post(LOGIN_URL, data=payload, headers = headers) # print the html returned or something more intelligent to see if it's a successful login page. print(p.text) I don't have an account to test your login-required page, but the above code returns "Your email address or PIN is incorrect. Please try again." which suggests that the code is functioning correctly.
has comment: http://stackoverflow.com/comment/88855519
has comment: http://stackoverflow.com/comment/88826933
has comment: http://stackoverflow.com/comment/88825361
has comment: http://stackoverflow.com/comment/88855351
has comment: http://stackoverflow.com/comment/88827261
answers question: http://stackoverflow.com/q/50894712
has comment: http://stackoverflow.com/comment/88825005
has comment: http://stackoverflow.com/comment/88831935
score: 0
has comment: http://stackoverflow.com/comment/88855291

http://stackoverflow.com/q/50882980
tagged with: python
type: AnsweredQuestion
upvote count: 3
type: Question
linked to: http://stackoverflow.com/q/13638898
has answer: http://stackoverflow.com/a/50884346
has body: Reposting this after receiving down vote, did went back and try something but i guess still not there yet. File with data which looks like this: name count count1 count3 add1 add2 jack 70 55 31 100174766 100170715 jack 45 656 48 100174766 100174052 john 41 22 89 102268764 102267805 john 47 31 63 102268764 102267908 david 10 56 78 103361093 103368592 two conditions that i need to check and one math operation which need to be done later: A) which rows/lines have duplicate values in add1 ( always == 2) B) if they are equal to 2, which line/row has a greater value in add2 lets take jack for example: jack 70 55 31 100174766 100170715 jack 45 656 48 100174766 100174052 jack has two add1 == 2 ( occurs twice) and 100174052 is greater so: row1 = jack 45 656 48 100174766 100174052 row2 = jack 70 55 31 100174766 100170715 Math: for each cell between both the rows row1 /(row1+row2) output for jack : jack 0.391304348 0.922644163 0.607594937 100174766 100174052 final desired output name count count1 count3 add1 add2 jack 0.391304348 0.922644163 0.607594937 100174766 100174052 john 0.534090909 0.58490566 0.414473684 102268764 102267908 code so far: I know i have not accounted for which add2 is greater not sure where and how to do it info = [] with open('file.tsv', 'r') as j: for i,line in enumerate(j): lines = line.strip().split('\t') info.append(lines) uniq = {} for index,row in enumerate(info, start =1): if row.count(row[4]) == 2: key = row[4] + ':' + row[5] if key not in uniq: uniq[key] = row[1:3] for k, v in sorted(uniq.iteritems()): row1 = k,v row2 = k,v print 'row1: ', row1[0], '\n', 'row2: ',row2[0] all i see is: row1: 100174766:100170715 row2: 100174766:100170715 row1: 100174766:100174052 row2: 100174766:100174052 instead of row1: 100174766:100170715 row2: 100174766:100174052
possible better answer: http://stackoverflow.com/a/50887030
has comment: http://stackoverflow.com/comment/88778557
tagged with: python-2.7
answer count: 2
has answer: http://stackoverflow.com/a/50887030
score: 3
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/50884346
has comment: http://stackoverflow.com/comment/88774683
has title: conditional math operations between rows

http://stackoverflow.com/comment/88884265
type: QuestionComment
has text: You mean like _"If `i == 1` execute query1, if `i == 2` execute query2, else fail with a strange error message"_ ?
comment on: http://stackoverflow.com/q/50943381
score: 0
type: Comment

http://stackoverflow.com/comment/88787023
type: QuestionComment
has text: Would that be `amazonaws.com`? @KlausD.
score: 0
comment on: http://stackoverflow.com/q/50892938
type: Comment

http://stackoverflow.com/comment/88956206
type: QuestionComment
has text: I'm sorry for the "on hold " problem. As the result, Nishant Patel please understood my intention.
comment on: http://stackoverflow.com/q/50960316
score: 0
type: Comment

http://stackoverflow.com/comment/88989445
type: Comment
comment on: http://stackoverflow.com/q/50997647
type: QuestionComment
score: 0
has text: What line gives you error? Post a complete error message.

http://stackoverflow.com/comment/88876918
score: 0
comment on: http://stackoverflow.com/a/50938928
type: Comment
has text: Using selenium, once im at the landing page after logging in how would i store the html as a df
type: AnswerComment

http://stackoverflow.com/q/50988232
score: 4
has title: Get user status (disabled or active) in Active Directory with ldap3 Python
has answer: http://stackoverflow.com/a/50990876
answer count: 1
tagged with: active-directory
linked to: http://stackoverflow.com/q/13597345
accepted answer: http://stackoverflow.com/a/50990876
upvote count: 4
type: AnsweredQuestion
tagged with: ldap3
downvote count: 0
favorite count: 0
type: Question
tagged with: python
has body: I am getting a list of all users in Active Directory and I need to check their status — if the user is active or disabled. I expect that userAccountControl should return user status, but I get only 512 for all users but one (who returns 66048) and this is not correlated with user status (as far as I know). from ldap3 import Server, Connection serverName = 'LDAP://server' domainName = 'name' userName = 'superuser' password = 'password' base = 'longString' server = Server(serverName) conn = Connection(server, read_only=True, user='{0}\\{1}'.format(domainName, userName), password=password, auto_bind=True) conn.search(base, '(objectclass=person)', attributes=['displayName', 'mail', 'userAccountControl','sAMAccountName']) for i in conn.entries: print 'USER = {0} : {1} : {2}'.format(i.sAMAccountName.values[0], i.displayName.values[0], i.userAccountControl.values[0]) USER = ABC : John Smith : 512 USER = DEF : Sarah Connor : 514 USER = GHI : Thomas Anderson : 66048 Is it a correct way to get user status? Is there any other way to check AD user status with some application with UI?

http://stackoverflow.com/comment/88902712
has text: Still a lot cheaper to read 10 files once at startup rather than 10 files every polling period. If you don't know the names yet at startup time, you can cache them and only do a read when you're asked for a file you haven't seen yet.
comment on: http://stackoverflow.com/q/50951632
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/a/51001268
has body: You can subtract a constant value but using tensor operations only: def pre_pro_layer(x): x = x*255.0 # this is fine tosub = K.constant([103.939, 116.779, 123.68]) # repeat or tile tosub based on the shape of x, depends on what you have # ... return x - tosub # element wise subtraction Note that subtraction does support broadcasting so you don't have to get exactly the same shape as x but something that would broadcast to the shape of x when subtracting.
score: 0
answers question: http://stackoverflow.com/q/51000885
type: Answer

http://stackoverflow.com/q/50941203
has comment: http://stackoverflow.com/comment/88880899
tagged with: excel
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/88880828
favorite count: 0
linked to: http://stackoverflow.com/q/28517508
has body: I am trying to use a python code to alter a single value in excel sheet and based on that value, certain calculations are being performed on the sheet itself. Finally, I need to read the answer but instead of the value, it is giving me the formula. import math import openpyxl M, Vb = 0, 0 wb = openpyxl.load_workbook(r"calc.xlsx") data_sheet = wb['Sheet2'] calc_sheet = wb['Sheet1'] Vb = data_sheet.cell(row=2,column=1).value calc_sheet.cell(row=30,column=4).value = Vb wb.save(r"calc.xlsx") M = calc_sheet.cell(row=26,column=4).value print(M) it returns P33 rather than the numerical value.
has title: How to copy a cell value instead of a formula from Excel using Python
tagged with: python
has comment: http://stackoverflow.com/comment/88880596
has comment: http://stackoverflow.com/comment/88880173
answer count: 0
type: UnansweredQuestion
score: 1
upvote count: 1

http://stackoverflow.com/q/50937826
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/50956831
has comment: http://stackoverflow.com/comment/88901330
downvote count: 0
has answer: http://stackoverflow.com/a/50937992
has body: I would like to make a directory tree in a docstring and have it rendered without change to my Sphinx documentation, but I am having trouble. I have tried using: single, double, and triple back-ticks; literal :code:; and literal .. code-block:: python to get this to work. I imagine the latter two did not work because this block is also not valid Python/code. In addition I have varied the number and type of indentation and spacing, to no avail. My example (using three back-ticks to delineate the block in question) is below. Therefore my question is - how does one render a block from a docstring to Sphinx exactly as shown in the docstring? I basically want to turn off the markup for a moment and present the pipes and indents as I would in a text file. In the interest of full disclosure, I did find this kind-of related post but it appears the OP had already given up on Sphinx by the time they asked, the post is from 2015, and they had different constraints (leading/trailing blank lines, versus indents and pipes). It's crazy to me to think that there wouldn't be a way to do this? Example: class SetUp(object) """Set up temp folders, log files, and global variables. The folder tree for setting up looks as follows (using attached attribute names rather than paths): ``` |-- workspace |-- folder_name (all up to this point = work_folder) |-- proc_id (^= process_path) |-- gdb_name.gdb (^= gdb_full_path) ``` Using `^=` as short-hand for `'all up to this point, os.path.join()`. Attributes ---------- (Etc) """ def __init__(self, log_level, proc_id, gdb_name): self.folder_name = "CHECKLIST" self.proc_id = proc_id # Etc
has comment: http://stackoverflow.com/comment/88882432
has title: Creating a literal text block in Sphinx
favorite count: 0
tagged with: python-sphinx
linked to: http://stackoverflow.com/q/34050044
tagged with: python
possible better answer: http://stackoverflow.com/a/50937992
score: 11
tagged with: restructuredtext
upvote count: 11
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50956831

http://stackoverflow.com/q/50910900
possible better answer: http://stackoverflow.com/a/50911002
type: Question
has answer: http://stackoverflow.com/a/50911002
has answer: http://stackoverflow.com/a/50911980
has body: I have a simple algorithm which calculate GCD for 2 integers. What I'm trying to do is to use result of this function to calculate GCD for more then 2 integers. For example GCD for 99 and 22 is 11. Then I want to use 11 as first integer and some number. The thing is I don't know how to use a first result to calculate another one. Especially if there are more then 3 integers because user decides for how many of them the GCD will be calculated. Here is my code (which work only for 2 integers): required_inputs = int(input("For how many numbers would you like to find their GCD?: ")) received_inputs = [] for num in range(0, required_inputs): values = int(input()) received_inputs.append(values) if len(received_inputs) == 0: values = int(input()) received_inputs.append(values) def GCD(a, b): if b == 0: return a else: return GCD(b, a % b) print(GCD(received_inputs[0], received_inputs[1]))
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/88821766
has title: How to use result of function as an argument of the same function multiple times?
has comment: http://stackoverflow.com/comment/88822019
accepted answer: http://stackoverflow.com/a/50911980
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/88876144
type: Comment
comment on: http://stackoverflow.com/a/50938906
has text: if i use yours method i will lose keys also is `*dct.values` means `mydict`?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88803948
comment on: http://stackoverflow.com/q/50901109
has text: Did you inspect the traceback from the `AttributeError`? Re-write as `except AttributeError as error` and call the `logger.exception(error)`.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88804878
type: Comment
type: QuestionComment
has text: But where is reader.compressed coming from?
score: 0
comment on: http://stackoverflow.com/q/50902445

http://stackoverflow.com/q/50896674
type: AnsweredQuestion
tagged with: ubuntu-16.04
accepted answer: http://stackoverflow.com/a/50896776
downvote count: 1
type: Question
linked to: http://stackoverflow.com/q/41573587
has title: Remove old version of python and replace it
has comment: http://stackoverflow.com/comment/88793252
has body: I am using Ubuntu 16.04 LTS. I installed python 3.6 using sudo apt-get python 3.6. But python 3.5 is still installed. How do I remove 3.5 and set 3.6 as default in place of it so that when I type python3 --version in terminal it shows 3.6.5 instead of 3.5.2
answer count: 1
linked to: http://stackoverflow.com/q/28831854
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50896776
tagged with: terminal
upvote count: 2
tagged with: python

http://stackoverflow.com/comment/88812168
type: Comment
score: 2
comment on: http://stackoverflow.com/q/50906123
type: QuestionComment
has text: You might want to import `load_img` as you have imported `ImageDataGenerator` and use it directly.

http://stackoverflow.com/q/50903390
favorite count: 0
has body: The first module minibatch. import numpy as np import tensorflow as tf import Utils.neighbor_samplers as samplers class Minibatch: def __init__(self, embedding, batch_size): self.embedding = embedding self.batch_idx = [i for i in range(self.embedding.shape[0])] self.batch_size = batch_size self.iters = 0 self.batch_permutation = np.random.permutation(self.batch_idx) #List self.next_batch = [] self.max_iters = embedding.shape[0] // self.batch_size def next_batch(self): self.start_idx = self.iters * self.batch_size self.iters += 1 self.end_idx = self.start_idx + self.batch_size #next_batch = tf.nn.embedding_lookup(embedding, [i for i in range(start_idx, end_idx)]) self.next_idx = self.batch_permutation[self.start_idx : self.end_idx] #next_neighbors = tf.nn.embedding_lookup(self.embedding, next_idx) def shuffle(self): self.batch_permutation = np.random.permutation(self.batch_idx) self.batch_num = 0 and the second module model. def train(self): batch = minibatch.Minibatch(self.normal_embedding, self.batch_size) for epoch in range(self.epoch): batch.shuffle() print('Epoch : %04d' %(epoch + 1)) for iter in range(batch.max_iters): if iter % 100 == 0 and iter != 0: print('%d iters done' %(iter)) next_idx = batch.next_batch With the last line next_idx = batch.next_batch, I want to get the next batch's indexes to look up in embeddings. But it keeps showing empty list as result.
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/88807531
score: 1
type: Question
downvote count: 0
tagged with: class
has title: Cannot get next batch's embedding indexes
tagged with: python

http://stackoverflow.com/q/50922606
tagged with: tensorflow
type: Question
has title: How to choose number of perceptron in fine-tuning FC layer?
has body: I use VGG-16 pre-trained model and fine-tune the last 3 FC layers. But in my case, I only use 3 classes as my classification. I want to ask how to choose the perceptron of FC layers. Should I visualize the Conv5_3 layer, then making a decision? BTW, VGG-16 official model is 4096, 4096, 1000 perceptron in FC layers.
score: 0
has answer: http://stackoverflow.com/a/50923449
answer count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/50923449
type: AnsweredQuestion

http://stackoverflow.com/q/50932489
type: Question
has body: I'm trying to predict Para using Cols. My data is in this format: Record ID Para Col2 Col3 1 A x a 1 A x b 2 B y a 2 B y b 1 A z c 1 C x a So far, I have tried applying One Hot Encoding (OHE) and running algorithms on the following transformed data: Record Para a b c x y z 1 A 1 1 1 1 0 1 1 C 1 1 1 1 0 1 2 B 1 1 0 0 1 0 The accuracy has been shoddy, highest of 27% with Logistic Regression. I tried kNN, Random Forest, Decision Tree. Next, I tried encoding the Cols to ordinal variables and then reran the algorithms (except Logistic Regression). Similarly poor results. Am I doing something incorrectly? How can I improve the accuracy? The raw data is 249681 rows × 9 columns. Both outcome and predictor columns are categorical. When doing OHE, the data is 5534 rows × 865 columns. One thing that I'd like to try is Naive Bayes that calculates P(Outcome|Predictor) and then assign the highest probability predictor to the outcome. Is that a reasonable approach to take?
score: -2
has comment: http://stackoverflow.com/comment/88863832
tagged with: pandas
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/88863815
tagged with: scikit-learn
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50932574
downvote count: 2
has title: How do I improve model accuracy predicting categorical outcome using categorial predictors?
tagged with: machine-learning

import
type: Tag
tags question: http://stackoverflow.com/q/50900030
tags question: http://stackoverflow.com/q/50918217
tags question: http://stackoverflow.com/q/50902805
tag name: import
tags question: http://stackoverflow.com/q/50881563
tags question: http://stackoverflow.com/q/50871611
tags question: http://stackoverflow.com/q/50922474
tags question: http://stackoverflow.com/q/50891514
tags question: http://stackoverflow.com/q/50992080
tags question: http://stackoverflow.com/q/50882841
tags question: http://stackoverflow.com/q/50897094
tags question: http://stackoverflow.com/q/50969330
tags question: http://stackoverflow.com/q/50938277
tags question: http://stackoverflow.com/q/50987150
tags question: http://stackoverflow.com/q/50859626
tags question: http://stackoverflow.com/q/50882040
tags question: http://stackoverflow.com/q/50936154
tags question: http://stackoverflow.com/q/50913431
tags question: http://stackoverflow.com/q/50881667

http://stackoverflow.com/a/50898699
score: 0
has comment: http://stackoverflow.com/comment/88817464
has body: This is another way you might wanna give atry: import requests from bs4 import BeautifulSoup url = "https://www.reuters.com/finance/stocks/company-officers/MPAPss.BO" response = requests.get(url) soup = BeautifulSoup(response.content, 'html.parser') table = soup.find('table', {'class': 'dataTable'}) for row in table.find_all("tr")[1::1]: col = row.find_all("td") name = col[0].get_text(strip=True) year = col[2].get_text(strip=True) position = col[3].get_text(strip=True) print("Name: {} Year: {} Position: {}".format(name,year,position)) Output: Name: K. Ratna Prabha Year: 2014 Position: Non-Executive Chairman of the Board Name: Mohan Kulkarni Year: 2012 Position: Compliance Officer, Company Secretary Name: Naveen Singh Year: 2014 Position: Managing Director, Executive Director Name: B. Khanna Year: 2014 Position: Non-Executive Director - Nominee of BIFR Name: V. Rammohan Year: 2013 Position: Non-Executive Director - Nominee of IFCI Name: Aravind Shrivastava Year: 2013 Position: Non-Executive Director Name: M. Lakshminarayana Year: 2009 Position: Non-Executive Independent Director Name: C. Okaly Year: 2010 Position: Non-Executive Independent Director Name: S. Parameswarappa Year: 1996 Position: Non-Executive Independent Director Name: C. Shivashankar Year: 1995 Position: Non-Executive Independent Director
type: Answer
has comment: http://stackoverflow.com/comment/88817283
answers question: http://stackoverflow.com/q/50898312

http://stackoverflow.com/a/50929599
answers question: http://stackoverflow.com/q/50929367
has body: Maybe this one can help!! mylist = ['abc', 'def', 'ghi', 'jkl', 'mno'] str1 = 'does mn have anything to do with it?' str2 = 'I think mn is there' b = [i for i, s in enumerate(mylist) for st in str2.split(' ') if st in s] print(b)
type: Answer
has comment: http://stackoverflow.com/comment/88858100
score: 0

oop
tags question: http://stackoverflow.com/q/50931196
tags question: http://stackoverflow.com/q/50879774
tags question: http://stackoverflow.com/q/50905843
tags question: http://stackoverflow.com/q/50940542
tag name: oop
tags question: http://stackoverflow.com/q/50954306
tags question: http://stackoverflow.com/q/50957382
tags question: http://stackoverflow.com/q/50942550
tags question: http://stackoverflow.com/q/51010228
tags question: http://stackoverflow.com/q/50957742
tags question: http://stackoverflow.com/q/50952539
tags question: http://stackoverflow.com/q/50963544
tags question: http://stackoverflow.com/q/51006809
tags question: http://stackoverflow.com/q/50964709
tags question: http://stackoverflow.com/q/50869654
tags question: http://stackoverflow.com/q/50984288
tags question: http://stackoverflow.com/q/50890416
tags question: http://stackoverflow.com/q/50880376
type: Tag
tags question: http://stackoverflow.com/q/50960719

wsgi
type: Tag
tags question: http://stackoverflow.com/q/50925596
tags question: http://stackoverflow.com/q/50913981
tags question: http://stackoverflow.com/q/50916796
tags question: http://stackoverflow.com/q/50913166
tags question: http://stackoverflow.com/q/50967352
tag name: wsgi

http://stackoverflow.com/comment/88981393
type: Comment
comment on: http://stackoverflow.com/a/50993173
has text: But anyway, it's more efficient (and more Pythonic) to use a `for` loop rather than a`while` loop, when you have a choice. And it's better to loop directly over a container's items rather than using indirect looping with indices.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88944804
comment on: http://stackoverflow.com/q/50970652
score: 0
type: QuestionComment
has text: What is the version of your `tldextract`? The version I have -- 2.2.0 does not have this issue. `pip freeze | grep tldextract` tells the version.
type: Comment

object
tags question: http://stackoverflow.com/q/50909641
tag name: object
tags question: http://stackoverflow.com/q/50893267
tags question: http://stackoverflow.com/q/50995225
tags question: http://stackoverflow.com/q/50954306
tags question: http://stackoverflow.com/q/50901470
tags question: http://stackoverflow.com/q/50971075
tags question: http://stackoverflow.com/q/50916006
tags question: http://stackoverflow.com/q/50935134
tags question: http://stackoverflow.com/q/50882547
tags question: http://stackoverflow.com/q/50964041
tags question: http://stackoverflow.com/q/50951284
type: Tag
tags question: http://stackoverflow.com/q/50864868

http://stackoverflow.com/comment/88785683
score: 1
type: AnswerComment
has text: Ok, that makes sense since `run_forever()` is blocking, adding `close()` does nothing, then in my exit call before shutting down application I run `loop.call_soon_threadsafe(loop.stop)` then it shuts down nicely, that worked perfectly. Thank you.
type: Comment
comment on: http://stackoverflow.com/a/50891817

http://stackoverflow.com/comment/89014145
type: QuestionComment
has text: Can you post a sample of your JSON and expected output?
score: 0
comment on: http://stackoverflow.com/q/51010647
type: Comment

http://stackoverflow.com/q/50904327
tagged with: subprocess
has title: Unsupported operand type(s) for +: 'Popen' and 'str'' in subprocess.Popen
type: Question
has answer: http://stackoverflow.com/a/50904487
has comment: http://stackoverflow.com/comment/88808802
duplicate of: http://stackoverflow.com/q/25465700
has body: I'm looking at this script to disable shell=True while creating an ova. It works when shell=True but gives me a TypeError when shell=False. I'm pretty sure the issue is with this part of the command - " vi:\//" + username + ":" + encodedPassword + "@" + hostname" - because when I remove this element from the list (i.e. command), the script moves forward. I've tried hardcoding values like "vi:\//user:password@70.60.70.90" and also removed so but I still get this type error. Python version is 2.7 com1 = "/usr/bin/ovftool --acceptAllEulas --disableVerification --noSSLVerify --datastore=" + datastore + " --network=\"" + network + "\" --name=" + name + " " + ovalocation + " vi:\//" + username + ":" + encodedPassword + "@" + hostname #prior to disabling shell=True # coms = subprocess.Popen(com1, shell=True, # stdout=subprocess.PIPE, stderr=subprocess.PIPE) # set shell=False - now it requires the command to be a list rather than a string. coms = subprocess.Popen(com1.split(), shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE) Error: 'unsupported operand type(s) for +: 'Popen' and 'str'' What am I doing wrong? Edit: I know it's an issue with the vi command becuase when replace "vi:\//" + username + ":" + encodedPassword + "@" + hostname" with a hardcoded "hello" the script moves forward.
score: 0
has comment: http://stackoverflow.com/comment/88808527
has comment: http://stackoverflow.com/comment/88808932
upvote count: 1
has comment: http://stackoverflow.com/comment/88808607
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/88809399
tagged with: ova
favorite count: 0
has comment: http://stackoverflow.com/comment/88813173
tagged with: virtualization
tagged with: ovf
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/25465700
has comment: http://stackoverflow.com/comment/88808511
tagged with: python
has comment: http://stackoverflow.com/comment/88809500

http://stackoverflow.com/comment/88873442
comment on: http://stackoverflow.com/q/50936802
has text: my goal is to run a 2D convolution over the individual matrices. Let's say that the matrices represent X,Y components of vectors, and the vectors are arranged in a matrix. I want to run a gaussian blur over the X components individually and then over the Y components.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/50933292
upvote count: 4
has comment: http://stackoverflow.com/comment/88866847
type: AcceptedAnswer
score: 4
accepted answer of: http://stackoverflow.com/q/50932527
downvote count: 0
has comment: http://stackoverflow.com/comment/88865665
answers question: http://stackoverflow.com/q/50932527
type: Answer
has comment: http://stackoverflow.com/comment/88866784
has comment: http://stackoverflow.com/comment/88867816
has body: You didn't define a main() function in app.py, so from app import main fails, yes. You could just import the app Flask object, and call the run() method on that: from app import app app.run(host='0.0.0.0', port=8000) Not that you should use this in production deployments. You'd instead instruct a production-ready WSGI server to use the app object in the app module as the WSGI application. See the Flask deployment documentation.
has comment: http://stackoverflow.com/comment/88869068

http://stackoverflow.com/q/50914650
tagged with: openimageio
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question
accepted answer: http://stackoverflow.com/a/50933632
has title: Resize image using Python OpenImageIO maintain aspect ratio
has body: I'm trying to resize an image after doing some additional processing using OpenImageIO and python. However it appears this process not is as easy as PIL. In PIL i can supply a new resolution for example 512 x 512 and it will resize my image regardless of it's current pixel aspect and resize it to fit it's maximum length so it fits inside a 512x512 box. How can i do this using OpenImageIO? Currently this will just stretch the image to fit withint 512x512. So images that favor width should fit based on the width value: Whereas images that favor height should fit based on the height value: buf = oiio.ImageBuf(file) data = buf.spec() print data.width print data.height resized = oiio.ImageBuf(oiio.ImageSpec (512, 512, 3, oiio.FLOAT)) oiio.ImageBufAlgo.resize(resized, buf, roi=oiio.ROI.All, nthreads=4) resized.write(output)
has answer: http://stackoverflow.com/a/50933632
upvote count: 1
answer count: 1
favorite count: 0

http://stackoverflow.com/q/50998588
tagged with: pandas
has comment: http://stackoverflow.com/comment/88991429
has comment: http://stackoverflow.com/comment/88991341
favorite count: 0
has comment: http://stackoverflow.com/comment/88991408
type: UnansweredQuestion
upvote count: 1
tagged with: python
has body: I'm trying to merge 2 dataframe with that line` recommendations_df = recommendations_df.merge(anime_df, how = 'left', left_on = 'name', right_on = 'name')'episodes', 'user_rating', 'anime_id', 'genre', "Score", "name", "type", "members" the key "name" is in both dataframe but when i run code it works but return the initial dataframe (recommandations) without column that i want (episodes ...etc). recommendations_df looks like name Score 0 Shinreigari Ghost Hound 0.946970 2 Wonderful Rush 0.882727 3 Saber Marionette J to X 0.836957 5 Hyouka 0.812808 6 Super Lovers 0.811879 and anime_df anime_id name genre type episodes rating members map_id 0 32281 Kimi no Na wa Drama, Romance, School, Supernatural Movie 1 9.37 200630.0 0 1 5114 Fullmetal Alchemist Brotherhood Action, Adventure, Drama, Fantasy, Magic, Mili... TV 64 9.26 793665.0 1 2 28977 Gintama Action, Comedy, Historical, Parody, Samurai, S... TV 51 9.25 114262.0 2 3 9253 Steins Gate Sci-Fi, Thriller TV 24 9.17 673572.0 3 4 9969 Gintama 039 Action, Comedy, Historical, Parody, Samurai, S... TV 51 9.16 151266.0 4
has comment: http://stackoverflow.com/comment/88991368
has comment: http://stackoverflow.com/comment/88991385
has comment: http://stackoverflow.com/comment/88991413
has comment: http://stackoverflow.com/comment/88991356
answer count: 0
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88997937
has title: Merge function doesn't return merged dataframe
score: 0

cryptography
tag name: cryptography
type: Tag
tags question: http://stackoverflow.com/q/50933460
tags question: http://stackoverflow.com/q/50953776
tags question: http://stackoverflow.com/q/50935381

http://stackoverflow.com/comment/88774258
has text: @Abhishek That dupe does not answer the question. The OP does not want to create a new list object, they want to modify an existing one
type: QuestionComment
comment on: http://stackoverflow.com/q/50886316
type: Comment
score: 2

http://stackoverflow.com/comment/88993105
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50999344
has text: @TaohidulIslam, you might have made a typo. You have `walk("I'm walking instead of flying.")` twice. :p

http://stackoverflow.com/a/50994892
has body: So this wound up being a quirk of the Django url setup, I can't believe I didn't figure it out but I hadn't been in that part of the code base for some time. In our urls.py script, the place I was pinging (which was in the location of the URL described) had a redirect on it and for that reason, the traffic wasn't going to the place I thought.
type: Answer
accepted answer of: http://stackoverflow.com/q/50938413
answers question: http://stackoverflow.com/q/50938413
type: AcceptedAnswer
score: 0

http://stackoverflow.com/comment/88737604
has text: the rows 11 and 13 have different `type_2` and `id_2` - they are in the merged dataframe after first merge. their `type_3` and `id_3` also different -why is this result unsatisfactory for your task?
comment on: http://stackoverflow.com/q/50867737
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/88735971
type: AnswerComment
comment on: http://stackoverflow.com/a/50866388
type: Comment
score: 0
has text: @HiteshRahangdale no worry :-) happy coding

http://stackoverflow.com/a/50909901
has comment: http://stackoverflow.com/comment/88822009
type: Answer
has body: Using just sorted with lambda function in key should work. Ex: import csv with open(filename, "rU") as f_input: csv_input = csv.reader(f_input) header = next(csv_input) data = sorted(csv_input, key=lambda x: x[1]) print(data) Output: [['100', 'Anne', '3', '4', '5'], ['103', 'Bo', '3', '6', '5'], ['101', 'Frank', '1', '2', '3'], ['104', 'James', '4', '7', '2'], ['102', 'Shawn', '7', '8', '9']] Edit as per comment with open(filename, "wb") as f_input: csv_out = csv.writer(f_input) csv_out.writerow(header) csv_out.writerows(data)
has comment: http://stackoverflow.com/comment/88821797
has comment: http://stackoverflow.com/comment/88825612
upvote count: 4
has comment: http://stackoverflow.com/comment/88820401
downvote count: 0
answers question: http://stackoverflow.com/q/50909772
score: 4
has comment: http://stackoverflow.com/comment/88820733
has comment: http://stackoverflow.com/comment/88820157

http://stackoverflow.com/comment/95378824
score: 9
type: AnswerComment
has text: You forgot `from telethon.tl.functions.messages import GetHistoryRequest`
comment on: http://stackoverflow.com/a/50989741
type: Comment

http://stackoverflow.com/comment/127800328
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/50995290
type: Comment
has text: Why? The `mock` package from PyPI is the same as standard library `unittest.mock`. The only difference is that it allows you to use a newer (or older) version than the one bundled with your Python.

http://stackoverflow.com/q/50975389
tagged with: tensorflow
type: Question
accepted answer: http://stackoverflow.com/a/50984516
answer count: 2
tagged with: cross-entropy
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/50988516
has answer: http://stackoverflow.com/a/50984516
has answer: http://stackoverflow.com/a/50988516
upvote count: 1
tagged with: python
has title: NaN with softmax cross entropy in simple model with dummy inputs
type: AnsweredQuestion
score: 1
has body: I was simplifying my model in order to see where the NaN error occurs and narrowed it down to my loss function: import tensorflow as tf from tensorflow.python import debug as tf_debug def train_input_fn(): pass def model_fn(features, labels, mode, params): classes = 225 enc = tf.ones((1,20,1024), dtype=tf.float16) labels = tf.ones((1,20), dtype=tf.int32) logits = tf.layers.dense(enc, classes) loss = tf.reduce_sum(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=labels)) / 20 train_op = tf.train.AdamOptimizer(learning_rate=0.00001, beta1=0.9, beta2=0.999).minimize(loss) return tf.estimator.EstimatorSpec(mode, loss=loss, train_op=train_op) if __name__ == '__main__': model_directory = path/to/logdir hooks = [tf_debug.LocalCLIDebugHook(ui_type="readline")] classifier = tf.estimator.Estimator( model_fn=model_fn, model_dir=model_directory, params={}, ) classifier.train(input_fn=lambda: train_input_fn(), hooks = hooks) After the third or fourth 'run' with the tensorflow debugger on a fresh model directory I get 'NaN loss during training.'. I already tried to set the learning rate very low, but nothing changed. I'm using tensorflow-gpu 1.8.

http://stackoverflow.com/a/50940710
score: 0
upvote count: 1
type: AcceptedAnswer
type: Answer
downvote count: 1
answers question: http://stackoverflow.com/q/50940424
accepted answer of: http://stackoverflow.com/q/50940424
has body: I think you want the &lt;ul&gt; after the h2 tag that starts the "See also" section. One way to find that h2 is to use CSS selectors to find the right tag, then grab the parent element (the h2), and then get the next sibling from there: def wikipediaCrawler(page, maxPages): #... soup = BeautifulSoup(plainText, "html.parser") see_also = soup.select("h2 &gt; #See_also")[0] ul = see_also.parent.find_next_sibling("ul") for link in ul.findAll('a'): page = str(link.get('href')) print(page) wikipediaCrawler("/wiki/Online_chat", 3) Output: /wiki/Chat_room /wiki/Collaborative_software /wiki/Instant_messaging /wiki/Internet_forum /wiki/List_of_virtual_communities_with_more_than_100_million_active_users /wiki/Online_dating_service /wiki/Real-time_text /wiki/Videotelephony /wiki/Voice_chat /wiki/Comparison_of_VoIP_software /wiki/Massively_multiplayer_online_game /wiki/Online_game /wiki/Video_game_culture

http://stackoverflow.com/a/50883944
has body: Depending on how large your array is, and how likely duplicates are, the answer will be different. For example, if you expect the average array to have around 3 duplicates, early exit will cut your average-case time (and space) by 2/3rds; if you expect only 1 in 1000 arrays to have any duplicates at all, it will just add a bit of complexity without improving anything. Meanwhile, if the arrays are big enough that building a temporary set as large as the array is likely to be expensive, sticking a probabilistic test like a bloom filter in front of it will probably speed things up dramatically, but if not, it's again just wasted effort. Finally, you want to stay within numpy if at all possible. Looping over an array of floats (or whatever) and boxing each one into a Python object is going to take almost as much time as hashing and checking the values, and of course storing things in a Python set instead of optimized numpy storage is wasteful as well. But you have to trade that off against the other issues—you can't do early exit with numpy, and there may be nice C-optimized bloom filter implementations a pip install away but not be any that are numpy-friendly. So, there's no one best solution for all possible scenarios. Just to give an idea of how easy it is to write a bloom filter, here's one I hacked together in a couple minutes: from bitarray import bitarray # pip3 install bitarray def dupcheck(X): # Hardcoded values to give about 5% false positives for 10000 elements size = 62352 hashcount = 4 bits = bitarray(size) bits.setall(0) def check(x, hash=hash): # TODO: default-value bits, hashcount, size? for i in range(hashcount): if not bits[hash((x, i)) % size]: return False return True def add(x): for i in range(hashcount): bits[hash((x, i)) % size] = True seen = set() seen_add = seen.add for x in X: if check(x) or add(x): if x in seen or seen_add(x): return True return False This only uses 12KB (a 62352-bit bitarray plus a 500-float set) instead of 80KB (a 10000-floa…
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50883576
score: 1
upvote count: 1

http://stackoverflow.com/comment/88783275
score: 0
type: Comment
type: QuestionComment
has text: @Apalala I actually want to make each `yield` output to has its own `JSON` file, instead of all in a single file.
comment on: http://stackoverflow.com/q/50890686

http://stackoverflow.com/comment/118292527
has text: add the path like this , data = os.path.abspath(os.path.dirname(__file__)) + "/serviceAccountKey.json"
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/66886716
score: 1

http://stackoverflow.com/a/50893667
upvote count: 1
has comment: http://stackoverflow.com/comment/88787628
score: 1
has body: File.readlines() returns a list of lines So the line that you read should be in: HubLines[0] or try just: HubLines When you try to access HubLines[1] it says out of range because it doesn't exist
accepted answer of: http://stackoverflow.com/q/50893596
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50893596

http://stackoverflow.com/a/73817867
has body: Its currently 2022 in the future and this works for me with Jupyer labs running on Ubuntu 20.04 pip install pyx At least this works for me: from scapy.all import * pkt = IP() pkt.canvas_dump()
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50914059
type: Answer

http://stackoverflow.com/q/51002735
score: 0
answer count: 3
tagged with: mysql-python
has answer: http://stackoverflow.com/a/78219067
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: python mysqldb err on my mac :Library not loaded: @rpath/libmysqlclient.21.dylib
has answer: http://stackoverflow.com/a/51107152
has body: import MySQLdb leads to Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "build/bdist.macosx-10.13-intel/egg/MySQLdb/__init__.py", line 19, in &lt;module&gt; File "build/bdist.macosx-10.13-intel/egg/_mysql.py", line 7, in &lt;module&gt; File "build/bdist.macosx-10.13-intel/egg/_mysql.py", line 6, in __bootstrap__ ImportError: dlopen(/Users/simon/.python-eggs/MySQL_python-1.2.5-py2.7-macosx-10.13-intel.egg-tmp/_mysql.so, 2): Library not loaded: @rpath/libmysqlclient.21.dylib Referenced from: /Users/simon/.python-eggs/MySQL_python-1.2.5-py2.7-macosx-10.13-intel.egg-tmp/_mysql.so Reason: image not found` I try to build and install mysql-python, and ln -s /usr/local/mysql/lib/libmysqlclient.18.dyli, but can not resolve it
tagged with: mysql
upvote count: 1
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/53589768

http://stackoverflow.com/q/50970555
favorite count: 0
has answer: http://stackoverflow.com/a/60343299
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/53720808
duplicate of: http://stackoverflow.com/q/41912372
tagged with: python
answer count: 10
has answer: http://stackoverflow.com/a/63205247
has body: Trying to install dlib on Windows 10 using pycharm package manager. I have Numpy, opencv-python, setuptools and wheel installed. tried installing dlib then got the first error asking me to install CMake. Now I'm getting this: (tried installing visual studio but it had no effect). Collecting dlib Using cached https://files.pythonhosted.org/packages/d5/5c/aa64510aa354d562ecba7edecd500b020280741140e5d91ff5ec1c6f8289/dlib-19.13.1.tar.gz Building wheels for collected packages: dlib Running setup.py bdist_wheel for dlib: started Running setup.py bdist_wheel for dlib: finished with status 'error' Complete output from command C:\Users\Tom\venv\Scripts\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\Tom\\AppData\\Local\\Temp\\pycharm-packaging\\dlib\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d C:\Users\Tom\AppData\Local\Temp\pip-wheel-f_njkl2_ --python-tag cp36: running bdist_wheel running build running build_py package init file 'dlib\__init__.py' not found (or not a regular file) warning: build_py: byte-compiling is disabled, skipping. running build_ext Building extension for Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 16:07:46) [MSC v.1900 32 bit (Intel)] Invoking CMake setup: 'cmake C:\Users\Tom\AppData\Local\Temp\pycharm-packaging\dlib\tools\python -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=C:\Users\Tom\AppData\Local\Temp\pycharm-packaging\dlib\build\lib.win32-3.6 -DPYTHON_EXECUTABLE=C:\Users\Tom\venv\Scripts\python.exe -DCMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE=C:\Users\Tom\AppData\Local\Temp\pycharm-packaging\dlib\build\lib.win32-3.6' -- Building for: NMake Makefiles -- The C compiler identification is unknown -- The CXX compiler identification is unknown CMake Error in CMakeLists.txt: The CMAKE_C_COMPILER: cl is not a full path and was not found in the PATH. To use the NMake generator with Visual C++, cmake must be run from a shell that can use the c…
tagged with: dlib
has title: failing to install dlib on windows 10
tagged with: pycharm
upvote count: 3
has comment: http://stackoverflow.com/comment/108978062
has answer: http://stackoverflow.com/a/56180644
has answer: http://stackoverflow.com/a/64533026
has answer: http://stackoverflow.com/a/53688652
type: Question
has answer: http://stackoverflow.com/a/51264508
linked to: http://stackoverflow.com/q/58777497
has answer: http://stackoverflow.com/a/52894667
score: 3
has answer: http://stackoverflow.com/a/64251395
downvote count: 0
has answer: http://stackoverflow.com/a/51033941

http://stackoverflow.com/q/50874061
has comment: http://stackoverflow.com/comment/88749878
has body: I'm reading a file line per line and checking where a code section ends: a specific sequence of characters appears. This sequence could occur within the code section so i have to check the redundancy : how many times successive lines contains the sequence. with 10 successive occurences i should return the first line where the successive occurences started to detect the end of the code section. regexp_dict_02 = {'Name': 'EMPTY_PAGES', 'Expr': '(FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)'} def FindEmptyPg(Inpfile,Section): NbrLine = [] Pos = [] flag = 0 index = 0 Ln = 0 with open(Inpfile) as fp: for i, line in enumerate(fp): if i &gt;= Section.startline and i &lt; 30061 : s=re.search(regexp_dict_02['Expr'],line) if s: NbrLine.append(i) logging.info (NbrLine) logging.info (len(NbrLine)) for index in range((len(NbrLine))-1): if NbrLine[index+1] - NbrLine[index] == 1 : logging.info (str (NbrLine[index+1]) + ' ' + str(NbrLine[index])) Pos.append (index) flag += 1 if flag == 5 : Ln = NbrLine[Pos[0]] break logging.info (Pos) return Ln enter image description here in the above Code I'm checking only on two successive lines and i get the wrong line number. i avoided using complicated stuff like state machines and so on but im still stuck.
has title: python find section in file with most regular expression match occurences
tagged with: python
tagged with: regex
type: AnsweredQuestion
score: 2
tagged with: list
downvote count: 0
type: Question
has comment: http://stackoverflow.com/comment/88750312
has comment: http://stackoverflow.com/comment/88750064
has answer: http://stackoverflow.com/a/50874561
accepted answer: http://stackoverflow.com/a/50874561
upvote count: 2
answer count: 1
tagged with: string
favorite count: 0
has comment: http://stackoverflow.com/comment/88750141

http://stackoverflow.com/a/50889877
type: Answer
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50889852
has body: Well each time you assign an empty list as value: data = open('file', 'r', encoding='utf8') for line in data: lang = line[:3] ipa_string = line[3:] lang_and_string_dict[lang] = [] lang_and_string_dict[lang].append(ipa_string) print(lang_and_string_dict) As a result, the old list containing the previous occurrence is lost. You should only create a list if no such element exists already, like: data = open('file', 'r', encoding='utf8') for line in data: lang = line[:3] ipa_string = line[3:] if lang not in lang_and_string_dict: lang_and_string_dict[lang] = [] lang_and_string_dict[lang].append(ipa_string) print(lang_and_string_dict) Since this pattern is rather common, you can use a defaultdict as well: from collection import defaultdict lang_and_string_dict = defaultdict(list) with open('file', 'r', encoding='utf8') as data: for line in data: lang = line[:3] ipa_string = line[3:] lang_and_string_dict[lang].append(ipa_string) print(lang_and_string_dict) A defaultdict is a subclass of dict that uses a factory (here list) in case a key is missing. So each time a key is queried that is not in the dictionary, we construct a list. You can later convert such defaultdict to a dict with dict(lang_and_string_dict). Furthermore if you open(..) files, you better do this with a with block. Since if an exception for example arises, then the file is still properly closed.
answers question: http://stackoverflow.com/q/50889852
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/89496091
comment on: http://stackoverflow.com/q/50935330
score: 0
type: Comment
type: QuestionComment
has text: Yes, please share it

http://stackoverflow.com/q/50875644
score: 0
has title: Can i find frequency of visit of stores using the information provided?
type: UnansweredQuestion
has body: I have a warehouse, which serves 100 stores. Each store has to be visited N times a month to fulfill its demand. i'e every day a Van V starts from the warehouse W , and cover n stores in a day(8 hours) and come back to warehouse I want to find the no. N , i'e how many times a store should be visited in a given month to fulfill its demand. I am gathering what information is needed for every store to calculate its frequency. I could come up with the following: Sale value of each store(monthly). i.e in this month a store will sell k items which will gain them the sale value s Total weight of the k items. Weight of the Truck Can this problem be solved by using knapsack algorithm? If yes, apart from the 3 points, is any other information required at store level? I have each store to store distance, also warehouse to store distance matrix available. Below shown is just the snapshot of the data i thought was required, and created a random dataset. Customer_code = store_code. PS . I am developing in python. Code to create random dataset: import pandas as pd import random from numpy.random import uniform my_randoms = random.sample(range(1000), 100) weights = random.sample(range(100), 100) df = pd.DataFrame({'customer_code':list(range(1,101)), 'latitude':uniform(24.74272,28.1234,100), 'longitude':uniform(46.1234,50.123445,100), 'sale_value':my_randoms, 'weights':weights})
tagged with: python
has comment: http://stackoverflow.com/comment/88754098
answer count: 0
tagged with: genetic-algorithm
type: Question
has comment: http://stackoverflow.com/comment/88762721
tagged with: algorithm

http://stackoverflow.com/comment/88959370
type: QuestionComment
comment on: http://stackoverflow.com/q/50969804
type: Comment
has text: Thank you @anishtain4 The link was really helpful. I found another solution. With `filling_values=0` I could fill the emty values with zero. Now it is working! :)
score: 0

http://stackoverflow.com/comment/89015482
score: 0
comment on: http://stackoverflow.com/q/50943043
type: QuestionComment
type: Comment
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/173715/discussion-between-veedrac-and-user136266).

http://stackoverflow.com/q/50879242
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/50879413
has body: I have a dataframe like this: A B C 1 10 121 5 6 122 7 8 123 9 10 124 12 23 125 10 24 1500 13 36 1600 By applying mean+/- 2std.deviation method to the column C, I wish to remove the outliers from C and filter the dataframe where I finally expect to get A B C 1 10 121 5 6 122 7 8 123 9 10 124 12 23 125 This is my code: target=df['C'] mean = target.mean() sd = target.std() lower_boundary = [x for x in target if (x &lt; mean - 2 * sd)] upper_boundary= [x for x in target if (x &gt; mean - 2 * sd)] selected_df=df[(target==lower_boundary) &amp; (target==upper_boundary)] selected_df But it shows TypeError: invalid type comparison error. Could you tell me where I make a mistake, please?
score: 0
possible better answer: http://stackoverflow.com/a/50879413
has answer: http://stackoverflow.com/a/50879492
tagged with: python
tagged with: outliers
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50879492
has title: Removing outlier from dataframe by filtering single column
tagged with: dataframe
tagged with: standard-deviation

http://stackoverflow.com/comment/88819543
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50884735
type: Comment
has text: Thank you! That was exactly, what I was looking for, guess I missed that part when I was reading the documentation.

http://stackoverflow.com/a/50875141
accepted answer of: http://stackoverflow.com/q/50874363
answers question: http://stackoverflow.com/q/50874363
type: AcceptedAnswer
score: 0
has comment: http://stackoverflow.com/comment/88754441
type: Answer
has body: I would recommend to use Python MSS. This library is intended exactly to take screenshots really fast. It is currently maintainable and cross-platform, and has good documentation.
has comment: http://stackoverflow.com/comment/88754279

http://stackoverflow.com/comment/88899451
comment on: http://stackoverflow.com/q/50950864
type: Comment
type: QuestionComment
has text: `{% url 'add_test' %}`
score: 0

http://stackoverflow.com/a/50981687
score: 1
has body: def sub(vec1, vec2): if len(vec1) != len(vec2): raise ValueError return [a - b for a, b in zip(vec1, vec2)]
answers question: http://stackoverflow.com/q/50981207
type: Answer
upvote count: 1
downvote count: 0

http://stackoverflow.com/a/50883100
type: Answer
accepted answer of: http://stackoverflow.com/q/50882063
answers question: http://stackoverflow.com/q/50882063
has comment: http://stackoverflow.com/comment/88772347
has body: BeautifulSoup is the de-facto standard library for parsing web pages in Python. It's great for sever-rendered or static content. It breaks down on sites that prevent web scraping, that dynamically update with client-side rendering, or that require cookies or authentication. So what do you use when BeautifulSoup doesn't cut it? Check out Cypress. It's Javascript-native, but it has backend adapters in work for Python, Node, Ruby, php, and .NET. Even without the adapters, Cypress is a powerful tool for e2e testing and browser automation that eliminates all the pain that comes with Selenium. If the information you're trying to scrape requires authentication, cookies, interaction, or is hampered by anti-bot code, give it a shot. If you already know about inspecting requests using your browser's dev tools you can stop reading here. Else... And finally, all this is assuming you've already inspected the network tab in your browser's dev tools to verify the data you're looking for isn't coming across XHR in an easily parseable format. If you haven't looked there yet, here are some Chrome instructions: Right click the page of interest -> Inspect -> Network -> Refresh page -> click xhr filter Then: Browse the response tab of each api call to see if the data of interest is hiding in plain sight. If the data you want is there, check the request tab to see whether your browser had to look at the request parameters you had to send to get it. If it's a simple GET request, chances are you can just copy that url straight into your browser and it'll be the data you want. If it's a POST, you can experiment with a tool like Servistate or Postman to see what sticks. I'd copy the request as it was in the browser identically, then pull stuff out or swap stuff in the POST body and in the other params to see how it works and what I can get away with. If it doesn't require you to have a cookie, you can get away with urllib in Python. If it does, just use Cypress, it'll save you time.
upvote count: 4
has comment: http://stackoverflow.com/comment/88768436
downvote count: 0
score: 4
type: AcceptedAnswer

http://stackoverflow.com/comment/88866428
type: Comment
has text: Is the process still running when it reportedly isn't updating any more? The first steps seems to be determining if this is an issue with your script/library or the shared network drive.
type: QuestionComment
comment on: http://stackoverflow.com/q/50933839
score: 1

http://stackoverflow.com/comment/88920914
comment on: http://stackoverflow.com/a/50955461
type: AnswerComment
score: 0
has text: Thanks!! would be part of anaconda?
type: Comment

http://stackoverflow.com/q/50947584
type: UnansweredQuestion
has body: I would like to create a new empty column and limit it to receive only numbers and double length. In general how do I make a limitation when creating new columns? for example to receive only binary? or to limit it to 250 characters? I have done these while creating databases with SQL but in pandas is new stuff. I am thinking that after you create a column you can pass something like this: df['col']='' # to create an empty column df['col'] = df['col'].astype('str') #to make it string after being filled or not but how to limit it to receive certain things like the ones mentioned above. If you can answer these it will help a lot.
upvote count: 1
type: Question
downvote count: 0
has title: Create new empty column and limit it to recieve certain data type and length of characters?
score: 1
favorite count: 0
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/88895170
answer count: 0

http://stackoverflow.com/comment/88873329
comment on: http://stackoverflow.com/q/50935495
score: 0
has text: Json added as requested
type: QuestionComment
type: Comment

http://stackoverflow.com/q/50950105
has comment: http://stackoverflow.com/comment/88899211
answer count: 2
has comment: http://stackoverflow.com/comment/88899095
has title: ImproperlyConfigured: Requested settings DATABASES
has comment: http://stackoverflow.com/comment/88899067
has comment: http://stackoverflow.com/comment/88899543
score: 0
has comment: http://stackoverflow.com/comment/88898753
has answer: http://stackoverflow.com/a/56145425
tagged with: python-3.x
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/88898263
has body: I have seen 10 different ways of configuring the MySQL database with Django, and none of them work. I am running MySQL 8.0 and Django 2.0 I updated the Project/settings.py with the database settings as followed: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'name_of_db', 'USER': 'root_user', 'PASSWORD': 'not_telling_u_my_pass_:)', 'HOST': 'localhost', 'PORT': '3306', } } When I run the command to test the connectivity: python manage.py dbshell I get error: django.core.exceptions.ImproperlyConfigured: Requested setting DATABASES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. No other settings have been made, however, I have tried to follow a few guides which say that I must declare: set DJANGO_SETTINGS_MODULE=mysite.settings I have also issued: python manage.py shell With no luck. I am running Windows 7 as well. I have all of the mysql dependencies installed for connecting from Python to MySQL. I know this question has been asked a number of times, but a thread should exist with clear instructions. Many of the other threads do not have clear and concise instructions, and I'm using a later version of MySQL so hopefully this will help solve others issues experiencing the same. Project Tree: Server | +-- Server | | | +-- _init_.py | +-- settings.py | +-- urls.py | +-- wsgi.py +-- manage.py Update 1 (10 mins after posting): I ran the python manage.py migrate and this installed all of the tables into my database schema. However, when I run the python manage.py dbshell command again, I still get the same error above saying the settings are not configured. Update 2: After running: python manage.py shell --settings=Server.settings I get: python manage.py dbshell CommandError: You appear not to have the 'mysql' program installed or on your path.
linked to: http://stackoverflow.com/q/15556499
has answer: http://stackoverflow.com/a/50950866
has comment: http://stackoverflow.com/comment/88898484
has comment: http://stackoverflow.com/comment/88899278
type: Question

http://stackoverflow.com/q/50971064
has comment: http://stackoverflow.com/comment/88940146
has comment: http://stackoverflow.com/comment/88938829
has body: I have a list which entries are numpy arrays (2D in this case). Example data: x=list([np.array([[1,2,3],[11,12,13],[111,112,113]]),np.array([[4,5,6],[14,15,16],[114,115,116],[1114,1115,1116]]),np.array([[11,12,13],[111,112,113]]),np.array([[7,8,9],[17,18,19],[117,118,119],[1117,1118,1119]])]) I want to execute functions on each column of each numpy array separate. Some functions have that axis command built in but some not e.g. MinMaxScaler. so far I created this list-comprehension: from sklearn.preprocessing import MinMaxScaler scaler = MinMaxScaler(feature_range=(0, 1)) Data=list() Data=[[(scaler.fit_transform(np.reshape(x[i][:,j],(-1,1)))) for j in range(x[i].shape[1])] for i in range(len(x))] The problem here is that the list comprehension creates a new list with one 1D- numpy array per iteration. I tried to use hstack and iterate over the list length. Data=list() L=list(range(len(x))) for k in range(len(x)): L[k]=np.zeros([x[k].shape[0],x[k].shape[1]]) Data=[[np.hstack((L[i],scaler.fit_transform(np.reshape(x[i][:,j],(-1,1))))) for j in range(x[i].shape[1])] for i in range(len(x))] But that works not at all. Of course, it stacks on top of the existing zeroes in L and it creates another list per iteration. Other initiations of L did not work even if that is not the main problem: L=list() #IndexError: list index out of range L=list(None)*len(x) #TypeError: 'NoneType' object is not iterable L=list(range(len(x))) #ValueError: all the input arrays must have same number of dimensions #...and others tried Does anyone have an idea how to solve this or do I have to do this with the classic for loops? Thanks for your help
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88939975
tagged with: python
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/88939341
has answer: http://stackoverflow.com/a/50986545
has title: Operation on 2D nd.array colums organized as a list
tagged with: list-comprehension
has answer: http://stackoverflow.com/a/50971437
has comment: http://stackoverflow.com/comment/88940071
score: 0
has comment: http://stackoverflow.com/comment/88939512
answer count: 3
has answer: http://stackoverflow.com/a/50973352

http://stackoverflow.com/q/50875192
favorite count: 0
tagged with: python
type: AnsweredQuestion
score: 6
type: Question
tagged with: feature-selection
linked to: http://stackoverflow.com/q/45346550
upvote count: 6
has body: I am trying to get a slightly modified version of the SelectKBest example to work but keep getting a ValueError("Unknown label type: %s" % repr(ys)) Here's my code: # Importing dependencies import numpy as np from sklearn.feature_selection import SelectKBest from sklearn.feature_selection import chi2 from sklearn.datasets import load_iris #The Example from: #http://scikit-learn.org/stable/modules/feature_selection.html#univariate-feature-selection iris = load_iris() X, Y = iris.data, iris.target print(X.shape, type(X), type(X[0,0])) print(Y.shape, type(Y), type(Y[0])) X_new = SelectKBest(chi2, k=2).fit_transform(X, Y) #My toyproblem: X = np.random.uniform(0,1, size=(5000, 10)) Y = np.random.uniform(0,1, size=(5000,)) #Type cast which might solve my problem by thi suggestion: # https://stackoverflow.com/questions/45346550/valueerror-unknown-label-type-unknown X=X.astype('float') Y=Y.astype('float') print(X.shape, type(X), type(X[0,0])) print(Y.shape, type(Y), type(Y[0])) X_new = SelectKBest(chi2, k=2).fit_transform(X, Y) The input data is shaped in exactly the same way, also input data types are almost the same: (150, 4) &lt;class 'numpy.ndarray'&gt; &lt;class 'numpy.float64'&gt; (150,) &lt;class 'numpy.ndarray'&gt; &lt;class 'numpy.int32'&gt; (5000, 10) &lt;class 'numpy.ndarray'&gt; &lt;class 'numpy.float64'&gt; (5000,) &lt;class 'numpy.ndarray'&gt; &lt;class 'numpy.float64'&gt; However my code crashes throwing the mentioned ValueError. Reading the SelectKBest Doc, the switch from classification to regression shouldn't really be a problem. Can someone help me find out what's going wrong? Traceback (most recent call last): File "featureSelection_toyproblem.py", line 26, in &lt;module&gt; X_new = SelectKBest(chi2, k=2).fit_transform(X, Y) File "C:\Users\mobrecht\AppData\Local\Continuum\anaconda3\envs\env_zipline\lib \site-packages\sklearn\base.py", line 520, in fit_transform return self.fit(X, y, **fit_params).transform(X) File "C:\Users\mobrecht\AppData\Local\Continu…
has answer: http://stackoverflow.com/a/50875389
accepted answer: http://stackoverflow.com/a/50875389
answer count: 1
downvote count: 0
tagged with: scikit-learn
has title: SelectKBest for regression gives "unknown label type"-error

http://stackoverflow.com/a/65103007
downvote count: 0
score: 1
has body: a = int(input("enter smaller no.")) b = int(input("enter larger no.")) for i in range (a,b+1): if i>1: for c in range(2,i): if i%c == 0: break else: print(i) In the code above we ran a for loop from minimum to the maximum number and storing the value in i for i in range (a,b+1): then we check that the number stored in i is greater than 1 or not as all numbers are divisible by 1 and we don not want to consider it. if i>1: after this we run another loop, this time from 2 to 1 less then the number stored in i for c in range(2,i): Now we check that the number stored in i is divisible by any of the number from 2 to 1 number less then itself. if i%c == 0: If yes then clearly it is not a prime number and we break the loop. break And if no we print the number. else: print(i)
answers question: http://stackoverflow.com/q/50905462
upvote count: 1
type: Answer

http://stackoverflow.com/q/50910736
score: 0
has body: I installed the API exactly as mentioned on this Tutorial and no error happened. but when I type: import gams on my ide (idle), the following error shows up: Traceback (most recent call last): File "&lt;pyshell#0&gt;", line 1, in &lt;module&gt; import gams File "C:\Users\Mansour\AppData\Local\Programs\Python\Python36-32\lib\site-packages\gams\__init__.py", line 8, in &lt;module&gt; from .workspace import * ImportError: DLL load failed: %1 is not a valid Win32 application. I'm using GAMS 25.0.2 and python 3.6.5 on windows 10. everything is 64-bit. p.s this is the log from cmd when installing the API: C:\GAMS\win64\25.0\apifiles\Python\api_36&gt;python setup.py install running install running build running build_py running install_lib running install_egg_info Removing C:\Users\Mansour\AppData\Local\Programs\Python\Python36-32\Lib\site-packages\gamsemb-0.0.0-py3.6.egg-info Writing C:\Users\Mansour\AppData\Local\Programs\Python\Python36-32\Lib\site-packages\gamsemb-0.0.0-py3.6.egg-info running install running build running build_py running install_lib running install_egg_info Removing C:\Users\Mansour\AppData\Local\Programs\Python\Python36-32\Lib\site-packages\gdxcc-7-py3.6.egg-info Writing C:\Users\Mansour\AppData\Local\Programs\Python\Python36-32\Lib\site-packages\gdxcc-7-py3.6.egg-info running install running build running build_py running install_lib running install_egg_info Removing C:\Users\Mansour\AppData\Local\Programs\Python\Python36-32\Lib\site-packages\gamsxcc-1-py3.6.egg-info Writing C:\Users\Mansour\AppData\Local\Programs\Python\Python36-32\Lib\site-packages\gamsxcc-1-py3.6.egg-info running install running build running build_py running install_lib running install_egg_info Removing C:\Users\Mansour\AppData\Local\Programs\Python\Python36-32\Lib\site-packages\dctmcc-1-py3.6.egg-info Writing C:\Users\Mansour\AppData\Local\Programs\Python\Python36-32\Lib\site-packages\dctmcc-1-py3.6.egg-info running install running build running build_py running install_lib run…
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has title: Installing GAMS API for Python not successful
has answer: http://stackoverflow.com/a/50924247
type: Question
tagged with: gams-math
tagged with: api
answer count: 1

http://stackoverflow.com/q/50866585
has comment: http://stackoverflow.com/comment/88735600
has answer: http://stackoverflow.com/a/50866718
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
tagged with: operators
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50866718
score: 1
upvote count: 1
type: Question
has title: Unexpected result with `in` operator chaining
has comment: http://stackoverflow.com/comment/88735561
has body: As far as I know, the in operator in Python can't be chained or at least I couldn't find any info on it, here is my problem Here is the code arr = [1, True, 'a', 2] print('a' in arr in arr) # prints False print(('a' in arr) in arr) # prints True What I don't understand is the first print, I know in the second the first in returns True and then it check if True is in arr, but what about the first one? Does it check if 'a' is in arr and then if arr is in arr?
has comment: http://stackoverflow.com/comment/88735626

http://stackoverflow.com/comment/88790409
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50895095
has text: AWS does not recomend object ACL: https://docs.aws.amazon.com/AmazonS3/latest/dev/access-policy-alternatives-guidelines.html Why not apply permissions at bucket/foilder level? All files in those folders should have similar permissions, right?

http://stackoverflow.com/q/50954770
tagged with: python
has body: So while using urllib I get this error, here is the full traceback: Traceback (most recent call last): File "C:\Users\user\Desktop\Dads project\Word search tool.py", line 148, in &lt;module&gt; print_absolute_counts(line.strip('\n'), 'english', smoothing=0, start_year=1799, end_year=1801) File "C:\Users\user\Desktop\project\Word search tool.py", line 43, in print_absolute_counts absolute_counts = retrieve_absolute_counts(token, corpus, smoothing, start_year, end_year) File "C:\Users\user\Desktop\Dads project\Word search tool.py", line 85, in retrieve_absolute_counts page = urllib.request.urlopen(urllib.request.Request(url)).read() File "C:\Users\user\AppData\Local\Programs\Python\Python37- 32\lib\urllib\request.py", line 222, in urlopen return opener.open(url, data, timeout) File "C:\Users\user\AppData\Local\Programs\Python\Python37- 32\lib\urllib\request.py", line 531, in open response = meth(req, response) File "C:\Users\user\AppData\Local\Programs\Python\Python37- 32\lib\urllib\request.py", line 641, in http_response 'http', request, response, code, msg, hdrs) File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 563, in error result = self._call_chain(*args) File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 503, in _call_chain result = func(*args) File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 755, in http_error_302 return self.parent.open(new, timeout=req.timeout) File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 531, in open response = meth(req, response) File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 641, in http_response 'http', request, response, code, msg, hdrs) File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 563, in error result = self._call_chain(*args) File "C:\Users\user\AppData\Local\Programs\Python\Python…
type: Question
tagged with: urllib
score: 0
answer count: 1
has title: Http Error 302 in python
has answer: http://stackoverflow.com/a/50954947
type: UnansweredQuestion

http://stackoverflow.com/comment/88921067
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50962162
type: Comment
has text: Tried a few ports ranging for 33 to 8000, seems to work on none. I used port 33 after some posts said it worked for them on that port.

http://stackoverflow.com/q/50955720
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90609686
has comment: http://stackoverflow.com/comment/93087643
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has title: Not able to read newly written image
tagged with: python
tagged with: object-detection
has body: I was actually trying to do read an image, do object detection on it and write a new image that has detected objects marked in it. A new image does indeed get saved in the working directory but I am unable to open it using cv2 or using any of the image displaying softwares on fedora. i tried uploading it to a photo uploading site and it displays properly. I did go through the stack overflow, they say the issue was regarding trying to read a png image using a jpeg reader and as per what i could understand i tried installing libpng but still does not work.Would be grateful if someone could help me with it. Here is the code I have tried: from imageai.Detection import ObjectDetection import os import cv2 execution_path = os.getcwd() detector = ObjectDetection() detector.setModelTypeAsRetinaNet() detector.setModelPath( os.path.join(execution_path , "resnet50_coco_best_v2.0.1.h5")) detector.loadModel() detections = detector.detectObjectsFromImage(input_image=os.path.join(execution_path , "car.jpg"), output_image_path=os.path.join(execution_path , "imagenew.jpg")) for eachObject in detections: print(eachObject["name"] + " : " + eachObject["percentage_probability"] ) print(cv2.imshow('detected',imagenew))
score: 2
answer count: 0
upvote count: 3

axes
tag name: axes
tags question: http://stackoverflow.com/q/51008008
type: Tag

tkinter-canvas
tags question: http://stackoverflow.com/q/50973137
type: Tag
tag name: tkinter-canvas
tags question: http://stackoverflow.com/q/50995790
tags question: http://stackoverflow.com/q/50947340

http://stackoverflow.com/a/50972337
answers question: http://stackoverflow.com/q/50971956
has body: It seemed you confuse two distinct procedures. A first way to complete your task is to build the html list before and then insert it within the whole html section: list_servers = ['boo', 'foo', 'bar'] # building the auxiliary string list items = ["\n {} ".format(s) for s in list_servers] items = "".join(items) # insert in the html html = """\ The file attached contains the servers. {0} """.format(items) The above method used the Python built-in .format function. It is valid for simple case as the one in the example. Yet, for more complex HTML construction, you may want to stick with jinja2 functionalities as indicated below: from jinja2 import Environment, BaseLoader # your template as a string variable html_template = """\ The file attached contains the servers. {% for server in servers %} {{ server }} {% endfor %} """ # jinja2 rendering template = Environment(loader=BaseLoader).from_string(html_template) template_vars = {"servers": list_servers ,} html_out = template.render(template_vars) print(html_out)
accepted answer of: http://stackoverflow.com/q/50971956
type: Answer
has comment: http://stackoverflow.com/comment/89050712
has comment: http://stackoverflow.com/comment/88941630
has comment: http://stackoverflow.com/comment/88973262
has comment: http://stackoverflow.com/comment/88970761
score: 2
has comment: http://stackoverflow.com/comment/88949514
downvote count: 0
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/a/50976908
upvote count: 4
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50976873
has comment: http://stackoverflow.com/comment/88950024
type: Answer
has body: With import pandas as pd df = pd.DataFrame({'CLIENT_ID': [51000222, 456]}) you can do df['CLIENT_ID'].astype(str).str[5:] 0 222 1 Name: CLIENT_ID, dtype: object Second row is used to show what happens with too short IDs
accepted answer of: http://stackoverflow.com/q/50976873
score: 4

http://stackoverflow.com/comment/89014950
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51010995
has text: @MartijnPieters I query all the tree at once, quering subtrees again are at least tens of queries in database; besides I'forced to use an ORM, so I don't have full control over the query.
score: 0

http://stackoverflow.com/comment/132302776
has text: @victorlin it's is important to note that this is intended to serialize mixed numpy and non numpy objects. Since it uses default, it should not fail if an item is not a numpy item. That is by design.
type: AnswerComment
comment on: http://stackoverflow.com/a/65151218
score: 0
type: Comment

http://stackoverflow.com/comment/88964775
type: QuestionComment
comment on: http://stackoverflow.com/q/50984397
has text: Exactly. Those are optimal values for the parameters of your `Gaussian` function.
score: 0
type: Comment

http://stackoverflow.com/a/50993354
upvote count: 7
has comment: http://stackoverflow.com/comment/88982619
has comment: http://stackoverflow.com/comment/88981371
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50992946
has body: This is how you do it: casted = K.cast(yPred,"int32")
type: Answer
answers question: http://stackoverflow.com/q/50992946
score: 7

http://stackoverflow.com/comment/88951016
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50977340
has text: The tuple contains about 241 lists of information that go into an excel spreadsheet. Using just `args=(dcf_data_tuple)` worked, however adding the `excelbtn_text` variable to the args seemed to break the tuple unpacking.
score: 0

min
tags question: http://stackoverflow.com/q/50887066
tags question: http://stackoverflow.com/q/50995690
tags question: http://stackoverflow.com/q/50901016
tag name: min
type: Tag

http://stackoverflow.com/comment/88884500
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50942785
has text: beautiful!!! thank you! I was missing the fact that "np.array(list(aset))" would give me the same result as "np.array([list(i) for i in x_set])". this was exactly what I was looking for.

http://stackoverflow.com/q/50993356
answer count: 1
favorite count: 0
tagged with: post-processing
has answer: http://stackoverflow.com/a/50996805
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
has title: Python - Assign slices to sparse matrix after multiprocessing
tagged with: slice
has body: I am currently working on a nonlocal method for image denoising and was asked to build a kernel, let's call it w, indexed by each pixel of an image. For context, if an image has NxM pixels, then the kernel (stored as a matrix) will have (NxM)^4 elements. Luckily, the matrix is sparse, symmetric, and its diagonal is known. So I designed a function win_largo(i,l), where i is the index of the i-th row of w and l is the number of elements I want to compute, this returns a CSR sparse row and its transpose. I have an image of 236^2pixels, so in my case l=1500 has enough information and I can compute the first 1500 rows and columns efficiently. However, there are 54 196 rows left. To compute them, I used the multiprocessing module like this: import multiprocessing as mp nm = N*M pool = mp.Pool(processes=15) results = [pool.apply_async(win_largo, args=(i,1500,) ) for i in xrange(1500, nm) ] pool.close() pool.join() I get a pretty quick calculation (couple minutes), that would instead take around 6.45 hours to compute. However, now I need to save this result. To do so, I wrote the following loop, where w is again stored as a CSR matrix: j = 0 for i in xrange(1500,nm): w[i,i-l:i], w[i-l:i, i] = results[j].get() j += 1 But it takes around 6.52 hours to complete. Is there a faster way to do this? Nowadays it seems like the multiprocessing loop is useless. I am using python 2.7 with macOS High Sierra.
tagged with: multiprocessing
type: Question
accepted answer: http://stackoverflow.com/a/50996805
downvote count: 0

http://stackoverflow.com/a/50891423
upvote count: 2
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/88783927
has body: While I cannot explain your error, you can use pd.DataFrame.applymap instead: out_df = in_df.applymap(mask_dict.get) This method should also be more efficient than pd.DataFrame.replace, which has a significant overhead when used with a dictionary. If you only need to replace values in a single series, you can use pd.Series.map: out_df = in_df.copy() out_df['Alphabets'] = out_df['Alphabets'].map(mask-dict) Related: Replace values in a pandas series via dictionary efficiently
has comment: http://stackoverflow.com/comment/88783849
answers question: http://stackoverflow.com/q/50891292
downvote count: 0

http://stackoverflow.com/comment/88784413
has text: What's your question?
comment on: http://stackoverflow.com/q/50891780
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/88827749
has text: Can you show `dulwich_ls_files` and `git_ls_files` so we can compare them?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50912696

http://stackoverflow.com/q/50973830
score: 0
has body: For example, the user will enter four colors (duplicates allowed) where orange = o, blue = b, green = g, red = r. I will assign values to each of these colors. dictColor = {"o": 4, "b": 2, "g": 7, "r": 5} colorScore = 0 for i in range(1): color = input("Enter 4 characters of colors: ") if "o" in color: colorScore += dictColor["o"] if "b" in color: colorScore += dictColor["b"] if "g" in color: colorScore += dictColor["g"] if "r" in color: colorScore += dictColor["r"] print("The color score is",colorScore) If the user were to enter in rbgo, the program works fine and outputs a value of 18. However, if the user entered one duplicate, such as rrgo, the program outputs 16, which is not the correct output. How would I make my program able to recognize these duplicates?
has comment: http://stackoverflow.com/comment/88943979
has comment: http://stackoverflow.com/comment/88949878
has comment: http://stackoverflow.com/comment/88944133
tagged with: python
has comment: http://stackoverflow.com/comment/88944018
accepted answer: http://stackoverflow.com/a/50973857
has title: Adding values from a dictionary in Python
has answer: http://stackoverflow.com/a/50973855
answer count: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50973857
has comment: http://stackoverflow.com/comment/88944148
type: Question
has answer: http://stackoverflow.com/a/50973978
has answer: http://stackoverflow.com/a/50973994
possible better answer: http://stackoverflow.com/a/50973855

http://stackoverflow.com/a/50923087
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50922923
upvote count: 2
has comment: http://stackoverflow.com/comment/88846256
has comment: http://stackoverflow.com/comment/88853396
has body: Multithreading gives you shared state of resources (variables). Instead of using globals, just pass in the buffer as an argument to your methods, and read/write from/to it. You still need to control access to the buffer resource, so both threads are not reading/writing at the same time. You can achieve that using Lock from the threading module: lock = threading.Lock() def cb_new(buffer_, lock_, message): print("New message") with lock_(): for m in message: #save data to buffer buffer.add(m) def is_buffer_ready(buffer_, lock_): print("Buffer state") with lock_(): if buffer_.ready(): #save buffer data to db Note that in case you are working with multiprocessing instead of threads, this solution won't work. By the way, as @abarnert commented, there are better mechanisms to check if the buffer is ready (has data to read / has free space to write) then calling a function that checks it. Check out select.select() which blocks you until the buffer is actually ready. When working with select, you put the calls inside a while True loop, and then you check if the buffer is ready for reading. You can start this function in a thread, passing a flag variable and the buffer. If you want to stop the thread, change the flag you passed to False. For the buffer object, use Queue.Queue() or similar datastructure. def read_select(flag, buff): flag = 1 while flag: r, _, _ = select.select([buff], [], []) if r: data = s.read(BUFFSIZE) # process data P.S - select also works with sockets. You can pass a socket object instead of a buffer, and it would check if the buffer on the socket is ready for read.
has comment: http://stackoverflow.com/comment/88863071
has comment: http://stackoverflow.com/comment/88862950
type: Answer

http://stackoverflow.com/q/50924752
downvote count: 0
score: 1
has title: POST method python - check status code
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/50927056
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/88848952
upvote count: 1
has body: I need help with the task. I have an automatic test that fills my form and adds an element after pressing the Save button. In my case, it adds the product to the store database. I have to check if I get the code 200 after pressing the SAVE button. POST has been sent well. My code: def methodPOST(auth, url, code, data): headers = {'charset': 'utf-8', 'Authorization': auth} response = requests.post(url, json=data, headers=headers) if not response.status_code == code: file = open("path", 'a') file.write(response.request.method) file.write("\n Code: " + str(response.status_code) + "\n expected: " +str(code)+"\n") file.write(str(response.reason) + "\n") file.close() I have a problem because I send the same again and then I check the code. I get the code 409[not 200], because I'm trying to add the same thing again. I can not check POST and its STATUS CODE when I press the SAVE button. How can I change my code? Thank you for help!
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50924951
has comment: http://stackoverflow.com/comment/88849018

http://stackoverflow.com/a/51061682
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50912166
answers question: http://stackoverflow.com/q/50912166
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: Following an advice to "just google it", I found an astropy-function - DAOStarFinder - that does what I was looking for. It scans an image for light-sources and one can set threshold for a detection, e.g. the "roundness", "sharpness" or brightness of an object have to be between [-0.05,0.05], [0.6,0.8] or >5*standard_deviation, respectively. I must say, that I have the impression the roundness and sharpness measure don't work consistently and sometimes values for the same object change enormously from one frame to the other. But DAOStarFinder gives you also a rough estimate of the flux density of the object, which I could use for sorting the sources and filtering out the relevant one. Here is a link to example script and to the documentation of DAOStarFinder. And here the example script explicitly: &gt;&gt;&gt; from astropy.stats import sigma_clipped_stats &gt;&gt;&gt; from photutils import datasets &gt;&gt;&gt; from photutils import DAOStarFinder &gt;&gt;&gt; hdu = datasets.load_star_image() &gt;&gt;&gt; data = hdu.data[0:400, 0:400] &gt;&gt;&gt; mean, median, std = sigma_clipped_stats(data, sigma=3.0, iters=5) &gt;&gt;&gt; daofind = DAOStarFinder(fwhm=3.0, threshold=5.*std) &gt;&gt;&gt; sources = daofind(data - median) &gt;&gt;&gt; print(sources)

http://stackoverflow.com/comment/88842788
has text: You are accessing the range incorrectly. You have to use slicing: `sheet[start_cell_: end_cell_]`. Not the colon instead of the comma you use.
comment on: http://stackoverflow.com/q/50919690
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88850695
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50925589
has text: Literally never heard that term used in the numpy community but it seems you aren't wrong. We just tend to call them boolean arrays / boolean index arrays.
type: AnswerComment

http://stackoverflow.com/q/50892557
has answer: http://stackoverflow.com/a/50892579
upvote count: 0
answer count: 1
favorite count: 0
has body: If I run this: import qrcode img = qrcode.make('Some data here') I don't know where it saves the actual image. I've tried CD'ing to a path and run the Python code, I have had the script in a directory. But when running the code above it doesn't create a QR image file in the directory. Where is it saved?! I've tried running qr "Some data here" &gt; test.png from the command-line which works perfectly. But not the module itself for some reason.
tagged with: python-3.x
type: UnansweredQuestion
score: -3
tagged with: python
has title: Python qrcode module not being saved
downvote count: 3
type: Question
has comment: http://stackoverflow.com/comment/88785729
tagged with: qr-code

http://stackoverflow.com/q/50981503
has body: I researched a lot on this, but I am not able to figure out what I am doing wrong. Please help!!! Objective of the program: Keep asking a question to choose an option to the user, until the user chooses the one in the list provided. Issue: I just can't get the not keyword working. Code Syntax: items = {'1': '2', '3': '4', '5': '6'} choice = input("Select your item: ") print(choice) for choice not in items: if choice in items: the_choice = items[choice] print("You chose",the_choice) break else: print("Uh oh, I don't know about that item") Error from eclipse: for not choice in items: ^ SyntaxError: invalid syntax
has title: Having issues with For loop in Python with a not key word
score: -1
has comment: http://stackoverflow.com/comment/88958476
tagged with: for-loop
has answer: http://stackoverflow.com/a/50981891
has answer: http://stackoverflow.com/a/50981572
upvote count: 0
possible better answer: http://stackoverflow.com/a/50981587
has comment: http://stackoverflow.com/comment/88958435
has answer: http://stackoverflow.com/a/50981587
favorite count: 0
has answer: http://stackoverflow.com/a/50981730
answer count: 5
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50981572
has answer: http://stackoverflow.com/a/50981746
tagged with: loops
downvote count: 1
type: Question

http://stackoverflow.com/comment/102150485
has text: Yes you want to logical-or this condition with whether the value is `NaN`
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50877468

http://stackoverflow.com/a/50946851
has comment: http://stackoverflow.com/comment/88894009
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/88900194
has comment: http://stackoverflow.com/comment/88893216
upvote count: 2
answers question: http://stackoverflow.com/q/50935663
type: Answer
has body: I think I understand your problem now. As far as I know, Django is really dependant on the User model; it can be a custom user model, but there has to be some sort of User model. When you build your own authentication backend, it still has to return User instances (or your custom User model instances). For example: File auth_backends.py from django.contrib.auth.models import User from .models import Loginteste class MyAuthBackend: def authenticate(self, request, username=None, password=None): if username is None or password is None: # nothing to do return None # get 'User' object try: usr = User.objects.get(username=username) except User.DoesNotExist: return None # get 'Loginteste' object try: loginteste = Loginteste.objects.get(username=username) except Loginteste.DoesNotExist: return None # authenticate user if not loginteste.check_password(password): # incorrect password return None return usr def get_user(self, pk): try: return User.objects.get(pk=pk) except User.DoesNotExist: pass return None File settings.py AUTHENTICATION_BACKENDS = [ 'project_config.auth_backends.MyAuthBackend', # 'django.contrib.auth.backends.ModelBackend', ] The only relatively simple option you might have is to use the model Loginteste as your custom user model. Everything else involves overriding a lot of Djangos code to make it work.
has comment: http://stackoverflow.com/comment/88893404

http://stackoverflow.com/q/50889026
tagged with: django
tagged with: python
has title: Creating a callable function to generate a value for an attribute in django models
tagged with: django-views
tagged with: django-models
type: Question
score: 0
answer count: 1
has body: I have a model A which has a models.PositiveIntegerField() value and I need to generate the value for this attribute using some information that I get from another related model B. class A(models.Model): .... num = models.PositiveIntegerField() .... def get_val(instance): return instance.a.num + 1 Class B(models.Model): ... a = models.ForeignKey(A, on_delete=models.CASCADE) val = models.PositiveIntegerField(default=get_val) ... But the mentioned approach is not working and is giving me this error while trying to do python manage.py migrate after doing python manage.py makemigrations TypeError: get_val() missing 1 required positional argument: 'instance' Error in detail: Applying problemsetting.0011_testcase_index...Traceback (most recent call last): File "manage.py", line 15, in &lt;module&gt; execute_from_command_line(sys.argv) File "/mnt/ebram96/workspace/linux/django_projects/env3/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/mnt/ebram96/workspace/linux/django_projects/env3/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/mnt/ebram96/workspace/linux/django_projects/env3/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/mnt/ebram96/workspace/linux/django_projects/env3/lib/python3.6/site-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/mnt/ebram96/workspace/linux/django_projects/env3/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 200, in handle fake_initial=fake_initial, File "/mnt/ebram96/workspace/linux/django_projects/env3/lib/python3.6/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/mnt/ebr…
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50889064

http://stackoverflow.com/a/50995856
type: Answer
accepted answer of: http://stackoverflow.com/q/50995707
has body: You need to build TensorFlow from source, the typical wheels that you install using pip were built with the requirement of using Compute Capability 3.5, but TensorFlow does indeed support Compute Capability 3.0: https://www.tensorflow.org/install/install_sources GPU card with CUDA Compute Capability 3.0 or higher. See NVIDIA documentation for a list of supported GPU cards. You can build the latest TF version as this will also auto-detect the capabilities of your CPU and should not use AVX.
downvote count: 2
type: AcceptedAnswer
upvote count: 6
score: 4
has comment: http://stackoverflow.com/comment/88986701
answers question: http://stackoverflow.com/q/50995707

http://stackoverflow.com/a/51002146
has body: According to this brilliant answer parsing HTML with Regex is never a good idea. You better use find_elements_by_css_selector or find_elements_by_xpath. Example with css selectors: for tag in browser.find_elements_by_css_selector('select[name=nouveau-num] option'): value = tag.get_attribute('value') text = tag.text
has comment: http://stackoverflow.com/comment/88998897
downvote count: 0
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/51001909

http://stackoverflow.com/comment/88953279
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50978627
has text: what version of wxPython are you using? it appears to exist at least as far back as 2.8
score: 0

http://stackoverflow.com/comment/88910463
score: 0
type: Comment
type: QuestionComment
has text: "that are saved in different folders" - do any of these overlap? Are the different threads ever going to be trying to save to the same files at the same time?
comment on: http://stackoverflow.com/q/50956201

http://stackoverflow.com/a/51010992
upvote count: 3
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51010940
type: Answer
has body: From the docs: This permission must only be applied to views that have a .queryset property set. So try to add queryset attribute to your RESTArticleList view: class RESTArticleList(APIView): queryset = Article.objects.filter(status='published') def get(self, request): articles = Article.objects.filter(status='published').all() serializer = ArticleSerializer(articles, many=True) return Response(serializer.data) def post(self): pass
score: 3
accepted answer of: http://stackoverflow.com/q/51010940

http://stackoverflow.com/a/50926886
score: 1
has body: For password change you can use this generic view using the inbuilt Django auth framework @login_required def change_password(request): if request.method == "POST": form = PasswordChangeForm(request.user, request.POST) if form.is_valid(): user = form.save() # Important to update the session otherwise user will have to login again update_session_auth_hash(request, user) # Server side alert print("Password changed for {0}".format(user.username)) return redirect('/index/') else: print(form.errors) else: form = PasswordChangeForm(request.user) return render(request, 'website/changepassword.html', {'form': form}) You need to use djangorestframework, and use the decorator @apiview(['GET', 'POST']) to create a RestAPI
answers question: http://stackoverflow.com/q/50926614
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/88852929
downvote count: 0

http://stackoverflow.com/comment/88820318
type: Comment
comment on: http://stackoverflow.com/a/50910005
has text: yes, i prefer you to not edit my program to make it more esely brutforceable, it's a bit like cheating
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88984618
comment on: http://stackoverflow.com/a/50994342
has text: @minion If you have neither nested parenthesis nor unbalanced ones this wouldn't be risky.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/50969366
has comment: http://stackoverflow.com/comment/88935108
has title: identifying the data type in python
answer count: 1
downvote count: 0
favorite count: 0
has body: What is the easiest way to find the data type of a variable? When I work with some image processing libraries, there are a lot of list and arrays. I'm aware of the following methods: clr = [np.uint8([[[0,255,0 ]]])] print type(clr) But this simply prints list, while I'm looking for a method to identify that its of type list of numpy array. I also know that the following can be done, for x in clr: print type(x) Is there some other easy method which I am overlooking?
tagged with: python
has comment: http://stackoverflow.com/comment/88937033
type: UnansweredQuestion
score: 1
has answer: http://stackoverflow.com/a/50969662
upvote count: 1
type: Question

http://stackoverflow.com/q/50877877
favorite count: 0
tagged with: python
score: -1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50878191
downvote count: 1
has body: I am trying to build an Action potential simulation (a graph of voltage relative to time, where the voltage values are obtained through numerically solving a couple of differential equiations). I have used the code from an online simulation of this in javaScript and am trying to translate it into python. However, due to the different ways in which python and java handle floats, I get an Overflowerror: math range error. Does anyone know how I can circumvent this in this specific situation? I am posting everything i've written and my error output: import numpy as np import math import matplotlib.pyplot as plt import random class HH(): def __init__(self): self.dt = 0.025 self.Capacitance = 1 self.GKMax = 36 self.GNaMax = 120 self.Gm = 0.3 self.EK = 12 self.ENa = 115 self.VRest = 10.613 self.V = 0 self.n = 0.32 self.m = 0.05 self.h = 0.60 self.INa = 0 self.IK = 0 self.Im = 0 self.Iinj = 0 self.tStop = 200 self.tInjStart = 25 self.tInjStop = 175 self.IDC = 0 self.IRand = 35 self.Itau = 1 @classmethod def alphaN(cls,V): if(V == 10): return alphaN(V+0.001) else: a = (10-V)/(100 * (math.exp((10-V)/10) -1)) print("alphaN: ", a) return a @classmethod def betaN(cls,V): a = 0.125*math.exp(-V/80) print("betaN: ", a) return a @classmethod def alphaM(cls, V): if (V == 25): return alphaM(V+0.0001) else: a = (25 - V)/10 * (math.exp( (25-V)/10) - 1) print("alphaM", a) return (a) @classmethod def betaM(cls, V): return 4 * math.exp(-V/18) @classmethod def alphaH(cls, V): return 0.07 * math.exp(-V/20) @classmethod def betaH(cls, V): return 1/(math.exp((30-V/10)+1)) def iteration(self): aN = self.alphaN(self.V) bN = self.betaN(self.V) aM = self.alphaM(self.V) bM = self.betaM(self.V) aH = self.alphaH(self.V) bH = self.betaH(self.V) tauN = 1/(aN + bN) print("tauN: ", tauN) tauM = 1/(aM + bM) print("tauM", tauM) tauH = 1/(aH + bH) print("tauH: ", tauH) nInf = aN * tauN print("nInf: ", nInf) mInf = aM * tauM print("mInf: ", mInf) hInf = aH * tauH print("hInf: ", hInf) self.n += self.dt/ tauN…
type: Question
has title: OverFlowError: math range error javaScript to python
has comment: http://stackoverflow.com/comment/88758382
has comment: http://stackoverflow.com/comment/88757841
has answer: http://stackoverflow.com/a/50878098
tagged with: numpy
answer count: 2
accepted answer: http://stackoverflow.com/a/50878191
upvote count: 0
possible better answer: http://stackoverflow.com/a/50878098

http://stackoverflow.com/comment/88866306
score: 1
comment on: http://stackoverflow.com/q/50933837
has text: One immediate issue in your code is that you're redefining run_attack just after getting user input for it.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50888138
has comment: http://stackoverflow.com/comment/88777769
type: Answer
has body: In interactive mode, the result of any expression-statement is printed only if it is not None. This behaviour is described in the doc. Expression statements are used (mostly interactively) to compute and write a value [...] In interactive mode, if the value is not None, it is converted to a string using the built-in repr() function and the resulting string is written to standard output The reason for that is that most functions that have side-effects return None. It would be annoying to have None spammed in the console. &gt;&gt;&gt; lst.append(1) None &gt;&gt;&gt; lst.append(2) None &gt;&gt;&gt; lst.append(3) None &gt;&gt;&gt; print('Please stop...') Please stop... None
score: 2
has comment: http://stackoverflow.com/comment/88777760
upvote count: 2
has comment: http://stackoverflow.com/comment/88777790
answers question: http://stackoverflow.com/q/50888091
downvote count: 0

http://stackoverflow.com/comment/131736228
type: AnswerComment
has text: When I use a non-trivial dataframe with values 0-0.2 the halving seems to break after some N rows. For example on a dataframe with 7 rows I notice the halving stops working around the 3-4th index.
score: 0
comment on: http://stackoverflow.com/a/50993341
type: Comment

http://stackoverflow.com/comment/88855147
comment on: http://stackoverflow.com/q/50921608
score: 0
type: Comment
type: QuestionComment
has text: @ascripter The django form is of category forms.Form and textarea is a charField(widget=forms.TextArea()) type. It's a big project so not desirable to show the complete template over here, but the logic is just rendering all the form fields in it. And this added javascript for the text box: bkLib.onDomLoaded(function() { new nicEditor({ iconsPath: "{% static 'website/js/nicEditorIcons.gif' %}", buttonList : ['fontSize','bold','italic','underline','strikeThrough','subscript','superscript','html','image', 'link', 'forecolor', 'bgcolor'] }).panelInstance('id_body'); });

http://stackoverflow.com/q/50880854
tagged with: django
tagged with: python
has body: MySQL 5.7.22 (but this happened with earlier versions) too. Happened with Django 1.8, now with Django 1.11, so wide range of MySQL and Django versions. class ShootFootAtMidnight(models.Model): time = models.TimeField(blank=True, null=True) time_source = models.ForeignKey(TimeSource) def save(self, *args, **kwargs): if self.time_source: self.time = self.time_source.time super(ShootFootAtMidnight, self).save(*args, **kwargs) Now, if there are a ton of these created around midnight time, sooner or later I'll face this: ValueError: hour must be in 0..23 Beware, because this is not a conventional models.DateTimeField but it's only the time part of that. This error never happened with me with DateTimeFields although the object has such (auto_now) as well. The models.TimeField has the type time in the MySQL DB (whereas DateTimeField has datetime and DateField has date. If I look at the database with MySQL prompt, I see the object is created honky and dory and has a time of 24:00:00. This value did not come from an auto_now field. Django actually created an object what it cannot read back (?!?!?). If I manually correct the time to 23:59:59 the ValueError: hour must be in 0..23 goes away, but how can I prevent this from happening? This is just my suspicion: is this a rounding issue on MySQL side? Maybe the Django framework supplies something like 23:59:59:99934. And if the time DB type's resolution is just 3 milliseconds, then it'll round it up to 24:00:00 without Django knowing it. But I was not able to prove that yet, I cannot find the exact resolution of the time but I feel it cannot be 6 fractional digits what Django displays sometimes. If this is the case I should maybe manually self.time = self.time_source.time.replace(microsecond=0) or something?
has comment: http://stackoverflow.com/comment/88766860
has comment: http://stackoverflow.com/comment/88764783
has comment: http://stackoverflow.com/comment/88787315
has comment: http://stackoverflow.com/comment/88766055
score: 1
tagged with: django-models
tagged with: mysql
has comment: http://stackoverflow.com/comment/88765293
type: Question
has comment: http://stackoverflow.com/comment/88766507
has comment: http://stackoverflow.com/comment/88766564
has comment: http://stackoverflow.com/comment/88765172
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88765452
has title: How to avoid MySQL + Django TimeField shooting itself in the foot at midnight?
answer count: 0
downvote count: 0
tagged with: time
type: UnansweredQuestion

http://stackoverflow.com/q/50872472
tagged with: python-3.x
type: Question
tagged with: python
upvote count: 2
answer count: 3
has answer: http://stackoverflow.com/a/50872496
downvote count: 1
has answer: http://stackoverflow.com/a/50873672
has title: Python3: remove a substring between two delimiting char
possible better answer: http://stackoverflow.com/a/50873672
tagged with: substring
accepted answer: http://stackoverflow.com/a/50872496
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50872621
has body: I am looking for a clean solution in Python3 to cut a substring out of a string (like an inline comment). However,if it is an odd number of seperators, then the rest of the text shall be removed (like a remark at the end of a programming line) input: s="abcd;efghij;kl;mn" output: s="abcdkl" How can this be done in a similar way like .replaceAll in Java
score: 1
favorite count: 0

http://stackoverflow.com/q/50901976
upvote count: 1
type: Question
has title: How to install certificate on Windows
has body: Trying to validate my certificate and getting the following error: failed to open CA file: No such process when I run in Python print(ssl.get_default_verify_paths()) Result: cafile: None, capath: None SSL_CERT_FILE AND SSL_CERT_DIR are shown, but how do i create a ca certificate containing this information in Windows?
tagged with: ssl-certificate
downvote count: 0
favorite count: 0
tagged with: windows
tagged with: python
answer count: 0
type: UnansweredQuestion
score: 1

http://stackoverflow.com/q/50949646
tagged with: python
accepted answer: http://stackoverflow.com/a/50949693
tagged with: python-3.x
upvote count: 2
has comment: http://stackoverflow.com/comment/88896883
downvote count: 1
tagged with: generator
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50949738
has answer: http://stackoverflow.com/a/50949738
has answer: http://stackoverflow.com/a/50949693
type: Question
has body: I have multiple generator functions that yield objects which are appended to a list. There's a lot of duplicated code, is there a possibility to minimize this (for Python 3.5+)? Generators: def gen1(obj): if obj == 'something': yield ValueError() def gen2(obj): if obj == 'else': yield ValueError() value_errors =[] Working version but duplicated code: for exc in gen1(obj): if isinstance(exc, ValueError): value_errors.append(exc) for exc in gen2(obj): if isinstance(exc, ValueError): value_errors.append(exc) Not working but no duplicated code: generators = [ gen1(obj), gen2(obj) ] for yielded in generators: if isInstance(yielded, ValueError): value_errors.append(yielded) ) This does not work because it yields generators not the generator's yielded value. Is it possible to fix this?
has answer: http://stackoverflow.com/a/50949803
linked to: http://stackoverflow.com/q/3211041
score: 1
favorite count: 0
has title: Iterate over multiple generators
has comment: http://stackoverflow.com/comment/88897075
duplicate of: http://stackoverflow.com/q/3211041
answer count: 3

http://stackoverflow.com/comment/88938466
type: Comment
type: QuestionComment
has text: Are you trying to sort these items on the percentage in the value, or the meaning of the key?
score: 1
comment on: http://stackoverflow.com/q/50970824

http://stackoverflow.com/q/50947776
type: Question
tagged with: numpy
upvote count: 9
has body: I'm attempting to plot two seaborn graphs side by side as other graphs (successfully) have done in previous questions, only difference I can see is that heatmaps seems to be throwing an issue. The code to produce the error is: import numpy as np; np.random.seed(0) import seaborn as sns uniform_data = np.random.rand(10, 12) uniform_data2 = np.random.rand(100, 120) fig, ax =plt.subplots(1,2) ax = sns.heatmap(uniform_data) ax = sns.heatmap(uniform_data2) Which produces the below
answer count: 2
accepted answer: http://stackoverflow.com/a/50947902
has title: plot two seaborn heatmap graphs side by side
score: 8
favorite count: 0
possible better answer: http://stackoverflow.com/a/50947912
tagged with: seaborn
has answer: http://stackoverflow.com/a/50947912
tagged with: python
tagged with: plot
tagged with: heatmap
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50947902
downvote count: 1

http://stackoverflow.com/q/50939977
score: 3
tagged with: http://stackoverflow.com/tag/json
upvote count: 3
tagged with: pandas
has body: I have a csv with one columns has '\0' value. I want to print it in json as \u0000 value. I used pandas read_csv and set the dtypes of the column as str to read the file. When I print it to json, it printed as \\0, which is \0 with the backslash escaped. How can I properly read it as NULL character and print it as unicode \u0000? This is the csv example id,data,timestamp 1,\0,2018-03-17 03:12:58 2,\0,2018-03-19 09:00:40 3,\0,2018-03-19 09:26:05 The output that I expect { "id": 1, "data": "\u0000", "timestamp":"2018-03-17T03:12:58.000Z"} { "id": 2, "data": "\u0000", "timestamp":"2018-03-19T09:00:40.000Z"} { "id": 3, "data": "\u0000", "timestamp":"2018-03-19T09:26:05.000Z"} How I read it using pandas csvfile = open('somefile.csv', 'r') col_names = ['id', 'data'] dtypes = { 'data': str } df = pd.read_csv(csvfile, names=col_names, dtype=dtypes) And how I write it to json jsonfile = open('somefile.json', 'w') df.to_json(jsonfile, orient='records', lines=True, date_format='iso')
answer count: 1
accepted answer: http://stackoverflow.com/a/50940239
favorite count: 0
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has title: Pandas read '\0' in CSV column as NULL character and print as Unicode in JSON
has comment: http://stackoverflow.com/comment/91962634
has answer: http://stackoverflow.com/a/50940239
has comment: http://stackoverflow.com/comment/91962768
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/88878109
type: Question

http://stackoverflow.com/comment/88718758
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50856208
has text: When I added your suggestion I get AttributeError: 'list' object has no attribute 'get' A trimmed down version of what I saved extraction is added above

http://stackoverflow.com/q/50873455
type: AnsweredQuestion
score: 2
has title: Multiple events in one TKinter control
accepted answer: http://stackoverflow.com/a/50876068
type: Question
downvote count: 0
has body: Consider the following minimal TKinter app: import tkinter as tki def do_something(*args): print('{} selected'.format(my_choice.get())) root_win = tki.Tk() option_list = ['apple', 'orange'] my_choice = tki.StringVar() my_choice.set('-- nothing selected --') script_list = tki.OptionMenu(root_win, my_choice, command=do_something, *option_list) script_list.pack(padx=20, pady=20) root_win.mainloop() The OptionMenu is initialised and "do_something" is executed as soon as the user makes a selection. So far so good. Now I want the option list to be refreshed every time the user clicks the OptionMenu: import tkinter as tki from random import randrange def do_something(*args): print('{} selected'.format(my_choice.get())) fruit = ['strawberry', 'banana', 'pineapple'] def get_new_choice(): if len(fruit) &gt; 0: new_fruit = fruit[randrange(len(fruit))] fruit.remove(new_fruit) return new_fruit else: return 'no more fruit' def refresh_option_list(*args): option_list.append(get_new_choice()) my_menu = my_om['menu'] my_menu.delete(0, "end") for option in option_list: my_menu.add_command(label=option, command = '') root_win = tki.Tk() option_list = ['apple', 'orange'] my_choice = tki.StringVar() my_choice.set('-- nothing selected --') my_om = tki.OptionMenu(root_win, my_choice, command=do_something, *option_list) my_om.bind('&lt;Button-1&gt;', refresh_option_list) my_om.pack(padx=20, pady=20) root_win.mainloop() The "refresh_option_list" is executed every time the contol is clicked and adds another option to the list. Which is nice. But what does not work any more is the "do_something" command, which is not executed any more. What am I doing wrong?
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50876068
tagged with: tkinter
upvote count: 2
tagged with: python

http://stackoverflow.com/comment/88946181
type: QuestionComment
has text: Shouldn't the list end in 10.3 or another increment of 0.1 instead of 10.255?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50975022

http://stackoverflow.com/q/50913856
has answer: http://stackoverflow.com/a/50914316
type: Question
downvote count: 0
answer count: 1
tagged with: python
score: 1
favorite count: 0
tagged with: args
tagged with: instance
tagged with: self
type: UnansweredQuestion
upvote count: 1
has title: Passing args from Instance Method to function using scipy optimize
has body: I have a class object like this with instance methods. class Neural: def __init__(self, params, X, y, lambda1): --- def costFunction(self): --- return J def backPropogate(self): --- return grad_back I am trying to call the functions using scipy.optimize.minimize result = opt.minimize(Neural(params_init, X, y, 1).costFunction(), x0=params_init, method='CG', jac=Neural(params_init, X, y, 1).backPropogate()) I keep on getting The truth value of an array with more than one element is ambiguous I have tried not calling the function with (), but I just get (this seems to me most correct): init() missing 1 required positional argument: 'lambda1' I have tried using args like this: result = opt.minimize(Neural.costFunction, x0=params_init, args=(X, y, 1), method='CG', jac=Neural.backPropogate) but the args parameter is recognized for the function of the class, not the object itself. If I call the functions instead like this Neural.costFunction(), I get missing positional requirement "self"
tagged with: scipy

http://stackoverflow.com/comment/88820059
score: 1
has text: I see, good! perhaps `i` could be renamed for readability, I have `starts` for a similar variable.
type: AnswerComment
comment on: http://stackoverflow.com/a/50909681
type: Comment

http://stackoverflow.com/q/50907540
has comment: http://stackoverflow.com/comment/88817731
has comment: http://stackoverflow.com/comment/88819903
tagged with: range
upvote count: 1
tagged with: python
tagged with: opencv
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/50912642
tagged with: image-processing
linked to: http://stackoverflow.com/q/43394437
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/88816994
has title: Convert RGB pixel values in a range to consecutive numbers
has comment: http://stackoverflow.com/comment/88817199
accepted answer: http://stackoverflow.com/a/50912642
has comment: http://stackoverflow.com/comment/88817146
has comment: http://stackoverflow.com/comment/88827565
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/88823634
has body: Guys I'm new to python and I'm stuck on this. Would really appreciate it if you could help me out. I've got an image that has a number of colours in each pixel. They all denote a number. The image was constructed using this range from 0 to 15625 pixels. Each of the pixels in the range from 0 to 15625 has a different colour and the above image was constructed using that. image range (it's massive so you might need to download it to see the image) What I'm trying to do is convert the RGB values from the range such as the first pixel value (5,5,5) to 1 and the next pixel value in the range to 2 and so on. Therefore, each pixel in the image above could correspond to a value. It's similar to this question but I don't think it does what I want to do. How to Convert all pixel values of an image to a certain range -python This is the code I used to create the range #!/usr/local/bin/python3 from PIL import Image import numpy as np # Create array to hold output image result=np.zeros([1,25*25*25,3],dtype=np.uint8) #change the values above i.e. 51*51*51 done by (upperbound-lowerbound)/step i.e (255-0)/5 j=0 for r in range(5,255,10): for g in range(5,255,10): for b in range(5,255,10): result[0,j]= (r,g,b) j+=1 # Convert output array to image and save im=Image.fromarray(result) im.save("perfect1.png") This is the code to find the RGB values of each pixel in the range from PIL import Image i = Image.open('perfect1.png') pixels = i.load() # this is not a list, nor is it list()'able width, height = i.size all_pixels = [] for x in range(width): for y in range(height): cpixel = pixels[x, y] all_pixels.append(cpixel) print all_pixels This is the code for creating a sub array with no extra pixel values as each "pixel" value in the image has a number of pixels enclosed. a = array of the image values rows_mask = np.insert(np.diff(a[:, 0]).astype(np.bool), 0, True) columns_mask = np.insert(np.diff(a[0]).astype(np.bool), 0, True) b = a[np.ix_(rows_mask, columns_mask)]
favorite count: 0

http://stackoverflow.com/q/50861252
tagged with: python
tagged with: dictionary
accepted answer: http://stackoverflow.com/a/50862951
possible better answer: http://stackoverflow.com/a/50862847
tagged with: list
has comment: http://stackoverflow.com/comment/88727726
score: 0
answer count: 2
has body: The above is a pandas dataframe. The values in col1 are sort of keys for values in col2 eg: In row 3, "-4" in col1 corresponds to list[12,23] in col2, similarly In row 3, "-2" in col1 corresponds to list[12] in col2. I'm looking to filter out only +ve values in col1 and their corresponding values in col2. I've tried multiple combinations of dict(zip(col1,col2)) to filter, but didn't work.. It would be really helpful, if someone can help me on this.
has answer: http://stackoverflow.com/a/50862951
type: AnsweredQuestion
has title: To filter rows from a list in a series in a dataframe in pandas
tagged with: series
type: Question
has answer: http://stackoverflow.com/a/50862847
tagged with: pandas

http://stackoverflow.com/a/50946584
has comment: http://stackoverflow.com/comment/88891035
score: 2
has comment: http://stackoverflow.com/comment/88890822
has comment: http://stackoverflow.com/comment/88890866
accepted answer of: http://stackoverflow.com/q/50946509
has body: You can't unpack an iterable of size one into two variables. Here's the minimal example for your problem. mystr = 'Store Location1: 8 SHENTON WAY #43-01 AXA TOWER Singapore' latitude, _ = mystr.split(',') # ValueError: not enough values to unpack (expected 2, got 1) Note there is no comma in your input string. Therefore, you need to refactor your logic or ensure your data upstream is appropriate. For example, if you want location to represent the first split only: latitude = mystr.split(', ', 1)[0]
answers question: http://stackoverflow.com/q/50946509
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88891138
has comment: http://stackoverflow.com/comment/88890601
has comment: http://stackoverflow.com/comment/88891184
has comment: http://stackoverflow.com/comment/88890966
upvote count: 2
has comment: http://stackoverflow.com/comment/88891115
type: Answer

http://stackoverflow.com/comment/89063022
type: QuestionComment
comment on: http://stackoverflow.com/q/50931168
score: 0
type: Comment
has text: f1_score function throws the error

http://stackoverflow.com/q/50991922
tagged with: webm
has title: Trimming and batch converting arbitrary video files to WebMs with python and ffmpeg
tagged with: video-encoding
score: 0
tagged with: python-3.x
tagged with: ffmpeg
type: UnansweredQuestion
tagged with: python
has body: I've got a whole lot of video files that I want to break up into multiple WebMs, each containing a trimmed portion of a specific video. I plan on having a csv file attached to each video file (having the same filename as the video) with a column structure similar to: Start Time | End Time | Rotation | Output Filename And I want to parse the csv files using python to execute ffmpeg, and I did a quick search and found the ffmpeg-python library and thought it might do the trick. The problem is, I don't know the first thing about ffmpeg or video encoding. I've tried reading through the ffmpeg documentation and trying to replicate stuff using ffmpeg-python but the furthest I can get is an output video of the same format as the input file, trimmed (but mpv still shows the duration as the duration of the original file but cuts off playback when the end of the trim is reached) and without audio. As a side note, I currently use a software named "WebM for Retards" (excuse the offensive title) which uses ffmpeg and I'm happy with its output but it's very tedious for my requirement. However I noticed that these are the arguments passed by using the software: -f nut -i pipe:0 -c:v libvpx -pix_fmt yuv420p -threads 8 -slices 4 -metadata title="This is a title" -ac 2 -c:a libvorbis -qmin 28 -crf 30 -qmax 32 -qcomp 1 -b:v 0 -qscale:a 3 -f webm -y "C:\Output.webm" I'd be happy if I could replicate output similar to what this provides. Thanks in advance for any help!
answer count: 0
has comment: http://stackoverflow.com/comment/88978924
type: Question
has comment: http://stackoverflow.com/comment/88978681

http://stackoverflow.com/q/50984288
accepted answer: http://stackoverflow.com/a/50984354
answer count: 1
tagged with: python
has body: I have a BaseClass and an AbstractClass that inherits from the BaseClass. This is the structure I have in place class BaseClass(object): def __init__(self, initialize=True): self.name = 'base_class' self.start = 0 if initialize: self.start = 100 class AbstractClass(BaseClass): def __init__(self): self.name = 'asbtract_class' super(BaseClass, self).__init__() I want to pass the abstract class an initialize parameter that gets transferred to the base class and if True sets the object's start value to 100. I tried using the super(BaseClass, self).__init__() but the abstract class gets no start attribute. I get an error when I try to access it. How can I pass a value the initialize argument to the AbstractClass and use the BaseClass's __init__ method to set the start attribute on the AbstractClass. The code I used best = BaseClass() abs = AbstractClass() abs.start # AttributeError: 'AbstractClass' object has no attribute 'start'
type: AnsweredQuestion
type: Question
tagged with: oop
has title: Extend Python class's init method
has comment: http://stackoverflow.com/comment/88963593
has comment: http://stackoverflow.com/comment/88963783
has answer: http://stackoverflow.com/a/50984354
score: 0

http://stackoverflow.com/a/71246226
answers question: http://stackoverflow.com/q/50999489
type: Answer
has body: This is outdated I understand, but if you have a command group, subcommand group, then a slash command you can have spaces in your commands when they are entered in discord.
score: 0

http://stackoverflow.com/comment/88796537
type: AnswerComment
type: Comment
score: 0
has text: @Charlotte: yes, it only works with ctypes. Builtin types (int, str, list, tuple, ...) don't support multiplication. Of course there might be other libraries that supports this feature, but this is not the case for builtin types.
comment on: http://stackoverflow.com/a/50890160

http://stackoverflow.com/comment/88983757
comment on: http://stackoverflow.com/q/50994328
has text: @UlrichEckhardt Thanks, I realize that (shared_ptr behaviour). My question was how to store/use such object for indexing. It seems id() is the part I was missing
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/88863023
has text: @JamesKPolk thanks. I get prime numbers to 1000000000, but I didn't find this sequence.
comment on: http://stackoverflow.com/q/50927619
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51001661
has title: Loading a database table with "slowly changing dimensions" in Python
linked to: http://stackoverflow.com/q/46039850
has comment: http://stackoverflow.com/comment/89245936
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/89176085
upvote count: 8
has comment: http://stackoverflow.com/comment/89269495
type: UnansweredQuestion
tagged with: python
has body: Ok, I can load records into a table using to_sql in pandas. (Unfortunately, I cannot use bcp or bulk insert, because my (SQL Server) database server is remote). How about a table with (Type 2) slowly changing dimensions? In SSIS, I would use SCD Wizard - what is the Python alternative? I would like to avoid coding up SCD logic from scratch - hopefully, there is a package (perhaps one of these) which does that? Simply loading a table is fine and dandy, but in the world of dimensional datamarts one surely has to support SCD?
answer count: 0
tagged with: scd
tagged with: etl
type: Question
has comment: http://stackoverflow.com/comment/89245958
tagged with: dimension
score: 8

http://stackoverflow.com/a/51325247
accepted answer of: http://stackoverflow.com/q/50931375
answers question: http://stackoverflow.com/q/50931375
score: 0
type: AcceptedAnswer
type: Answer
has body: I tried to connect Oracle database via SQLPLUS and I am calling the script with below way : os.environ['ORACLE_HOME'] = '&lt;ORACEL PATH&gt;' os.chdir('&lt;DIR NAME&gt;') VARIBALE=os.popen('./script_to_Call_sql_script.sh select.sql').read() My shell script: script_to_Call_sql_script.sh #!/bin/bash envFile=ENV_FILE_NAME envFilePath=&lt;LOACTION_OF_ENV&gt;${envFile} ORACLE_HOME=&lt;ORACLE PATH&gt; if $# -eq 0 then echo "USAGES: Please provide the positional parameter" echo "`$basename $0` &lt;SQL SCRIPT NAME&gt;" fi ECR=`$ORACLE_HOME/bin/sqlplus -s /@&lt;server_name&gt;&lt;&lt;EOF set pages 0 set head off set feed off @$1; exit EOF` echo $ECR Above things help me to do my work done on Production server.

http://stackoverflow.com/a/50971047
has comment: http://stackoverflow.com/comment/88939252
type: Answer
answers question: http://stackoverflow.com/q/50970795
score: 1
has body: For the function button_press to be able to print the button that clicked it, you need to pass in that button as a variable. So maybe the function definition for button_press should be something like def button_press(self, x, y): print("Button (%d,%d)" % (x,y)) And when you create the button, you could do something like self.buttons[y][x] = tx.Button(command = (lambda : self.button_press(x,y))) This means that when the button is clicked, it calls the lambda function, which calls button_press with the x and y of the button. Lambdas are pretty cool, and are definitely worth reading more about.
upvote count: 1
downvote count: 0

http://stackoverflow.com/comment/88762994
has text: Just be careful of TimeSeriesSplit() returns the indices as mentioned in the example
type: AnswerComment
comment on: http://stackoverflow.com/a/50880096
score: 0
type: Comment

http://stackoverflow.com/comment/88863036
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50932009
has text: No dependencies installed. When we try to "pip install sasl" we get the same issue.
score: 0

http://stackoverflow.com/a/50904355
type: AcceptedAnswer
upvote count: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/50904160
has body: In order to read the file you need to mount the filesystem first: sudo mkdir /media/data sudo mount /dev/sdb1 /media/data Afterwards you should be able to read the data using: with open('/media/data/file.txt','r') as input_file: for line in input_file: print(line) ...
answers question: http://stackoverflow.com/q/50904160
downvote count: 0
score: 2

http://stackoverflow.com/comment/88875165
comment on: http://stackoverflow.com/q/50938216
type: Comment
type: QuestionComment
has text: Can you just filter the subset of data before loading it into mysql? Something like `df[df['yearid']==2018].to_sql(...)`?
score: 0

http://stackoverflow.com/comment/88734504
type: QuestionComment
comment on: http://stackoverflow.com/q/50865953
has text: @MoxieBall It can be anywhere
score: 0
type: Comment

http://stackoverflow.com/comment/88872235
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50936686
score: 1
has text: Welcome to StackOverflow. Please read and follow the posting guidelines in the help documentation, as suggested when you created this account. [Minimal, complete, verifiable example](http://stackoverflow.com/help/mcve) applies here. We cannot effectively help you until you post your MCVE code and accurately describe the problem. We should be able to paste your posted code into a text file and reproduce the problem you described.

http://stackoverflow.com/a/50892566
has comment: http://stackoverflow.com/comment/88785781
has comment: http://stackoverflow.com/comment/88785819
accepted answer of: http://stackoverflow.com/q/50892550
answers question: http://stackoverflow.com/q/50892550
has comment: http://stackoverflow.com/comment/88785911
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88915161
has comment: http://stackoverflow.com/comment/88785725
has comment: http://stackoverflow.com/comment/88786456
downvote count: 0
has comment: http://stackoverflow.com/comment/88785752
has body: You can try lst = '\n'.join(' '.join(i) for i in txt) (Also, it is good to use variable name other than list): txt = [['This','is','here.'],['Second','sentence','here.']] with open(outfile, 'w') as newfile: lst = '\n'.join(' '.join(i) for i in txt) newfile.write(lst) Update: Looks like the the item in list has None, you can filter them as explained in other answer and use following: txt = [['This','is','here.'],['Second','sentence','here.'], ['Here',None, 'is']] lst = '\n'.join(' '.join(list(filter(None.__ne__, i))) for i in txt) print(lst) Result: This is here. Second sentence here. Here is As suggested in comments below, just adding additional timing results for comparing filter to list comprehension in this case, and list comprehension is faster: %%timeit txt = [['This','is','here.'],['Second','sentence','here.'], ['Here',None, 'is']] lst = '\n'.join(' '.join(list(filter(None.__ne__, i))) for i in txt) # Result: 100000 loops, best of 3: 4.52 µs per loop %%timeit txt = [['This','is','here.'],['Second','sentence','here.'], ['Here',None, 'is']] lst = '\n'.join(' '.join(([j for j in i if j != None])) for i in txt) # Result: 100000 loops, best of 3: 3.28 µs per loop
has comment: http://stackoverflow.com/comment/88798150
has comment: http://stackoverflow.com/comment/88786533
has comment: http://stackoverflow.com/comment/88785923
has comment: http://stackoverflow.com/comment/88785773
has comment: http://stackoverflow.com/comment/88786398
type: Answer
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/88839460

http://stackoverflow.com/q/50933912
downvote count: 0
tagged with: search
type: Question
answer count: 1
tagged with: replace
upvote count: 3
has title: Searching for text in html using python
has answer: http://stackoverflow.com/a/50934049
has body: I have an ebook reader that does not export highlighting annotations into an epub file, so I am to write a Sigil plugin to import annotations from the reader and put them into the epub file so that I can read it on my desktop computer. The naive way of doing this is using the replace method on strings in python: for html_id, href in bk.text_iter(): # read orignal html code from file original_html = bk.readfile(html_id) # modify html code modified_html = original_html.replace('Every issue that comes up', 'Every issue that comes up') There is a caveat here though: the string I look for might have been continuous text on the ebook reader but could contain html tags in the underlying html file. I guess it is not me who bumps to this problem first: is there a name and a method for searching with such constraints? It would be useful to get back a list of strings or positions in a file that in all add up to the original text. Example: Alfa Romeo Mercedes Volkswagen I have highlighted the list in the ebook reader, so I search for Alfa Romeo Mercedes Volkswagen and my search function would return a list with the positions in the html file so that I could add the span tags to each. Alfa Romeo Mercedes Volkswagen What is this type of search that allows inserted html tags and whitespace on the way? Is there a library routine for that in python?
tagged with: string
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 3

http://stackoverflow.com/comment/88761233
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.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50879438

http://stackoverflow.com/q/50995683
possible better answer: http://stackoverflow.com/a/50995746
downvote count: 0
tagged with: decorator
has answer: http://stackoverflow.com/a/50995746
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50997062
has title: Error when using staticmethod with flyweight decorator
tagged with: python
tagged with: python-decorators
tagged with: flyweight-pattern
type: AnsweredQuestion
has body: I have a class for making sprites flyweight and I am using a decorator to call this class. Here is some code: class flyweight: def __init__(self, cls): self._cls = cls self.__instances = dict() def __call__(self, title): return self.__instances.setdefault((title), self._cls(title)) In this question I'll just simplify the code to show what is relevant. @flyweight class Sprite: def __init__(self, title, surf=None): self.title = title self.surf = surf if surf is not None else pygame.image.load('Images/Sprites/'+title+'.png').convert_alpha() self.w, self.h = self.surf.get_size() @staticmethod def from_colour(colour, size=(40,40)): surf = pygame.Surface(size).convert(); surf.fill(colour) return Sprite(colour, surf) red = Sprite.from_colour((125,0,0)) But this gives me the error: AttributeError: 'flyweight' object has no attribute 'from_colour' Should I remodel my flyweight implementation or is there some way around this?
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/50997062
type: Question
answer count: 2

http://stackoverflow.com/a/50950851
has body: You are pretty close, here you go: import re from bs4 import BeautifulSoup html_doc = """ &lt;tr class="owner"&gt;&lt;td id="P184" class="ownerP" colspan="4"&gt;&lt;ul&gt; &lt;li&gt;&lt;span class="detailType"&gt;name:&lt;/span&gt;&lt;span class="detail"&gt;merry/span&gt;&lt;/li&gt; &lt;li&gt;&lt;a title="sendmessage" class="sendMessageLink" onclick="return openSendMessage('/sendMessage.php',20205" href="" tabindex="0"&gt;&lt;span&gt;&lt;/span&gt;sendmessage&lt;/a&gt;&amp;nbsp;&lt;span class="remark_soft"&gt;(by pm system)&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span class="detailType"&gt;phone 1&lt;/span&gt;&lt;a class="detail" href="tel:0387362531"&gt;0387362531&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;span class="detailType"&gt;&lt;/span&gt;&lt;/li&gt; &lt;/ul&gt;&lt;/td&gt;&lt;/tr&gt; """ soup = BeautifulSoup(html_doc, 'html.parser') for details in soup.find_all(attrs= {"class": "detail"}): if "href" in details.attrs and re.search("^tel:", details.attrs["href"]): print(details.text) Output: 0387362531 I'm simply looking through the details list you've made and if I find one that has and href and that href starts with tel: then print that value out.
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50950593
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50950593

angular-moment-picker
tags question: http://stackoverflow.com/q/50990178
type: Tag
tag name: angular-moment-picker

http://stackoverflow.com/comment/88985144
has text: I'm using Python 3.6 and plan on upgrading to 3.7 once all of the packages I use migrated as well. So in `__init__` I would call the `ete3.Tree` class?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50995225

http://stackoverflow.com/q/50974066
type: Question
linked to: http://stackoverflow.com/q/19001402
tagged with: javascript
tagged with: flask
has body: I have an HTML form that asks users for their emails, and a .txt file where the emails are stored line by line. How do I show on my website, a "counter", like so: "Join x number of people who already signed up!" Where x is an int that counts the number of emails in the .txt file? I am using flask for my web server, combined with HTML, CSS, and Javascript.
accepted answer: http://stackoverflow.com/a/50974181
score: 0
upvote count: 1
downvote count: 1
answer count: 1
tagged with: web
has answer: http://stackoverflow.com/a/50974181
favorite count: 0
has title: How to show how many people have signed up on my website?
duplicate of: http://stackoverflow.com/q/19001402
tagged with: python
has comment: http://stackoverflow.com/comment/88944537
type: AnsweredQuestion
tagged with: forms

http://stackoverflow.com/comment/89053354
comment on: http://stackoverflow.com/a/51011357
score: 0
type: AnswerComment
has text: I hope that my answer illuminated why the `SyntaxError: can't assign to function call` error came up
type: Comment

http://stackoverflow.com/comment/88940190
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/50957153
has text: @kinderchan as I said in the answer, **no**, you can't easily replace/delete part of a sequential file, because it is sequential.

http://stackoverflow.com/comment/88751147
comment on: http://stackoverflow.com/q/50874514
type: Comment
type: QuestionComment
score: 1
has text: @Chris_Rands: I modified the question, as it will be a primitve parser

http://stackoverflow.com/a/50856819
accepted answer of: http://stackoverflow.com/q/50856752
has body: I think you can assign to new column filtered by same boolean mask: from sklearn.preprocessing import StandardScaler mask = df['Col1'].notnull() df.loc[mask, 'Ref'] = StandardScaler().fit_transform(df.loc[mask, ['Col1']]) print (df) No Col1 Ref 0 12 10.0 -0.327089 1 23 NaN NaN 2 34 5.0 -1.027992 3 45 NaN NaN 4 54 22.0 1.355081 Detail: print (StandardScaler().fit_transform(df.loc[mask, ['Col1']])) [[-0.32708852] [-1.02799249] [ 1.35508101]]
answers question: http://stackoverflow.com/q/50856752
upvote count: 4
score: 4
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/q/50948608
type: Question
has comment: http://stackoverflow.com/comment/88898383
score: 0
has comment: http://stackoverflow.com/comment/88897940
tagged with: http-post
answer count: 1
has answer: http://stackoverflow.com/a/50950369
tagged with: http-get
tagged with: python
has body: I am trying to scrape data results (odds as per betfair starting price) of horse racing from site 'https://www.timeform.com/', but it seems that I am not logging well (my POST request isn't good) Any suggestions/proposals? My code: import requests url_get='https://www.timeform.com/horse-racing/result/brighton/2018-06-11/0200/6/1/phoenix-arts-club-fillies-handicap' url_post_pgin='https://www.timeform.com/horse-racing/account/handlelogin?returnUrl=%2Fhorse-racing%2F' payload = {"EmailAddress":"mymail@gmail.com","Password":"XXXXXXXXX","RememberMe":"true"} headers = {'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Encoding':'gzip, deflate, br', 'Accept-Language':'en-US,en;q=0.5', 'Connection':'keep-alive', 'Content-Length':'195', 'Content-Type':'application/x-www-form-urlencoded', 'DNT':1, 'Host':'www.timeform.com', 'Referer':'https://www.timeform.com/horse-racing/account/sign-in?returnUrl=%2Fhorse-racing%2F', 'Upgrade-Insecure-Requests':1, 'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:54.0) Gecko/20100101 Firefox/54.0'} s = requests.session() login = s.post(url=url_post_pgin,headers=headers, data=payload) #this should log me in, but I am afraid is not doing good job get_data=s.get(url=url_get,headers=headers, cookies=s.cookies) #file = open("rr.html", "w") #file.write(str(m.text)) #file.close() *EDIT: I changed url name variables.
has title: Python request POST (and Cookie) to login and after GET to scrape failed
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88897803
tagged with: session-cookies
tagged with: python-requests

http://stackoverflow.com/q/50858012
tagged with: setup.py
accepted answer: http://stackoverflow.com/a/50859582
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88718990
score: 1
upvote count: 1
type: Question
has title: inconsistent python package installation location with prefix
linked to: http://stackoverflow.com/q/122327
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/50859582
favorite count: 0
has body: I am installing python package with prefix, and getting a following error. $ python3 setup.py install --prefix=$HOME/some_prefix running install You are attempting to install a package to a directory that is not on PYTHONPATH and which Python does not read ".pth" files from. The installation directory you specified (via --install-dir, --prefix, or the distutils default setting) was: /home/user/some_prefix/lib64/python3.4/site-packages/ and your PYTHONPATH environment variable currently contains: '' Surely i can export PYTHONPATH=/home/user/some_prefix/lib64/python3.4/site-packages:$PYTHONPATH. But given that the path has python version, I found a fancy way from How do I find the location of my Python site-packages directory? $ python3 -c "import distutils.sysconfig as sc; print(sc.get_python_lib(prefix=\"$HOME/some_prefix\"));" /home/user/some_prefix/lib/python3.4/site-packages Unfortunately, they mismatch on lib part, apart from negligible trailing /. So it still fails. $ python3 setup.py install --prefix=$HOME/some_prefix running install You are attempting to install a package to a directory that is not on PYTHONPATH and which Python does not read ".pth" files from. The installation directory you specified (via --install-dir, --prefix, or the distutils default setting) was: /home/user/some_prefix/lib64/python3.4/site-packages/ and your PYTHONPATH environment variable currently contains: '/home/user/some_prefix/lib/python3.4/site-packages' Now, how can I properly match it? I checked the documentation, but I don't think there is a relevant arguments. https://docs.python.org/3/distutils/apiref.html#module-distutils.sysconfig distutils.sysconfig.get_python_lib([plat_specific[, standard_lib[, prefix]]])¶ $ python3 -c "import distutils.sysconfig as sc; print(sc.get_python_lib(\"A\", \"B\", \"C\"));" C/lib64/python3.4 Also, which one is right? is lib or lib64? I see more packages in /usr/lib. $ ll /usr/lib/python3.4/site-packages/ | wc 70 554 5408 $ ll /usr/lib64/python3…

https
tags question: http://stackoverflow.com/q/50899937
tags question: http://stackoverflow.com/q/50897837
tags question: http://stackoverflow.com/q/51001489
tags question: http://stackoverflow.com/q/50929322
type: Tag
tags question: http://stackoverflow.com/q/50959048
tag name: https

http://stackoverflow.com/q/50917432
has body: I am new to python and am having trouble getting my def simspin to print properly in the main. When I run the function in the shell with manual data inputs it returns the proper data, but when it prints through the main function it doesn't print complete data. Is there something I can do different for return in def simspin? from random import randrange from random import random def printintro(): **Removed for Purposes of this post** def inputvalues(): bankroll=int(input("Enter the number of dollars you start with:")) spins=int(input("Enter the number of spins you will play:")) bet=int(input("Enter how many dollars you will bet for each spin:")) print() return bankroll, spins, bet def betstyle():.....**Removed for purposes of this post.** def simspin(spins,placebet,bankroll,strategy,bet): wins=0 losses=0 spincount=0 endingbank=bankroll netwinnings=0 while spincount != spins and endingbank &gt;0: spincount=spincount+1 winningnumber=7 if strategy == 's' and placebet == winningnumber: wins=wins+1 endingbank=endingbank+(bet*35) netwinnings=netwinnings+bet*35 elif strategy == 'e' and placebet== winningnumber: wins=wins+1 endingbank=endingbank+bet+bet netwinnings=netwinnings+bet+bet elif strategy == 'd' and placebet== winningnumber: wins=wins+1 endingbank=endingbank+bet+(bet*2) netwinnings=netwinnings+bet+(bet*2) else: losses=losses+1 endingbank=endingbank-bet return wins,losses,spincount,endingbank,netwinnings def printResults(spincount, wins, losses, endingbank, netwinnings): winsperc=wins/spincount lossperc=losses/spincount print() print("After {0} spins".format(spincount)) print("Wins: {0} ({1}%)".format(wins,100*winsperc)) print("Losses: {0} ({1}%)".format(losses,100*lossperc)) print("Ending bank: ${0}".format(endingbank)) print("Net winnings: ${0}".format(netwinnings)) def main(): bankroll, spins, bet=inputvalues() printintro() strategy=placebet=betstyle() wins, losses, spincount, endingbank, netwinnings=simspin(spins,placebet,bankroll,strategy,bet) printResults(spin…
score: 0
has comment: http://stackoverflow.com/comment/88834933
has title: Using return in while loop doesn't print properly in main function
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88835872
answer count: 0
has comment: http://stackoverflow.com/comment/88835841
has comment: http://stackoverflow.com/comment/88835665
type: Question

http://stackoverflow.com/q/50894712
type: UnansweredQuestion
tagged with: web-scraping
tagged with: python
score: 1
has comment: http://stackoverflow.com/comment/88800983
has answer: http://stackoverflow.com/a/50912265
has title: Steps involved in sending a post request in Python to login to website
downvote count: 1
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/88817198
has comment: http://stackoverflow.com/comment/88789516
tagged with: http://stackoverflow.com/tag/html
has body: I've read tons of questions like this here but still haven't managed to solve my problem I'm trying to login to this website using Python but am not being able to. I've found the form I wanted to fill Email Address Pin Number Forgotten Your Pin? but am facing the following problems: Where can I find the link the form is POSTing to? (there is no action attribute) From the form, how can I create the payload? I've tried various things (with urllib, mechanize, and requests) but was now trying this import requests url = 'https://www.puregym.com/Login/' payload = {'email':'myusername', 'pin': 'mypin'} r = requests.post(url, params=payload) with open("requests_results.html", "w") as f: f.write(r.content) and the problem is always the same, it just returns the same page I was in. I figure this code is incorrect since I'm posting to the wrong url but again, I don't know where to find the correct one. I'd really like an explanation on how to break down this problem with actual python code if possible. EDIT: Inspecting the POST request with Chrome Developer Tools, I got Request URL: https://www.puregym.com/api/members/login/ Request Method: POST Status Code: 200 Remote Address: 123.45.57.89:123 Referrer Policy: no-referrer-when-downgrade Also, the payload is (replacing my credentials) associateAccount:"false" email:"myemail@email.com" pin:"1234567890" However, this code import requests # Fill in your details here to be posted to the login form. payload = {"associateAccount":"false", "email":"myemail@email.com", "pin":"1234567890"} LOGIN_URL = 'https://www.puregym.com/api/members/login/' # Use 'with' to ensure the session context is closed after use. with requests.Session() as s: p = s.post(LOGIN_URL, data=payload) # print the html returned or something more intelligent to see if it's a successful login page. print p.text # An authorised request. r = s.get('https://www.puregym.com/members/') print r.text just returns { "message": "An error has occurred." } EDIT 2: The current c…
favorite count: 0
upvote count: 2

http://stackoverflow.com/comment/89080441
type: Comment
has text: @Christopher What I was concerned about was how to do it reliably, but I think I've come up with a reasonable approach (in my head) since then: use App Engine Cron (scheduled minutely) to call a process that uses URL Fetch in a loop however many times per minute. Probably don't need to write to Cloud Storage; just persist directly in BigQuery. I'm hoping to try it out in the next few days and update, but any feedback over whether that seems reasonable is always welcome!
comment on: http://stackoverflow.com/q/50885739
score: 0
type: QuestionComment

http://stackoverflow.com/comment/93697588
type: Comment
has text: please provide the URLs to those pages.
comment on: http://stackoverflow.com/a/50882842
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89038764
comment on: http://stackoverflow.com/a/50999226
score: 0
type: AnswerComment
type: Comment
has text: Sorry meant to tag you @Rakesh

series
tag name: series
type: Tag
tags question: http://stackoverflow.com/q/50877281
tags question: http://stackoverflow.com/q/50944592
tags question: http://stackoverflow.com/q/50995942
tags question: http://stackoverflow.com/q/50896479
tags question: http://stackoverflow.com/q/50899676
tags question: http://stackoverflow.com/q/50867085
tags question: http://stackoverflow.com/q/51005760
tags question: http://stackoverflow.com/q/50988858
tags question: http://stackoverflow.com/q/50950638
tags question: http://stackoverflow.com/q/50988726
tags question: http://stackoverflow.com/q/50861252
tags question: http://stackoverflow.com/q/50965262
tags question: http://stackoverflow.com/q/50888819
tags question: http://stackoverflow.com/q/50958377
tags question: http://stackoverflow.com/q/50992000
tags question: http://stackoverflow.com/q/50993568
tags question: http://stackoverflow.com/q/50981383
tags question: http://stackoverflow.com/q/50965844
tags question: http://stackoverflow.com/q/50996642

http://stackoverflow.com/comment/88778328
comment on: http://stackoverflow.com/q/50888483
type: Comment
type: QuestionComment
score: 0
has text: If I understand RegEx correctly that would give me a list of the matching characters inside the string. Then I would need to compare the lengths of the original list of characters and the new list and if not matching then I'd need to discard. This works, but is probably too convoluted and it's likely that there's a better way.

http://stackoverflow.com/comment/88965128
has text: `propertie__value__gt=str(int(timestamp_from.total_seconds())), propertie__value__lt=str(int(timestamp_to.total_seconds())),` This is comparing `value` to a length of time in seconds. Are you sure `value` is the attribute you want to filter on?
comment on: http://stackoverflow.com/q/50984298
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89013915
score: 0
type: Comment
type: QuestionComment
has text: Nope Didn't work
comment on: http://stackoverflow.com/q/51010448

http://stackoverflow.com/q/50995225
type: Question
tagged with: inheritance
has comment: http://stackoverflow.com/comment/88985403
tagged with: class
linked to: http://stackoverflow.com/q/8853966
has comment: http://stackoverflow.com/comment/88985053
has comment: http://stackoverflow.com/comment/88985374
has answer: http://stackoverflow.com/a/50995466
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88985144
upvote count: 1
tagged with: python
tagged with: object
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50995466
tagged with: super
score: 1
has title: How to inherit all functionality of a parent class?
has body: I'm trying to inherit all of the functionality from ete3.Tree into my new class called TreeAugmented but not all of the methods and attributes are available? Is there something I am supposed to do in __init__ with super? It seems like with super you must specify individual attributes like in The inheritance of attributes using __init__. I could have another object in the class called tree where I store everything from ete3.Tree but I want to be able to use these objects with the functions in the ete3 package. Is there a way to just inherit everything from the parent class? import ete3 newick = "(((petal_width:0.098798,petal_length:0.098798):0.334371," "sepal_length:0.433169):1.171322,sepal_width:1.604490);" print(ete3.Tree(newick).children) # [Tree node '' (0x1296bf40), Tree node 'sepal_width' (0x1296bf0f)] class TreeAugmented(ete3.Tree): def __init__(self, name=None, new_attribute=None): self.name = name # This is an attribute in ete3 namespace self.new_attribute = new_attribute x = TreeAugmented(newick) x.children Traceback AttributeError Traceback (most recent call last) &lt;ipython-input-76-de3016b5fd1b&gt; in &lt;module&gt;() 9 10 x = TreeAugmented(newick) ---&gt; 11 x.children ~/anaconda/envs/python3/lib/python3.6/site-packages/ete3/coretype/tree.py in _get_children(self) 145 146 def _get_children(self): --&gt; 147 return self._children 148 def _set_children(self, value): 149 if type(value) == list and \ AttributeError: 'TreeAugmented' object has no attribute '_children'

http://stackoverflow.com/comment/89066374
comment on: http://stackoverflow.com/a/51026775
score: 0
type: AnswerComment
type: Comment
has text: Yes you are right, the class' been written in a funny way. Please check my answer again after the *edited* tag!

http://stackoverflow.com/q/50991972
tagged with: tensorflow
type: Question
has title: ImportError: cannot import name preprocessor_pb2
has comment: http://stackoverflow.com/comment/88989976
has comment: http://stackoverflow.com/comment/89059906
tagged with: google-cloud-python
has comment: http://stackoverflow.com/comment/92902022
has body: I have skimmed through the internet for a couple of days but found no working solution for this problem. I'm training an image dataset using the Tensorflow Object Detection API on the GCloud. My job keeps failing, citing this error. I have the latest protobuf version installed, I have performed this code as well (proposed as a soluiton in some cases): protoc object_detection/protos/*.proto --python_out=. I've done everything as instructed but my job keeps failing. This is the error log in detail: 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 "/root/.local/lib/python2.7/site- packages/object_detection/train.py", line 49, in &lt;module&gt; from object_detection import trainer File "/root/.local/lib/python2.7/site- packages/object_detection/trainer.py", line 27, in &lt;module&gt; from object_detection.builders import preprocessor_builder File "/root/.local/lib/python2.7/site- packages/object_detection/builders/preprocessor_builder.py", line 21, in &lt;module&gt; from object_detection.protos import preprocessor_pb2 ImportError: cannot import name preprocessor_pb2 Update: I performed the same procedure, with the same packages to train the data locally on my CPU and it worked without any errors. So maybe it is a problem with GCloud.
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/51253089
type: UnansweredQuestion
tagged with: python
tagged with: computer-vision
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/88991107

http://stackoverflow.com/comment/89618838
type: QuestionComment
comment on: http://stackoverflow.com/q/50923323
score: 0
has text: Can you provide a minimum code example so we can reproduce the error?
type: Comment

http://stackoverflow.com/comment/88725053
has text: post the expected output
comment on: http://stackoverflow.com/q/50861253
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/88761218
type: Comment
has text: Outside the loop )
type: AnswerComment
comment on: http://stackoverflow.com/a/50866928
score: 0

http://stackoverflow.com/comment/93892137
comment on: http://stackoverflow.com/a/51416900
type: AnswerComment
has text: That's not the correct way. Because the `__file__` const will always be a relative path to the entrance script (e.g. `script.py`) wherever and however you call the executable. The correct way is to use `sys.argv[0]` or `sys.executable`.
type: Comment
score: 2

http://stackoverflow.com/q/50921284
score: 0
has comment: http://stackoverflow.com/comment/88842017
tagged with: python
has comment: http://stackoverflow.com/comment/88872922
answer count: 0
type: UnansweredQuestion
has body: Is it possible to overwrite any past print statement in Python 3? For example, let's say our current output is: Hello! Planet! Earth! And now I want to overwrite the first line ("Hello!"), but not output a new line to do so. Is this possible? i.e. Awesome! Planet! Earth! Side note: My application is working in a Jupyter notebook, where this would be aesthetically pleasing. Thanks!
has title: Print over Previous Lines
type: Question

http://stackoverflow.com/a/50903772
downvote count: 0
type: Answer
upvote count: 1
has body: You can iterate df's columns and apply dropna Serieswise {col: df[col].dropna().values for col in df} Which yields {'AAA': array([4, 5, 6, 7]), 'BBB': array([], dtype=float64), 'CCC': array([ 100., -30.])} You can filter out empty arrays such as 'BBB' with {key: val for key, val in ddict.items() if val}
score: 1
answers question: http://stackoverflow.com/q/50903622

http://stackoverflow.com/a/50962622
type: Answer
answers question: http://stackoverflow.com/q/50948937
accepted answer of: http://stackoverflow.com/q/50948937
type: AcceptedAnswer
has body: Yes, that "Multiplicand" you see in the xml is the input you can edit via the gui. You can create and edit Choregraphe boxes entirely through the GUI, editing their inputs, outputs and parameters; I recommend doing that instead of touching the XML; because the exact format used in the .xar file may change in future versions. I have used Choregraphe quite a bit and have never felt the need to directly edit the .xar (except maybe when resolving git conflicts, but that was years ago and since then we've been avoiding having to ever merge a .xar file).
score: 0

http://stackoverflow.com/q/50953575
favorite count: 0
has comment: http://stackoverflow.com/comment/88914997
type: UnansweredQuestion
tagged with: python
downvote count: 1
tagged with: virtual-environment
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/139125400
type: Question
score: 5
answer count: 1
has body: I want to use tensorflow through a virtual environment. However, the Python script I want to run requires me to use a separate virtual environment that does not include tensorflow. Is it possible to activate these simultaneously? If not, can I merge the two virtual environments somehow?
has answer: http://stackoverflow.com/a/50953934
upvote count: 6
has title: Can you activate multiple Python virtual environments at once?

http://stackoverflow.com/a/50904735
has comment: http://stackoverflow.com/comment/88883783
has body: First step detect big root, by user select or big erosion. Second step base on previous big area center coordinate, make a fill algorithm (like Paint Bucket Tool in Paint) on this original threshold image
score: 0
has comment: http://stackoverflow.com/comment/88829499
answers question: http://stackoverflow.com/q/50883330
type: Answer

http://stackoverflow.com/q/50933895
tagged with: python
has comment: http://stackoverflow.com/comment/88866767
has answer: http://stackoverflow.com/a/50933987
type: AnsweredQuestion
tagged with: list
upvote count: 2
score: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/88866805
type: Question
tagged with: naivebayes
tagged with: text-processing
accepted answer: http://stackoverflow.com/a/50933987
has comment: http://stackoverflow.com/comment/88867259
has title: Replace double quotations with brackets in a Python List of Strings
has body: This is the format of my List currently: ["'There's no going back', 'pop'", "'Mark my words', 'pop'", "'This love will make you levitate', 'pop'", "'Like a bird, like a bird without a cage', 'pop'"] I want to convert it to the following format: [('There\'s no going back', 'pop'), ('Mark my words', 'pop'), ('This love will make you levitate', 'pop'), ('Like a bird, like a bird without a cage', 'pop')] So I need to tokenize the input strings into tuples. But I'm not sure how can this be done since the "" are present as it is primarily a String. If additional context is required, I'm scraping a large chunk of data in the above mentioned format and to process it with a Naive Bayes Classifier I need it in the bracket format. I'm open to try a different approach if it's more efficient.
has comment: http://stackoverflow.com/comment/88867299
has comment: http://stackoverflow.com/comment/88866824
has comment: http://stackoverflow.com/comment/88866889
answer count: 1
has comment: http://stackoverflow.com/comment/88866398
tagged with: string
favorite count: 0

http://stackoverflow.com/comment/88939520
type: Comment
has text: when you say default version, why is it that a bash script has a different default version than the command line? Running python stack.py from the command line, runs python 3, and running python --version outputs python 3.5.2
comment on: http://stackoverflow.com/a/50970560
type: AnswerComment
score: 0

http://stackoverflow.com/q/50994832
tagged with: flask
favorite count: 0
has answer: http://stackoverflow.com/a/50994930
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has title: In Flask, how can I pass a variable from template to Python?
type: AnsweredQuestion
has body: I have a list of profile name. When users click on one of the profile name, the application will load all the details of the profile. I also have a mySQL table on a database. For example, if I have the following: Michael John Emily The names of these three people, are the primary key of the mySQL data, I need to pass the name to Python in order to load the profile. I know how to get name using "onclick()" in JavaScript. However, I have struggle on passing the variable from either HTML or JavaScript to Python. The following code is a snippet of my "apprunner.py": app = Flask(__name__) @app.route("/") def index(): return render_template("index.html") if __name__ == "__main__": app.run(debug=True) Assume that"li" is on the "index.html". How can I pass the name of the profile to "apprunner.py" as a variable? So that I can use the variable as a primary key to find the tuple in the database.
has comment: http://stackoverflow.com/comment/88984380
upvote count: 1
downvote count: 1
accepted answer: http://stackoverflow.com/a/50994930
type: Question
tagged with: web-development-server
score: 0
answer count: 1
tagged with: javascript

http://stackoverflow.com/a/50965764
has comment: http://stackoverflow.com/comment/88928178
has body: In shapefiles, a country/province/whatever, may be broken down into several line segments. Why that is, I don't know, but in order to plot the shape correctly, you need to use all the necessary segments. Actually, in the Basemap documentation for shapefiles there is an example under 'filling polygons', how to do this correctly. I adapted their example to your use case. It's probably not the most optimal solution, but it seems to work. import pandas as pd import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap from matplotlib import patches as mpatches from matplotlib import cm from numpy import linspace import matplotlib.patches as mpatches from matplotlib.collections import PatchCollection fig, ax = plt.subplots(figsize=(4,8)) # create the map map = Basemap(resolution='l', # c, l, i, h, f or None projection='merc', lat_0=15.95, lon_0=105.85, llcrnrlon=102., llcrnrlat= 8.31, urcrnrlon=109.69, urcrnrlat=23.61) # load the shapefile, use the name 'states' map.readshapefile(r'shapefiles/gadm36_VNM_1', name='states', drawbounds=True) # shapefile downloaded from http://www.gadm.org/ # collect the state names from the shapefile attributes so we can # look up the shape obect for a state by it's name state_names = [] for shape_dict in map.states_info: state_names.append(shape_dict['VARNAME_1']) ax = plt.gca() # get current axes instance # NOR, CEN, SOU and MEK are some subdivisions I have created for the states of Vietnam NOR = ['Lai Chau', 'Lao Cai', 'Ha Giang', 'Cao Bang', 'Dien Bien', 'Son La', 'Yen Bai', 'Tuyen Quang', 'Bac Kan', 'Lang Son', 'Thai Nguyen', 'Phu Tho', 'Vinh Phuc', 'Hoa Binh', 'Ha Noi', 'Bac Ninh', 'Hai Duong', 'Hung Yen', 'Ha Nam', 'Quang Ninh', 'Hai Phong', 'Thai Binh', 'Nam Dinh', 'Bac Giang', 'Ninh Binh'] CEN = ['Thanh Hoa', 'Nghe An', 'Ha Tinh', 'Quang Binh', 'Quang Tri', 'Thua Thien Hue', 'Da Nang'] SOU = ['Quang Nam', 'Kon Tum', 'Quang Ngai', 'Gia Lai', 'Binh Dinh', 'Dak Lak', 'Phu Yen', 'Khanh Hoa', 'Dak Nong', 'Lam Dong', 'Ninh Th…
score: 2
answers question: http://stackoverflow.com/q/50928942
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50928942
upvote count: 2
type: Answer

http://stackoverflow.com/comment/89008741
has text: Which version of doxygen are you using? I do see documentation of both functions though the argument in case of `a:int` is not handled properly in doxygen.
type: Comment
comment on: http://stackoverflow.com/q/51002584
score: 0
type: QuestionComment

http://stackoverflow.com/a/50975690
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88966531
type: Answer
answers question: http://stackoverflow.com/q/50975012
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50975012
has comment: http://stackoverflow.com/comment/88964757
has comment: http://stackoverflow.com/comment/89008515
has comment: http://stackoverflow.com/comment/88982458
has body: How can I modify what I am doing in order to be able to yield from multiple coroutines in parallel? You need a function that merges two async sequences into one, iterating over both in parallel and yielding elements from one or the other, as they become available. While such a function is not included in the current standard library, you can find one in the aiostream package. You can also write your own merge function, as shown in this answer: async def merge(*iterables): iter_next = {it.__aiter__(): None for it in iterables} while iter_next: for it, it_next in iter_next.items(): if it_next is None: fut = asyncio.ensure_future(it.__anext__()) fut._orig_iter = it iter_next[it] = fut done, _ = await asyncio.wait(iter_next.values(), return_when=asyncio.FIRST_COMPLETED) for fut in done: iter_next[fut._orig_iter] = None try: ret = fut.result() except StopAsyncIteration: del iter_next[fut._orig_iter] continue yield ret Using that function, the loop would look like this: async for batch in merge(downloader.fetch(url1), downloader.fetch(url2)): ....
upvote count: 2

http://stackoverflow.com/comment/88899732
type: QuestionComment
comment on: http://stackoverflow.com/q/50950749
has text: @TylerMarques I know I should but it's a really really long code.. I didn't write "print (something)"
type: Comment
score: 0

http://stackoverflow.com/q/50904510
tagged with: python
has answer: http://stackoverflow.com/a/50904769
type: AnsweredQuestion
score: 2
has title: Categorical variables into multiple columns (2)
possible better answer: http://stackoverflow.com/a/50904769
type: Question
tagged with: numpy
answer count: 2
downvote count: 0
has body: I have a dataframe with a categorical variable Segment ID Segment Var1 Var2 Var3 1 AAA 1 1 1 2 BBB 1 0 1 3 BBB 1 1 1 4 AAA 0 1 1 5 CCC 0 1 1 6 AAA 0 0 1 7 AAA 0 1 1 8 AAA 1 0 1 9 BBB 1 0 1 10 CCC 1 0 1 And I would like to transform a column Segment into 3 categories for each variable like this: ID Var1_AAA Var1_BBB Var1_CCC Var2_AAA Var2_BBB Var2_CC Var3_AAA Var3_BBB Var3_CCC 1 1 null null 1 null null 1 null null 2 null 1 null null 0 null null 1 null 3 null 1 null null 1 null null 1 null 4 0 null null 1 null null 1 null null 5 null null 0 null null 1 null null 1 6 0 null null 0 null null 1 null null 7 0 null null 1 null null 1 null null 8 1 null null 0 null null 1 null null 9 null 1 null null 0 null null 1 null 10 null null 1 null null 0 null null 1 Could you please help me with that?
tagged with: pandas
has answer: http://stackoverflow.com/a/50904629
favorite count: 0
accepted answer: http://stackoverflow.com/a/50904629
upvote count: 2

http://stackoverflow.com/comment/88766957
score: 1
comment on: http://stackoverflow.com/q/50882246
type: Comment
type: QuestionComment
has text: use a library like `pypika`

http://stackoverflow.com/comment/88869443
has text: just a comment, 'days_missing' is 0 or 1 for the first row? (you used 0 the first time and 1 the second tine)
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50935098

http://stackoverflow.com/q/50913339
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/88832030
answer count: 1
has answer: http://stackoverflow.com/a/50913974
favorite count: 0
has title: How to crop area from mask in cv2 python
linked to: http://stackoverflow.com/q/41919319
upvote count: 1
tagged with: python
tagged with: opencv
type: AnsweredQuestion
has body: I have videos of black screen and a white ball I want to track the centre of the white ball in every frame (output as x, y co-ordinate). So my attempt is to use cv2.HoughCircles but no matter how I tuned the parameter, I won't get 100% tracking. So I have another idea. Because when average every pixel of circle shape will get the centre point of the circle. I decided to try on that idea. But looping every pixel until we found the white isn't feasible. Is there any way to crop (roughly) to get only white circle pixel? (For example, I have image resolution of 1920x1080 but the ball's size won't exceed 50x50 pixel. So it would be too slow to process it in python. So is there a way to crop a region in an image to 50x50 in size?)
has comment: http://stackoverflow.com/comment/88826919
score: 1
accepted answer: http://stackoverflow.com/a/50913974
tagged with: image

http://stackoverflow.com/comment/88864014
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50932527
has text: What is `run.py`? There is indeed no name `main` in your `app` module, so that is expected.

http://stackoverflow.com/comment/88871787
type: QuestionComment
score: 1
has text: There's no way to run arbitrary code absolutely safely. But there are all kinds of techniques to reduce the exposure. Instead of directly `exec`ing it in your process, you can run it as a child process. You can put that child process in a chroot jail, and run it as a limited user. You can even run it in an isolated container/virtual machine that has no connection with your real machine except stdin/stdout pipes. Or you can build an interpreter (or modify an existing one like CPython) that doesn't allow anything dangerous. And so on.
comment on: http://stackoverflow.com/q/50936538
type: Comment

http://stackoverflow.com/comment/88895761
type: Comment
comment on: http://stackoverflow.com/a/50941600
has text: @ShawnSchreier : No problem mate.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/88979592
type: QuestionComment
has text: Possible duplicate of ['module' object has no attribute 'PortScanner'](https://stackoverflow.com/questions/14913153/module-object-has-no-attribute-portscanner)
score: 1
comment on: http://stackoverflow.com/q/50992325
type: Comment

http://stackoverflow.com/comment/88737662
comment on: http://stackoverflow.com/a/50867726
type: AnswerComment
score: 0
type: Comment
has text: @user3630844: That's a different question...and I suggest you search for existing answers here on SO before asking it because I'm fairly sure it's been answer (so would get marked a duplicate). Doing it with `exec()` would **not** be considered a good approach...I would suggest using `getattr()` with the name given to the imported module.

http://stackoverflow.com/comment/88945709
type: QuestionComment
has text: You're just looking for the string of a date. Try `[str(datetime.date(2018, 6, 22))]`
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50974761

http://stackoverflow.com/comment/88883947
has text: On which like?What is the error?
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50943277

http://stackoverflow.com/q/50941855
has comment: http://stackoverflow.com/comment/88892004
has body: I'm new to pyQt4 and i need to create GUI using pyQt4 and python 3.5. I have long process which does not have exact time duration to be executed. time duration is varying according to the inputs that I use in the process at each time. There are examples about adding progress bars by using timers.but in my case i don't know the exact time duration. I need to complete a progress bar according to the time taken by the process.as in the my code this process is methodtobeexecute(). could someone help me out to resolve this problem with a code example with a explanation. Thanks in advance.... this is my code and so far it completes the progress bar using QTimer.but what i want is complete the progress bar meanwhile the methodtobeexecute() method finishes its tasks.(QTimer has used only for check the progrss bar here) # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'pro2.ui' # # Created by: PyQt4 UI code generator 4.11.4 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui import sys try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig) class Ui_Form(QtGui.QWidget): def __init__(self): QtGui.QWidget.__init__(self) self.setupUi(self) def setupUi(self, Form): Form.setObjectName(_fromUtf8("Form")) Form.resize(400, 300) self.progressBar = QtGui.QProgressBar(Form) self.progressBar.setGeometry(QtCore.QRect(160, 60, 118, 23)) self.progressBar.setProperty("value", 24) self.progressBar.setObjectName(_fromUtf8("progressBar")) self.pushButton = QtGui.QPushButton(Form) self.pushButton.setGeometry(QtCore.QRect(170, 140, 75, 23)) self.pushButton.setObjectName(_fromUtf8("pushButton")) # # restarts the 'QPro…
has comment: http://stackoverflow.com/comment/88883189
tagged with: qprogressbar
downvote count: 1
type: Question
has title: progress bar during time unkonwn process in pyqt4
has comment: http://stackoverflow.com/comment/88881437
tagged with: pyqt4
favorite count: 0
score: 0
has comment: http://stackoverflow.com/comment/88882333
has comment: http://stackoverflow.com/comment/88882197
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/88899249
comment on: http://stackoverflow.com/a/50946365
type: AnswerComment
score: 0
type: Comment
has text: It worked , Thanks , Seems like the error was the '?' . MySQL accepts either '%' method or format method but since format is not applicable because it needs to be replaced within the sql statement . Thanks alot

http://stackoverflow.com/comment/89127396
comment on: http://stackoverflow.com/q/50914555
has text: Take a look at [this](http://www.aizac.info/the-easiest-way-of-inter-thread-communication-for-python/) example in PyQt4
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50911592
type: AnsweredQuestion
upvote count: 0
type: Question
has body: i want to average price based on similar family and city columns in different rows, suppose i have following dataframe, df1 = [ID, name, family, city, price 1, a, g, u, 25 2, f, b, c, 20 3, i, b, c, 15 4, k, b, c, 10 5, r, b, c, 15 6, d, r, t, 20 7, q, x, s, 11] My expected dataframe is: df1 = [ID, name, family, city, price 1, a, g, u, 25 2, f, b, c, 15 3, i, b, c, 15 4, k, b, c, 15 5, r, b, c, 15 6, d, r, t, 20 7, q, x, s, 11] and i used groupby but it doesn't work well, shareg1 = df1'ID','name','family','city','price'.groupby(['family','city']).mean().reset_index()`
score: -1
tagged with: pandas
has answer: http://stackoverflow.com/a/50911645
accepted answer: http://stackoverflow.com/a/50911645
answer count: 1
downvote count: 1
favorite count: 0
has title: How dealing with semi-similar rows in pandas
tagged with: python

http://stackoverflow.com/comment/88967792
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50986441
has text: According to your code snippet, the list "L" is not suppose to change as "i" is just a counter veriable and holds single element from "L" every time it iterate.
score: 0

http://stackoverflow.com/comment/88866555
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50933860
has text: @today Wow, thank you! I knew it was something simple like that I was missing. Feel free to put write up an answer and I'll accept.

http://stackoverflow.com/a/50904712
has comment: http://stackoverflow.com/comment/88809363
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/88809347
answers question: http://stackoverflow.com/q/50904668
upvote count: 1
has body: You don't have to match regex to do that. you can use find instead: start = "------------------------------ Output ------------------------------" end = "--------------------------------------------------------------------" extracted_text = data[data.find(start)+len(start):data.rfind(end)] the output will be: ERROR: /b/cd-builder/sandboxes/sb_DEV_COMMON_BRANCH-_act-builder-4977/src/junos/usr.sbin/rpd/bgp/lib/proto/tls_syms.clang.amd64,bsdx: changed global or static TLS variables 261a262 bgp_inetsrte_incolor_update._xinfo If correct, use: mk --machine amd64,bsd11 -C junos/usr.sbin/rpd/bgp/lib/proto accept-syms make[1]: *** [check-syms] Error 1

http://stackoverflow.com/comment/135503596
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/65947322
has text: Is there a full example. Trying to do that but is that filename under os.walk?

http://stackoverflow.com/a/50990563
upvote count: 3
has body: Here's one way of achieving it i.e #Take the count of unique hours per year s = df.groupby(['year'])['hour'].nunique() # Take the count of the the runway n = df.groupby(['year','runway']).size().reset_index() # Divide them n['avg'] = n[0]/n['year'].map(s) year runway 0 avg 0 2017 30R 1 0.5 1 2017 32L 4 2.0 2 2018 32L 4 2.0
type: AcceptedAnswer
type: Answer
score: 3
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50990075
answers question: http://stackoverflow.com/q/50990075

http://stackoverflow.com/comment/88930245
comment on: http://stackoverflow.com/a/50966836
score: 1
type: AnswerComment
has text: i get error : /usr/local/bin/python3.6: No module named pip
type: Comment

http://stackoverflow.com/q/50906541
has title: Python get diff for ConfigParser
downvote count: 0
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
has body: Let say I have old and new configurations initialized from ConfigParser import ConfigParser old_config = ConfigParser() old_config.read(config_file1) new_config = ConfigParser() new_config.read(config_file2) How can I get the difference between these two configs?
tagged with: configparser
type: Question
tagged with: configuration
answer count: 1
tagged with: configuration-files
has comment: http://stackoverflow.com/comment/88813021
has answer: http://stackoverflow.com/a/50906868
score: 2

http://stackoverflow.com/q/50875335
linked to: http://stackoverflow.com/q/6255344
has comment: http://stackoverflow.com/comment/88752552
duplicate of: http://stackoverflow.com/q/6255344
has body: This is jquery ajax snippet use to send requests to localhost:5000/query so this is my jquery snippet var saveData=$.ajax({ type:"POST", url:"http://localhost:5000/query", datatype:"json", data:{"type":"Company","name":"harshit","cin":"2014UPTC20"}, success:function(resultData){ alert(resultData); } }); and i cannot retrieve above sent data from python flask:- @app.route('/query',methods=['POST']) def query_neo_dynamic(): data="currently working" #return json.dumps(fetch_specific_data(type,name,i_num)) req_data=request.get_json() return json.dumps(json.dumps(req_data)) if __name__=="__main__": app.run() I am getting a null please help
duplicate of: http://stackoverflow.com/q/20001229
type: Question
tagged with: jquery
tagged with: flask
tagged with: ajax
score: 0
has comment: http://stackoverflow.com/comment/88754733
duplicate of: http://stackoverflow.com/q/10434599
tagged with: python
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88752315
has title: cannot retrieve post data from python flask
has comment: http://stackoverflow.com/comment/88752266

http://stackoverflow.com/q/50899819
tagged with: python
upvote count: 4
has comment: http://stackoverflow.com/comment/88799803
has answer: http://stackoverflow.com/a/66497833
has comment: http://stackoverflow.com/comment/88799684
tagged with: sha256
downvote count: 0
has title: Computing a test hash with python pbkdf2_hmac-sha256 + salt not the same vaules
has answer: http://stackoverflow.com/a/50904046
type: Question
answer count: 2
has body: For a encryption class i'm in we were tasked to make a program to check a password if the computer knows the following defined information. The teacher gave us a working set of fixed information. I am trying to write a python code to verfiery a given set of user data based upon the known and fixed... digest method: HMAC-SHA256 rounds: 100000 salt:"e65814e4382759f85550029e723dc7e7" password:"governor washout beak" to output the derived: "5f37a3bd08ac1c7d163294a3cb192ed1407b62bbc6a6259fee55f6e53f754273" This is my code to generate the derived to check the against the above derived... key = hashlib.pbkdf2_hmac('sha256', b'governor washout beak', b'e65814e4382759f85550029e723dc7e7', 100000, dklen=32) print(binascii.hexlify(key)) however I get "0ce7d2e654c0ba80e67348c9610ca1851312458166ee8c9e6d46666832a21b11" instead. I don't understand what is missing.
score: 4
favorite count: 0
type: UnansweredQuestion

interpolation
tags question: http://stackoverflow.com/q/50978828
tags question: http://stackoverflow.com/q/50904604
tags question: http://stackoverflow.com/q/50905222
tag name: interpolation
tags question: http://stackoverflow.com/q/50865482
tags question: http://stackoverflow.com/q/50945375
type: Tag
tags question: http://stackoverflow.com/q/50938144

http://stackoverflow.com/comment/88719396
has text: Have you tried checking encoding of the database?
comment on: http://stackoverflow.com/q/50858303
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50876958
answers question: http://stackoverflow.com/q/50869441
upvote count: 1
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/88771567
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50869441
has body: (Spyder maintainer here) To have that you need to create a Spyder project per each conda environment by going to the menu Projects &gt; New project... and associating a directory with it. This is because our saves and loads the set of open files in our Editor associated with each project. Note: This will improved in Spyder 4 (to be released in 2019), when we add the possibility to associate pip/conda envs to our projects.
score: 1
has comment: http://stackoverflow.com/comment/88770069

http://stackoverflow.com/a/50990226
downvote count: 0
type: Answer
has body: You should install findspark modeule by pip then try: import findspark findspark.init('&lt;your spark home directory for example /home/spark&gt;') then you can import spark modules.
upvote count: 1
answers question: http://stackoverflow.com/q/50989747
score: 1

http://stackoverflow.com/comment/89011805
comment on: http://stackoverflow.com/a/51009517
type: AnswerComment
has text: Please find the explanation in my answer.
score: 0
type: Comment

http://stackoverflow.com/comment/121632880
comment on: http://stackoverflow.com/a/50912412
score: 0
type: AnswerComment
type: Comment
has text: Your edit doesn't answer the question, I think: the `__init__` of B is supposed to take only one parameter, and instance of `a`.

http://stackoverflow.com/a/50901012
downvote count: 0
answers question: http://stackoverflow.com/q/50900832
type: Answer
has body: Your code is quite good - it works exactly as it should, and I think asyncio still doesn't have some strong standards being developed. But if you just want to run coroutines in parallel, there is another way, and it is seen more frequently. It is asyncio.gather(). Gather's doc is quite self-explanatory, it returns future with list of results, and here is an example of your code with it: async def do_batch_work(): res1 = do_work(100000) res2 = do_work(100) return await asyncio.gather(res1, res2) def main(): loop = asyncio.get_event_loop() res1, res2 = loop.run_until_complete(do_batch_work()) print(res1) print(res2) loop.close()
score: 5
upvote count: 5

http://stackoverflow.com/q/50912024
upvote count: 1
has title: How to package sub-folder for gcloud ml?
accepted answer: http://stackoverflow.com/a/50918584
downvote count: 0
has body: I am trying to upload my project to google cloud ml-engine for training. I have followed the "getting started" guide, replacing in relevant places with my own files. I manage to train locally using gcloud ml-engine local train --module-name="my-model.task" --package-path=my-model/ -- ./my_model/model_params_google.json Yes, I have dashes in the module name :(. I also made a symbolic link my_module -&gt; my-module so that I can use the name with underscore instead of dash. In any case, I don't think this is the problem, since the above command works well locally. My folder structure doesn't follow the recommended one, since I had the project before thinking about ml-engine. It looks like this: my-model/ ├── __init__.py ├── setup.py ├── task.py ├── model_params_google.json ├── src │ ├── __init__.py │ ├── data_handler.py │ ├── elastic_helpers.py │ ├── model.py The problem is that the src folder is not packaged/uploaded with the code, so in the cloud, when I say from .src.model import model_fn in task.py, it fails. The command I use for packaging is (in folder my-model/../): gcloud ml-engine jobs submit training my_model_$(date +"%Y%m%d_%H%M%S") \ --staging-bucket gs://model-data \ --job-dir $OUTPUT_PATH \ --module-name="my_model.task" \ --package-path=my_model/ \ --region=$REGION \ --config config.yaml --runtime-version 1.8 \ -- \ tf_crnn/model_params_google.json --verbosity DEBUG It packages my-model.0.0.0.tar.gz without the contents of my-model/src. I cannot figure out why. I'm using the example setup.py: from setuptools import find_packages from setuptools import setup REQUIRED_PACKAGES = ['tensorflow&gt;=1.8'] setup( name='my_model', version='0.1', install_requires=REQUIRED_PACKAGES, packages=find_packages(), include_package_data=True, description='my first model' ) So, the question is, why does gcloud not pack the src folder ?
type: AnsweredQuestion
score: 1
favorite count: 0
type: Question
tagged with: google-cloud-ml
tagged with: package
has answer: http://stackoverflow.com/a/50918584
tagged with: python
answer count: 1

http://stackoverflow.com/q/50859307
has title: Django - Form value ERROR [Simple?]
tagged with: django-views
has body: I will provide all the details necessary to this issue. Issue description: I store some input fields with the Django forms (i.e. FormPredmet) After that I save the form in a model called > Predmet When pulling the data I have an issue that I didn't have with ModelForm When printing or displaying (on the page) the Predmet.predavacIme object I get: &lt;input type="text" name="Ime_Predavaca" value="Elvir" maxlength="50" required id="id_Ime_Predavaca" /&gt; &lt;input type="text" name="Ime_Predavaca" value="Elvir" maxlength="50" required id="id_Ime_Predavaca" /&gt; &lt;input type="text" name="Ime_Predavaca" value="Dzenan" maxlength="50" required id="id_Ime_Predavaca" /&gt; &lt;input type="text" name="Ime_Predavaca" value="Petko" maxlength="50" required id="id_Ime_Predavaca" /&gt; Instead I just wanted a single value of each of these: Desired output: Elvir,Elvir, Dzenan, Petko Summary: I get data using FormPredmet(forms.Form) this is I think the issue then save the data to the Model Predmet I try getting any obj for instance: myobj = Predmet.objects.get(pk=1) after printing one of it's fields print(myobj.imePredavaca()) Instead of a value like "Elvir" I get HTML..input.. (did I store html?) Modelsmodels.py class ModelRazred(models.Model): godina = models.PositiveSmallIntegerField() brojRazreda = models.PositiveSmallIntegerField() ime = models.CharField(max_length=50) prezime = models.CharField(max_length=50) class Predmet(models.Model): predavacIme = models.CharField(max_length=50) predavacPrezime = models.CharField(max_length=50) imePredmeta = models.CharField(max_length=50) razred = models.ForeignKey(ModelRazred, on_delete=models.CASCADE) URLS urls.py """urlconf for the base application""" from django.urls import path from .views import * urlpatterns = [ #Base path('', home, name='home'), # Stranice path('dodajrazred/', dodajrazred, name='dodajrazred'), path('predmeti/&lt;int:razred_id&gt;/', predmetisubmit, name='predmetisubmit'), path('razred/&lt;int:razred_id&gt;/', …
score: 1
has answer: http://stackoverflow.com/a/50859761
upvote count: 1
tagged with: django
tagged with: django-forms
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88721518
tagged with: django-models
linked to: http://stackoverflow.com/q/5925278
accepted answer: http://stackoverflow.com/a/50859761
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/88721582
tagged with: python

http://stackoverflow.com/comment/88805481
has text: you can fill the list with None or Zeros first, and later set in position
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50902804

http://stackoverflow.com/a/50860678
has body: What you want to do is iterate over a product. Use itertools.product. import itertools ranges = [range(x1, x2), range(x3, x4), ...] for xs in itertools.product(*ranges): f(*xs) Example import itertools ranges = [range(0, 2), range(1, 3), range(2, 4)] for xs in itertools.product(*ranges): print(*xs) Output 0 1 2 0 1 3 0 2 2 0 2 3 1 1 2 1 1 3 1 2 2 1 2 3
upvote count: 6
downvote count: 0
score: 6
type: Answer
answers question: http://stackoverflow.com/q/50860578

http://stackoverflow.com/a/50908316
has comment: http://stackoverflow.com/comment/88816391
has body: The reason why your code fails on python 3.x as already been answered by @FHTMitchell answer, that said, here's a simpler way to achieve what you want in both python2.x/3.x: print(["Happy Birthday to {}".format("you" if x!=2 else "dear Name") for x in range(4)]) There is a lot of ways to achieve this task, few more examples: lst = ["Happy Birthday to you"]*4; lst[1] = lst[1].replace("you", "dear Name"); print(lst) s1 = "Happy Birthday to you"; print([s1,s1.replace("you", "dear Name"),s1,s1]) But if you ask me, my favourite one, even if not a oneliner, would be doing something like this: import textwrap song = textwrap.dedent("""\ Happy Birthday to you Happy Birthday to dear Name Happy Birthday to you Happy Birthday to you """) print(song.splitlines())
has comment: http://stackoverflow.com/comment/88816889
downvote count: 0
has comment: http://stackoverflow.com/comment/88816845
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/88816408
answers question: http://stackoverflow.com/q/50908196
upvote count: 2
has comment: http://stackoverflow.com/comment/88820225

http://stackoverflow.com/q/50916170
type: Question
tagged with: youtube-dl
has comment: http://stackoverflow.com/comment/88845845
answer count: 2
has comment: http://stackoverflow.com/comment/88839582
favorite count: 0
has answer: http://stackoverflow.com/a/66161615
type: UnansweredQuestion
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/88836403
has body: I am trying to use youtube-dl embedded in a script. I would like it to only download videos from a playlist after a certain date. But, none of the options I have tried work. I have tried dateafter and daterange. Here is what I currently have: from __future__ import unicode_literals import youtube_dl from youtube_dl.utils import DateRange import os def prog_hook(d): if d['status'] == 'finished': path='/home/pi/.temp/Commute/' for filename in os.listdir(path): if os.path.isdir(os.path.join(path,filename)): mvcmd = 'rsync -a --remove-source-files /home/pi/.temp/Commute/{}/ /home/pi/Commute/{}/'.format(filename, filename) os.system(mvcmd) delcmd = 'rm -r {}'.format(filename) os.system(delcmd) daterange = DateRange('20180601') ydl_opts = { 'format' :'bestaudio/best', 'format' : 'mp4', 'outtmpl' : '/home/pi/.temp/Commute/%(playlist)s/00%(playlist_index)s-%(title)s.%(ext)s', 'download_archive' : '/home/pi/.temp/Commute/downloadedShows.txt', 'ignoreerrors' : 'True', 'restrictfilenames' : 'True', 'daterange' : daterange, 'progress_hooks' : [prog_hook], } with youtube_dl.YoutubeDL(ydl_opts) as ydl: try: link = ["https://www.youtube.com/playlist?list=PLBZb_61EqeJlvaIUzRne-vxEFhNDLvmga"] ydl.download(link) except: pass
has answer: http://stackoverflow.com/a/50929705
score: 0
has comment: http://stackoverflow.com/comment/88836448
has comment: http://stackoverflow.com/comment/88858104
downvote count: 1
has title: YouTube-DL Embeded Date After Option

http://stackoverflow.com/comment/88851512
comment on: http://stackoverflow.com/q/50926012
has text: `#.orange.*` is a comment, you should at least enclose it in quotes to make a string.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50929015
accepted answer: http://stackoverflow.com/a/50929480
favorite count: 0
has comment: http://stackoverflow.com/comment/88857366
tagged with: python
has title: Generating an evenly sized matrix by a given number of elements in python?
has body: I have a python list containing n items. I would like to place the items in an (nearly) evenly sized matrix.i.e the matrix shape should be as close to a square as possible. Here are some examples. number of items 4, matrix size: 2*2 number of items 5, matrix size: 3*2 number of items 6, matrix size: 3*2 number of items 7, matrix size: 3*3
has answer: http://stackoverflow.com/a/50932767
has comment: http://stackoverflow.com/comment/88857351
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88857041
possible better answer: http://stackoverflow.com/a/50930523
has comment: http://stackoverflow.com/comment/88857595
downvote count: 3
has answer: http://stackoverflow.com/a/50930523
type: Question
has answer: http://stackoverflow.com/a/50929480
has comment: http://stackoverflow.com/comment/88902201
score: -3
answer count: 3
upvote count: 0

http://stackoverflow.com/comment/88777722
type: QuestionComment
type: Comment
has text: >>> id(t+t) 49172744L >>> id(t*2) 49172744L
comment on: http://stackoverflow.com/q/50888069
score: 0

http://stackoverflow.com/q/50963616
linked to: http://stackoverflow.com/q/16434725
answer count: 1
tagged with: flask
duplicate of: http://stackoverflow.com/q/16434725
has answer: http://stackoverflow.com/a/50963803
tagged with: http://stackoverflow.com/tag/html
has body: My webapp has two pages: home and maps. Clicking on either button on home should redirect to maps (with different parameters). However, on clicking Flask routes me to '/' (home). I tried getting around this with a redirect, but then the form data wasn't preserved. Here is the relevant code: home.html Spot Events app.py @app.route('/', methods=['GET']) def home_page(): if request.method == 'GET': return render_template('home.html') @app.route('/maps', methods=['GET', 'POST']) def maps(): if request.method == 'GET': return render_template('404.html') elif request.method == 'POST': if 'spot' in request.form: return render_template('maps.html', filter='spot') elif 'event' in request.form: return render_template('maps.html', filter='event')
has title: Flask form redirects to same page
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50963803
score: 0
type: Question

http://stackoverflow.com/a/50996644
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50996623
has body: There are a couple ways to deal with this, and it kind of depends what you're looking for: You could encode your categories to numeric values, i.e. transform each level of your category to a distinct number, or dummy code your category, i.e. turn each level of your category into a separate column, which gets a value of 0 or 1. In lots of machine learning applications, factors are better to deal with as dummy codes. Note that in the case of a 2-level category, encoding to numeric according to the methods outlined below is essentially equivalent to dummy coding: all the values that are not level 0 are necessarily level 1. In fact, in the dummy code example I've given below, there is redundant information, as I've given each of the 2 classes its own column. It's just to illustrate the concept. Typically, one would only create n-1 columns, where n is the number of levels, and the omitted level is implied (i.e. make a column for Female, and all the 0 values are implied to be Male). Encoding Categories to numeric: Method 1: pd.factorize pd.factorize is a simple, fast way of encoding to numeric: For example, if your column gender looks like this: &gt;&gt;&gt; df gender 0 Female 1 Male 2 Male 3 Male 4 Female 5 Female 6 Male 7 Female 8 Female 9 Female df['gender_factor'] = pd.factorize(df.gender)[0] &gt;&gt;&gt; df gender gender_factor 0 Female 0 1 Male 1 2 Male 1 3 Male 1 4 Female 0 5 Female 0 6 Male 1 7 Female 0 8 Female 0 9 Female 0 Method 2: categorical dtype Another way would be to use category dtype: df['gender_factor'] = df['gender'].astype('category').cat.codes This would result in the same output Method 3 sklearn.preprocessing.LabelEncoder() This method comes with some bonuses, such as easy back transforming: from sklearn import preprocessing le = preprocessing.LabelEncoder() # Transform the gender column df['gender_factor'] = le.fit_transform(df.gender) &gt;&gt;&gt; df gender gender_factor 0 Female 0 1 Male 1 2 Male 1 3 Male 1 4 Female 0 5 Female 0 6 Male 1 7 Femal…
type: Answer
upvote count: 14
score: 14
has comment: http://stackoverflow.com/comment/89021660
accepted answer of: http://stackoverflow.com/q/50996623

http://stackoverflow.com/a/50899439
accepted answer of: http://stackoverflow.com/q/50899179
answers question: http://stackoverflow.com/q/50899179
has body: df.join(...) is usually used to join on the index of df with the index of another DataFrame. df.join(..., on='id') joins the id column of df with the index of another DataFrame. Per the docs (my emphasis): on : name, tuple/list of names, or array-like Column or index level name(s) in the caller to join on the index in other, otherwise joins index-on-index. If multiple values given, the other DataFrame must have a MultiIndex. Can pass an array as the join key if it is not already contained in the calling DataFrame. Like an Excel VLOOKUP operation Since x and y look like this: In [14]: x Out[14]: id value1 0 1 5 1 2 5 2 3 5 In [15]: y Out[15]: id value2 0 1 10 x.join(y, on='id') attempts to join x['id'] (with values 1, 2, 3) with y.index (with value 0). Since x['id'] and y.index have no values in common, the (by default) left join produces NaNs for the values in the new y-columns produced by the join. z1 = x.join(y, on = "id") raises ValueError: columns overlap but no suffix specified: Index(['id'], dtype='object') because the y-columns produced by the join include id which is already a x-column name. When column names overlap, you must specify a lsuffix, rsuffix, or both to disambiguate the column names. z2 = x.join(y, on = "id", lsuffix = "_left", rsuffix = "_right") returns In [12]: z2 Out[12]: id_left value1 id_right value2 0 1 5 NaN NaN 1 2 5 NaN NaN 2 3 5 NaN NaN because the common x and y-column (i.e. the id column) has been disambiguated. The NaN values are due to x['id'] and y.index having no values in common (as explained above). z3 = x.join(y, lsuffix = "_left", rsuffix = "_right") produces In [20]: z3 Out[20]: id_left value1 id_right value2 0 1 5 1.0 10.0 1 2 5 NaN NaN 2 3 5 NaN NaN because now the join is being performed on x.index and y.index.
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/a/51004252
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51002858
accepted answer of: http://stackoverflow.com/q/51002858
type: Answer
has body: The background of your window is indeed black. However, you're covering it with a canvas so you won't be able to see the black. You can see this by adding the options padx=10 and pady=10 when packing the canvas to see the black that surrounds the canvas. If you want the canvas to be black, set it's background color to be black (eg: canvas = Canvas(self.master, ..., background='black') In the comments it sounds like you are complaining about the thin white border around the canvas. If you don't want that border, set borderwidth to zero, and also set highlightthickness to zero.
score: 1
upvote count: 1

http://stackoverflow.com/q/50927715
favorite count: 0
has body: How can I save MS Word .docx file data into modal table like Excel sheet row wise, column wise using django from subprocess import Popen, PIPE from docx import opendocx, getdocumenttext from cStringIO import StringIO def document_to_text(filename, file_path): cmd = ['antiword', file_path] p = Popen(cmd, stdout=PIPE) stdout, stderr = p.communicate() return stdout.decode('ascii', 'ignore') print document_to_text('your_file_name','your_file_path')
type: UnansweredQuestion
tagged with: django
tagged with: python
answer count: 0
score: 1
upvote count: 1
type: Question
has title: How can I save .docx file data into modal table like Excel sheet using django
tagged with: python-2.7
downvote count: 0

http://stackoverflow.com/q/50897438
has comment: http://stackoverflow.com/comment/88794673
type: Question
tagged with: date
has comment: http://stackoverflow.com/comment/88794853
duplicate of: http://stackoverflow.com/q/38189867
score: 0
linked to: http://stackoverflow.com/q/38189867
has comment: http://stackoverflow.com/comment/88794634
has body: This is driving me crazy. I've looked and looked at the strptime documentation and can't for the life of me figure out why this isn't working. Please help! import datetime a = '20180615 16:00 EST' datetime.datetime.strptime(a, '%Y%m%d %H:%M %Z') Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2963, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "&lt;ipython-input-30-d72261c0e1d6&gt;", line 1, in &lt;module&gt; datetime.datetime.strptime(a, '%Y%m%d %H:%M %Z') File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/_strptime.py", line 565, in _strptime_datetime tt, fraction = _strptime(data_string, format) File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/_strptime.py", line 362, in _strptime (data_string, format)) ValueError: time data '20180615 16:00 EST' does not match format '%Y%m%d %H:%M %Z'
type: UnansweredQuestion
tagged with: python
answer count: 0
has title: Why isn't this string parsing as a date?

http://stackoverflow.com/q/50950009
linked to: http://stackoverflow.com/q/33024510
has comment: http://stackoverflow.com/comment/88897675
type: UnansweredQuestion
tagged with: django
tagged with: python
has title: Equivalent of Rails' seed file in Django with Python3
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/88898722
tagged with: database
tagged with: seed
score: 0
has body: I would like to manually populate the database in my Django app. In Rails, I just have to enter the info in the seed file and that's it. The db.sqlite3 file has many numbers in it which I don't get. I am a beginner so please forgive my ignorance. In which directory should I put my DB and which format should the file be in? Then, how can I manually (no Faker I want to write the instances myself) create the DB? Finally, how can I retrieve the info to display it in my view? Thanks!
tagged with: sqlite

http://stackoverflow.com/a/50988113
has body: The problem is that your Lambda function is unable to connect to your EC2 instance which is running MongoDB. This is most likely a SecurityGroup issue. You should allow your lambda VPC to connect to your EC2 instance. In essence it means that you will assign a VPC, subnet and Security group to your lambda. Afterwards you can allow the security group of the lambda to access the security group of your mongo. Detailed instructions on how to add a vpc/subnet/sg to your lambda can be found here You add VPC information to your Lambda function configuration using the VpcConfig parameter, either at the time you create a Lambda function (see CreateFunction), or you can add it to the existing Lambda function configuration (see UpdateFunctionConfiguration).
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 3
has comment: http://stackoverflow.com/comment/97208399
score: 3
accepted answer of: http://stackoverflow.com/q/50986575
answers question: http://stackoverflow.com/q/50986575

http://stackoverflow.com/comment/88769974
type: Comment
has text: `cat /proc/pid/task/tid/comm` will show only 'python' if I execute my program as `python myprogram.py`. but I want to see it as 'Thread-1', as that is the name I have specified for the thread.
type: AnswerComment
comment on: http://stackoverflow.com/a/50867673
score: 0

http://stackoverflow.com/a/50866732
upvote count: 4
accepted answer of: http://stackoverflow.com/q/50866657
type: AcceptedAnswer
downvote count: 0
score: 4
answers question: http://stackoverflow.com/q/50866657
has comment: http://stackoverflow.com/comment/88760775
type: Answer
has body: This is a simple groupby. Let me see if I find a dupe: import pandas as pd df = pd.DataFrame({ 'LOT': [102,104,162,102,104,102], 'VAL': [22,424,65,4,34,6] }) df = [x for _, x in df.groupby('LOT')] Ok, I found something. However the answer seems overcomplicated so I'm gonna leave this here. Looks a lot like: Split pandas dataframe based on groupby
has comment: http://stackoverflow.com/comment/104950398
has comment: http://stackoverflow.com/comment/104944606

http://stackoverflow.com/comment/88956667
has text: @MatrixTai Python _does_ have real parallel processing. You can run multiple I/O-bound threads in parallel, you can run multiple threads doing work in libraries like NumPy in parallel, or of course you can run multiple processes instead of threads in parallel.
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/50980459

http://stackoverflow.com/comment/89045752
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50996166
has text: Thanks for the help! I get the error at the os.mkdir(newFolder) line.

http://stackoverflow.com/comment/88936228
has text: On second thought, it's not constant time, but linear time with respect to degree. But that's almost as good as constant time, since degree won't go above 10 anyway.
score: 0
comment on: http://stackoverflow.com/q/50968800
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88790441
type: QuestionComment
comment on: http://stackoverflow.com/q/50895202
score: 1
has text: What if you use a `$` at the end?
type: Comment

http://stackoverflow.com/comment/89014874
comment on: http://stackoverflow.com/q/51011057
has text: The solution was so simple. Thanks
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89014227
comment on: http://stackoverflow.com/q/51010770
has text: Post this data frame as text rather than image
score: 5
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88879954
has text: For sure, Kris is great! If you want to know more about the dedup process, there's info about that here: https://zapier.com/developer/documentation/v2/deduplication/ It sounds like you are taking a more custom and more complex approach to the problem. Good luck!
comment on: http://stackoverflow.com/a/50933101
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/88760312
type: Comment
has text: @juanpa.arrivillaga I love being pedantic, helps me understand things better. I only said it was misleading because someone else might read that and assume it passes by value, since call-by-sharing is less common to think about in this context. Thanks for the responses
type: AnswerComment
comment on: http://stackoverflow.com/a/50878705
score: 0

http://stackoverflow.com/q/50997085
favorite count: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/50997411
has comment: http://stackoverflow.com/comment/88988450
tagged with: python
type: AnsweredQuestion
upvote count: 1
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/50997411
has body: I'm currently working with data from a camera that tracks the location of a robotic agent and humans moving around it. I want to set the distance of the people relative to the robot rather than the grid the camera is currently using. Below is an example of the formatted data: x idx time type 0 -24.782 7 1.390789e+09 0 1 25.832 6 1.390789e+09 0 2 47.513 5 1.390789e+09 0 3 42.492 4 1.390789e+09 0 4 10.387 3 1.390789e+09 0 5 -12.468 2 1.390789e+09 0 6 44.725 1 1.390789e+09 0 7 -13.452 0 1.390789e+09 1 Type = 1 indicates that the agent identified is the robot and I'd like to subtract all the 'x' values where Type == 0 (humans) by the robot's (Type == 1) position(only when the time value is the same). I've made some ham-handed attempts at doing this, but short of iterating through and then rebuilding the data frame, I have been unable to do it efficiently. Is there a more pythonic way to go about this?
has comment: http://stackoverflow.com/comment/88989505
has comment: http://stackoverflow.com/comment/88989046
has title: Pandas: Subtracting columns based on row values
has comment: http://stackoverflow.com/comment/88989521
has comment: http://stackoverflow.com/comment/88988601
score: 0
has comment: http://stackoverflow.com/comment/88988550
has comment: http://stackoverflow.com/comment/88989113
answer count: 1

http://stackoverflow.com/a/50998457
answers question: http://stackoverflow.com/q/50998417
has comment: http://stackoverflow.com/comment/88991391
downvote count: 3
has comment: http://stackoverflow.com/comment/88991373
has body: The fastest way is: def capitalize_names(inp): return [i.capitalize() for i in inp] def test_capitalize_names(): assert ["James"] == capitalize_names(["JAMES"]) assert ["Harry", "Jack"] == capitalize_names(["HArry", "jack"])
type: Answer
upvote count: 4
has comment: http://stackoverflow.com/comment/88991177
score: 1
has comment: http://stackoverflow.com/comment/88991030

http://stackoverflow.com/q/50942814
has answer: http://stackoverflow.com/a/50942891
has comment: http://stackoverflow.com/comment/88883446
tagged with: python
answer count: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88883101
possible better answer: http://stackoverflow.com/a/50942949
has comment: http://stackoverflow.com/comment/88883686
score: 0
has answer: http://stackoverflow.com/a/50942949
accepted answer: http://stackoverflow.com/a/50942891
type: Question
has answer: http://stackoverflow.com/a/50942967
has comment: http://stackoverflow.com/comment/88883305
tagged with: replace
has body: I am trying to count the word frequency in a long string. I have split the string into list of words using string.split() method and remove case sensity by applying string.lower() before splitting the long string. I want to remove some special character such as '!', ':', '.' as those character will mess up the word count. Below is the function that I wrote but it seems not to work properly def clean_word(word): replace_list = [':','.',',','!','?'] s = list(word) for i in s: for j in replace_list: if i == j: i="" print(s) # to see s before it being joined word =''.join(s) return word print(clean_word('Hello!')) The result is: ['H', 'e', 'l', 'l', 'o', '!'] Hello! I wonder why "!" has not been replaced with ""? I did put in a test code at line and it shows the comparison works. if i == j: print('Checked')
tagged with: char
tagged with: string
has answer: http://stackoverflow.com/a/50943013
has title: Remove special char out of a word

http://stackoverflow.com/a/50951221
has body: Here is one way.Let's call your dataframe df. First work is on the case where cells ends by A or N. # create the mask when finisig by A or N mask_AN = (df['cells'].str[-1] == 'A') | (df['cells'].str[-1] == 'N') # create the column final_value and write # 1 if the value should be from the column npv and #2 if the value should be from the column scpci df.loc[mask_AN,'final_value'] = pd.np.where((df.loc[mask_AN,'scpci']%3 == 0) &amp; (df.loc[mask_AN,'npv']%3 != 0),2,1) The np.where works as: the final_value should be from scpci (so 2 for now) only if the column scpci is divisible by 3 while the column npv is not, otherwise the final_value will be from npv (so 1). The next step is to fill final_value for a same site with the value where cells ends by A or N. This can be done by: df['final_value'] = df.groupby('Site')['final_value'].ffill() # fill forward Note that the filling works here as it seems that you have a cell ending by 'A' before one endings by 'B' or 'C' (except when unique) and same a cell ending by 'N' before one endings with 'O' and 'P'. This ffill might not work if you don't always have this configuration. Finally, you need to do the site with unique row: # mask of site with unique cell df_g = df.reset_index().groupby('Site') mask_unique = df_g.index.first()[df_g.cells.count() ==1] # a bit on the same idea than before for adding 1 or 2 in the final_value column df['final_value'].loc[mask_unique] = pd.np.where((df['scpci'].loc[mask_unique]%3 == 0) &amp; (df['npv'].loc[mask_unique]%3 != 0),2,1) Now that you have 1 or 2 in this final_value column, just need to replace by the value in the associated column: df['final_value'] = pd.np.where( df['final_value'] == 1, df['npv'], df['scpci']) The output is like expected: Site cells Azimut technology npv scpci final_value 0 T30264 G30264B 130 UMTS900 343 276 276 1 T30992 G30992A 10 UMTS900 171 12 171 2 T30992 G30992B 260 UMTS900 173 13 173 3 T30992 U30992A 10 UMTS2100 171 12 171 4 T30992 U30992B 260 UMTS2100 173 13 …
upvote count: 2
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/88919026
accepted answer of: http://stackoverflow.com/q/50947267
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88918836
downvote count: 0
has comment: http://stackoverflow.com/comment/88936094
has comment: http://stackoverflow.com/comment/88918125
answers question: http://stackoverflow.com/q/50947267

http://stackoverflow.com/comment/88998013
comment on: http://stackoverflow.com/a/51002123
type: AnswerComment
score: 0
type: Comment
has text: Thanks for the help! However, I got the following: `TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'RangeIndex'`

http://stackoverflow.com/comment/88713721
has text: Your mapping can't be an instance attribute if you're using it like this, because the decorator is run during class definition. Why do you need the class?
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50855495

http://stackoverflow.com/comment/88993739
score: 0
comment on: http://stackoverflow.com/a/50999625
type: Comment
has text: Thanks, I didn't know the zip function, did some research and now I understand! But one more question: After I shuffle the names, each time I print names, do I always get a shuffled names list?
type: AnswerComment

http://stackoverflow.com/q/50984928
downvote count: 0
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: Upset Plot in Python with large dataset
score: 3
has body: The Best and efficient way of plotting upset plot in python for large dataset. I've three data set consisting of 500Million, 300Million and 150Million. I know pyupset can be used but is it recommended to use with above mentioned large dataset.
type: Question
has comment: http://stackoverflow.com/comment/99261439
tagged with: graph
has answer: http://stackoverflow.com/a/53300669
tagged with: database
upvote count: 3
tagged with: pandas

http://stackoverflow.com/comment/88957554
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50980795
has text: 'code' PROXY = "test:8080" # IP:PORT or HOST:PORT chrome_options = webdriver.ChromeOptions() chrome_options.add_argument('--proxy-server=%s' % PROXY) # Connect Chrome to proxy # Enter chromedriver path chrome = webdriver.Chrome("<driver path>",chrome_options=chrome_options) chrome.get(url) --------------------------------------- I want to stop/pause the program for here -------------------------------- Remaining code to be executed later. All these are written in a single function
score: 0

http://stackoverflow.com/comment/88728165
has text: Try printing out every line to the console/idle and then at least you can see what information python is processing. Especially print out an empty argument.
score: 1
comment on: http://stackoverflow.com/q/50862801
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50894409
answers question: http://stackoverflow.com/q/50894170
upvote count: 1
has body: The answer given above is correct. You should provide the path to the ChromeDriver that you downloaded from the link mentioned above. For example, create a folder name ChromeDriver on your desktop and unzip the executable there. Then provide the path as chrome_path = '/Users/[yourname]/Desktop/chromedriver_mac64/chromedriver' driver = webdriver.Chrome(chrome_path)
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/88796830
type: Answer

http://stackoverflow.com/q/50950953
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50951825
has answer: http://stackoverflow.com/a/50953087
downvote count: 1
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/50969037
score: 3
has answer: http://stackoverflow.com/a/50952383
has comment: http://stackoverflow.com/comment/88903675
upvote count: 4
has title: How to vectorize (make use of pandas/numpy) instead of using a nested for loop
tagged with: pandas
possible better answer: http://stackoverflow.com/a/50952383
has body: I wish to efficiently use pandas (or numpy) instead of a nested for loop with an if statement to solve a particular problem. Here is a toy version: Suppose I have the following two DataFrames import pandas as pd import numpy as np dict1 = {'vals': [100,200], 'in': [0,1], 'out' :[1,3]} df1 = pd.DataFrame(data=dict1) dict2 = {'vals': [500,800,300,200], 'in': [0.1,0.5,2,4], 'out' :[0.5,2,4,5]} df2 = pd.DataFrame(data=dict2) Now I wish to loop through each row each dataframe and multiply the vals if a particular condition is met. This code works for what I want ans = [] for i in range(len(df1)): for j in range(len(df2)): if (df1['in'][i] &lt;= df2['out'][j] and df1['out'][i] &gt;= df2['in'][j]): ans.append(df1['vals'][i]*df2['vals'][j]) np.sum(ans) However, clearly this is very inefficient and in reality my DataFrames can have millions of entries making this unusable. I am also not making us of pandas or numpy efficient vector implementations. Does anyone have any ideas how to efficiently vectorize this nested loop? I feel like this code is something akin to matrix multiplication so could progress be made utilising outer? It's the if condition that I'm finding hard to wedge in, as the if logic needs to compare each entry in df1 against all entries in df2.
favorite count: 0
has answer: http://stackoverflow.com/a/50969037
tagged with: python
tagged with: vectorization
answer count: 4

http://stackoverflow.com/a/50991218
answers question: http://stackoverflow.com/q/50991123
has body: Use re.split Ex: import re s = "I:would:like:to:find\:out:how:this\:works" print( re.split(r"(?&lt;=\w):", s) ) Output: ['I', 'would', 'like', 'to', 'find\\:out', 'how', 'this\\:works']
downvote count: 0
score: 1
type: Answer
upvote count: 1

http://stackoverflow.com/a/50936443
downvote count: 0
has comment: http://stackoverflow.com/comment/88871816
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/50936377
has body: on_message takes a Message object, not a Context object. You should probably also add await bot.process_commands(message) to the end of your on_message coroutine. Otherwise none of your commands will be called bot.say will not work outside a command. Use bot.send_message instead. @bot.event async def on_message(message): primary_id = message.author.id if primary_id not in amounts: print("") else: bob = random.randint(1,25) if bob == 1: await bot.send_message(message.channel, "You got a crate! It contained 5 coins!") amounts[primary_id] += 5 with open('amounts.json', 'w+') as f: json.dump(amounts, f) else: print("") await bot.process_commands(message)

http://stackoverflow.com/a/50937547
answers question: http://stackoverflow.com/q/50937505
upvote count: 2
score: 2
has body: The reason you're getting a ValueError in the background thread is that you're explicitly raising a ValueError in the target function for that thread: def CheckTime(): global gamesummary sleep(5) print("Time's up!") gamesummary.close() raise ValueError When a background thread raises an exception, instead of killing the whole program, it just dumps the traceback to stderr and kills the thread, leaving the other threads running. Which is what you're seeing here. If you don't want that, just leave that line off. If you were hoping the exception would somehow affect the main thread, it's not going to do that. But you don't need it to do that. You're closing the file out from under the main thread, which means AskQuestions is going to get a ValueError: I/O operation on closed file exception when it tries to write to the file. Which you're properly handling. This is a bit of an odd design, but it will work as intended; you don't need to add anything extra on top of it. If you were hoping to catch the exception from the main thread, that won't work either—but again, it isn't needed. The main thread isn't affected by the background thread's exception.
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50937505
type: Answer

http://stackoverflow.com/a/50895557
downvote count: 0
has body: This is one way: import itertools list1 = [{'firstname':'foo','lastname':'bar','id':1}, {'firstname':'foo2','lastname':'bar2','id':2}] list2 = [{'text':'sample','contact_no':'666','id':1}, {'text':'sample2','contact_no':'111','id':1}, {'text':'sample3','contact_no':'121','id':2}] lst = [] for x, y in itertools.product(list1, list2): if x['id'] == y['id']: c = x.copy() c.update(y) lst.append(c) print(lst) # [{'firstname': 'foo', 'lastname': 'bar', 'id': 1, 'text': 'sample', 'contact_no': '666'}, # {'firstname': 'foo', 'lastname': 'bar', 'id': 1, 'text': 'sample2', 'contact_no': '111'}, # {'firstname': 'foo2', 'lastname': 'bar2', 'id': 2, 'text': 'sample3', 'contact_no': '121'}]
upvote count: 3
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50895239
type: Answer
accepted answer of: http://stackoverflow.com/q/50895239
score: 3

http://stackoverflow.com/q/51002638
upvote count: 2
tagged with: python
downvote count: 1
type: AnsweredQuestion
score: 1
type: Question
has answer: http://stackoverflow.com/a/51002785
answer count: 1
tagged with: search
tagged with: binary-search
has body: I'm new to stack overflow. I hope this question meets the guide lines. Thnakyou.! class Solution: def searchRange(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ start = self.firstGreaterEqual(nums, target) if start==len(nums) or nums[start]!=target: return [-1, -1] return [start, self.firstGreaterEqual(nums, target+1)-1] def firstGreaterEqual(self, nums, target): lo, hi = 0, len(nums) while lo&lt;hi: mid = (hi+lo)//2 if nums[mid]&lt;target: lo = mid + 1 else: hi = mid return lo Input: nums = [5,7,7,8,8,10], target = 6 Output: [-1,-1] Input: nums = [5,7,7,8,8,10], target = 8 Output: [3,4] This program is to search for a range link to the program This solution has the best run time. I'm finding it hard to understand the logic behind it. It is using binary search but I'm not fully understanding it.
has title: How does this program work? How's firstGreaterEqual method working
favorite count: 0
accepted answer: http://stackoverflow.com/a/51002785

http://stackoverflow.com/a/50939502
has body: If you want to store all of the values entered and then print them, you may use a list. You code would end like this: #number_enterd = str() # This is totally unnecessary. This does nothing num = int(input ( "Enter a number: " )) total = 0 #sum of number numsEntered = [] # An empty list to hold the values we will enter numsEntered.append(num) # Add the first number entered to the list while num != 0: total += num num = int(input ( "Enter a number: " )) #number_enterd = num # Unnecesary as well, this overwrites what you wrote in line 2 # It doesn't even make the num a string numsEntered.append(num) #This adds the new num the user just entered into the list print("Total is =", total ) print("Numbers entered:", numsEntered) #check to see the numbers you've collected For example, user enters 5,2,1,4,5,7,8,0 as inputs from the num input request. Your output will be: &gt;&gt;&gt;Total is = 32 &gt;&gt;&gt;Numbers entered: [5, 2, 1, 4, 5, 7, 8, 0] Just as a guide, this is how I would do it. Hope it helps: num = int(raw_input("Enter a number: ")) numsEntered = [] # An empty list to hold the values we will enter total = 0 #sum of numbers while True: numsEntered.append(num) #This adds the num the user just entered into the list total += num num = int(raw_input("Enter a number: ")) print("Total is =", total) print("Numbers entered:", numsEntered) #check to see the numbers you've collected In this case, the last 0 entered to get out of the loop doesn't show up. At least, I wouldn't want it to show up since it doesn't add anything to the sum. Hope you like my answer! Have a good day :)
type: Answer
answers question: http://stackoverflow.com/q/50939311
score: 0

http://stackoverflow.com/a/52054734
has body: import os import pymysql import pandas as pd host = os.getenv('MYSQL_HOST') port = os.getenv('MYSQL_PORT') user = os.getenv('MYSQL_USER') password = os.getenv('MYSQL_PASSWORD') database = os.getenv('MYSQL_DATABASE') conn = pymysql.connect( host=host, port=int(port), user=user, passwd=password, db=database, charset='utf8mb4') df = pd.read_sql_query("SELECT * FROM YOUR_TABLE", conn) df.tail(10)
answers question: http://stackoverflow.com/q/50973191
downvote count: 0
type: Answer
score: 16
upvote count: 16

http://stackoverflow.com/a/50910770
accepted answer of: http://stackoverflow.com/q/50909824
type: AcceptedAnswer
upvote count: 44
has comment: http://stackoverflow.com/comment/88824176
type: Answer
downvote count: 0
has body: AWS Lambda also sets up a handler, on the root logger, and anything written to stdout is captured and logged as level INFO. Your log message is thus captured twice: By the AWS Lambda handler on the root logger (as log messages propagate from nested child loggers to the root), and this logger has its own format configured. By the AWS Lambda stdout-to-INFO logger. This is why the messages all start with (asctime) [(levelname)]-(module):(lineno), information; the root logger is configured to output messages with that format and the information written to stdout is just another %(message) part in that output. Just don't set a handler when you are in the AWS environment, or, disable propagation of the output to the root handler and live with all your messages being recorded as INFO messages by AWS; in the latter case your own formatter could include the levelname level information in the output. You can disable log propagation with logger.propagate = False, at which point your message is only going to be passed to your handler, not to to the root handler as well. Another option is to just rely on the AWS root logger configuration. According to this excellent reverse engineering blog post the root logger is configured with: logging.Formatter.converter = time.gmtime logger = logging.getLogger() logger_handler = LambdaLoggerHandler() logger_handler.setFormatter(logging.Formatter( '[%(levelname)s]\t%(asctime)s.%(msecs)dZ\t%(aws_request_id)s\t%(message)s\n', '%Y-%m-%dT%H:%M:%S' )) logger_handler.addFilter(LambdaLoggerFilter()) logger.addHandler(logger_handler) This replaces the time.localtime converter on logging.Formatter with time.gmtime (so timestamps use UTC rather than locatime), sets a custom handler that makes sure messages go to the Lambda infrastructure, configures a format, and adds a filter object that only adds aws_request_id attribute to records (so the above formatter can include it) but doesn't actually filter anything. You could alter the formatter on that han…
has comment: http://stackoverflow.com/comment/88823613
has comment: http://stackoverflow.com/comment/88822566
score: 44
answers question: http://stackoverflow.com/q/50909824

http://stackoverflow.com/q/50911868
has answer: http://stackoverflow.com/a/50917738
accepted answer: http://stackoverflow.com/a/50917738
type: Question
has body: My selenium code checks for a completed subroutine to be done by waiting on the site's title to change which worked perfectly. Code looks like this: waitUntilDone = WebDriverWait(session, 15).until(EC.title_contains(somestring)) However, this can fail sometimes since the site's landing page changes after manual website visits. The server remembers where you left off. This forces me to check for an alternate condition (website title = "somestring2). Here is what I came up with so far (also works as far as I can tell): try: waitUntilDone = WebDriverWait(session, 15).until(EC.title_contains(somestring)) # the old condition except: try: waitUntilDone = WebDriverWait(session, 15).until(EC.title_contains(somestring2)) # the new other condition which is also valid except: print "oh crap" # we should never reach this point Either one of these conditions is always true. I don't know which one thou. Is there any way to include an "OR" inside these waits or make the try/except block look nicer?
has title: Combine multiple Selenium waits using "OR"?
upvote count: 2
tagged with: python-2.7
answer count: 1
favorite count: 0
tagged with: python
tagged with: selenium-webdriver
score: 2
tagged with: selenium-chromedriver
type: AnsweredQuestion
downvote count: 0
tagged with: selenium

http://stackoverflow.com/q/50972328
has comment: http://stackoverflow.com/comment/88943641
favorite count: 0
has comment: http://stackoverflow.com/comment/88941132
has body: I am new to python, I was trying to convert my excel data into .txt format by pipe (|) delimited. I have around 250 rows in my excel, i was trying to get an output in the .txt file like below State|County|Zip|Address Newyork|Albany|10054|59th st,cass ave,apt9| illinois|lisle|60072|brook ave,steve blvd|
tagged with: python
has title: How to add '|' Pipe in each cell at end of the word in my excel sheet using python
type: UnansweredQuestion
score: 1
has answer: http://stackoverflow.com/a/50972560
has comment: http://stackoverflow.com/comment/88941189
has comment: http://stackoverflow.com/comment/88943634
type: Question
has comment: http://stackoverflow.com/comment/88941363
tagged with: pandas
has comment: http://stackoverflow.com/comment/88941117
upvote count: 1
answer count: 1
downvote count: 0

http://stackoverflow.com/q/50962803
type: UnansweredQuestion
has body: I'm new to PostgreSQL and I'm trying to populate a table with the content of a list of dictionaries built in Python, which looks like: diclist = [{'accession':'value', 'species':'value', 'seq':'value', 'length': 'value'}, {'accession':'value', 'species':'value', 'seq':'value', 'length': 'value'}, ...] 'seq' values are strings with sometimes > 300.000 characters... However, my data include genetic sequences which are pretty long so when I try to load these data into the table, PostgreSQL claims the following: index row requires 1460216 bytes, maximum size is 8191 Is there a way to increase the row index maximum size?? Or is there a way to compress the space required by my data? I know BioPython and BioSQL are made to handle genetic sequences, but they don't exactly match what I need... This is the function I've built for the moment (diclist is the list of dictionaries): def insert_biosequence(diclist): try: params = config() conn = psycopg2.connect(**params) cur = conn.cursor() cur.executemany("""INSERT INTO biosequence(accession, species, seq, length) VALUES (%(accession)s, %(species)s, %(seq)s, %(length)s)""", diclist) conn.commit() cur.close() except (Exception, psycopg2.DatabaseError) as error: print(error) finally: if conn is not None: conn.close() My CREATE TABLE command is the following: CREATE TABLE biosequence ( accession TEXT, species TEXT, seq TEXT PRIMARY KEY, length INTEGER ); I'm not using any INDEX commands, I think it's done by default by PostgreSQL... should I?
has comment: http://stackoverflow.com/comment/88924871
has comment: http://stackoverflow.com/comment/88922692
tagged with: python
score: 2
has answer: http://stackoverflow.com/a/54634663
has comment: http://stackoverflow.com/comment/88923047
has comment: http://stackoverflow.com/comment/88928221
type: Question
tagged with: indexing
has title: PostgreSQL: "index row requires 1460216 bytes, maximum size is 8191"
has comment: http://stackoverflow.com/comment/88929586
has comment: http://stackoverflow.com/comment/88928692
has comment: http://stackoverflow.com/comment/88924566
has comment: http://stackoverflow.com/comment/88922449
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/88923686
favorite count: 0
tagged with: postgresql
upvote count: 2

http://stackoverflow.com/comment/88786439
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50892944
has text: @DanD. The question specifically asks to ignore operator precedence
type: Comment

http://stackoverflow.com/q/50950593
has title: Can't figure how to web-scraping using beautifulsoup
has answer: http://stackoverflow.com/a/50950888
type: Question
has body: I am trying to scrape the info below from some web page. This is the full code: &lt;tr class="owner"&gt; &lt;td id="P184" class="ownerP" colspan="4"&gt; &lt;ul&gt; &lt;li&gt;&lt;span class="detailType"&gt;name:&lt;/span&gt;&lt;span class="detail"&gt;merry/span&gt;&lt;/li&gt; &lt;li&gt;&lt;a title="sendmessage" class="sendMessageLink" onclick="return openSendMessage('/sendMessage.php',20205" href="" tabindex="0"&gt;&lt;span&gt;&lt;/span&gt;sendmessage&lt;/a&gt;&amp;nbsp;&lt;span class="remark_soft"&gt;(by pm system)&lt;/span&gt;&lt;/li&gt; &lt;li&gt;&lt;span class="detailType"&gt;phone 1&lt;/span&gt;&lt;a class="detail" href="tel:0387362531"&gt;0387362531&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;span class="detailType"&gt;&lt;/span&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/td&gt; &lt;/tr&gt; I want to only get this info (the phone number): &lt;a class="detail" href="tel:0387362531"&gt;0387362531&lt;/a&gt; Here is my code, but it doesn't work: for details in soup.find_all(attrs= {"class": "detail"}): re_res = re.search(r"tel:\('.*?',(\d+)\)", details['href']) print(re_res)
possible better answer: http://stackoverflow.com/a/50950888
score: 0
accepted answer: http://stackoverflow.com/a/50950851
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/50950851
has answer: http://stackoverflow.com/a/50951031
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/50954901
answer count: 4
type: AnsweredQuestion

http://stackoverflow.com/q/51010319
tagged with: pandas
tagged with: http://stackoverflow.com/tag/html
tagged with: python
accepted answer: http://stackoverflow.com/a/51011418
type: AnsweredQuestion
has title: Extract Dataframe from nested html table structure?
has body: I wonder if there is a way to extract a dataframe from a nested Html structure/ code like the Pandas read_html() method. Here is the html from which i need to extract all columns that come after the column "action". Data.html: Central Repository Passadena-USA Fairfax Av. CMS action address machinie_id portal supplier created_by date portal deficit Load Value 1 Load Value 2 Load Value 3 Load Value 4 Load Value 5 Sub Load 1 Sub Load 2 Sub Load 3 Sub Load 4 Sub Load 5 Coordinates Area Code pending case id project details identification number APAC site_id state status timestamp FP 1195 Fairfax Avenue ZEBA 5841 NHE-9850 CMS Administrator 2017/6/19 687965 0 0 0 0 0 0 0 0 0 0 Relay 4-12 Avery J Tonal One B 2602700 Tertiary Node 0 Volume Sub < 1 passadena PA 2017/06/19 17:35:56 Here is my Python Code: import pandas as pd df = pd.read_html(Data.html) print(df[3]) # shouldn't the index 3 return all the columns that come after "CMS" i.e... columns : action,address, machine_id, portal.....till timestamp Here is the snap of my html page:
tagged with: dataframe
has answer: http://stackoverflow.com/a/51011418
type: Question
answer count: 1
score: 0

http://stackoverflow.com/comment/88747410
has text: Is that all the code? What is the error exactly? I can't see a problem or reproduce any error.
type: QuestionComment
comment on: http://stackoverflow.com/q/50872865
score: 4
type: Comment

http://stackoverflow.com/q/50899699
has title: ndarray .floor() and .ceil() methods missing?
has comment: http://stackoverflow.com/comment/88799494
has comment: http://stackoverflow.com/comment/88799536
has body: I'm processing a numpy.matrix and I'm missing the round-up and down functions. I.e. I can do: data = [[1, -20],[-30, 2]] np.matrix(data).mean(0).round().astype(int).tolist()[0] Out[58]: [-14, -9] Thus use .round(). But I cannot use .floor() or .ceil(). They are also not mentioned in the SciPy NumPy 1.14 reference. Why are these (quite essential) functions missing? edit: I've found that you can do np.floor(np.matrix(data).mean(0)).astype(int).tolist()[0]. But why the difference? Why is .round() a method and .floor not?
has comment: http://stackoverflow.com/comment/88799322
has comment: http://stackoverflow.com/comment/88799980
type: UnansweredQuestion
tagged with: numpy
has comment: http://stackoverflow.com/comment/88799266
upvote count: 0
has comment: http://stackoverflow.com/comment/88799408
linked to: http://stackoverflow.com/q/29120730
favorite count: 0
has comment: http://stackoverflow.com/comment/88799746
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/50901547
score: -1
has comment: http://stackoverflow.com/comment/88799681
answer count: 1
downvote count: 1

http://stackoverflow.com/q/50962324
has title: SSL - create client.crt and client.key for Python requests call
type: UnansweredQuestion
tagged with: python
has body: I'm new to Python and have been struggling with this for hours now, so I thought perhaps someone within the community would be able to help. I am trying to connect to a 3rd party enterprise server which is not a global CA. I have the following files my_csr.key (which I created myself) and is just the CSR that I sent to the 3rd party my_private.key (was created when making the my_csr.key above) their.pem (which 3rd party sent to me) my.p12 The steps I took are as follows: I was instructed by the 3rd party to create a CSR as step 1. Using openssl, I created my_csr.key (along with my_private.key) upon which I sent my_csr.key to the 3rd party The 3rd party then took my CSR and sent me the file 'their.pem' Using 'their.pem' and my_private.key, using openssl I created a .p12 which I can use successfully to make SSL verified HTTP requests in both C# and Java. The openssl command to create the p12 was openssl pkcs12 -in their.pem -inkey my_private.key -export -out my.p12 I've taken a look at python requests documentation:python requests but I'm still not clear on the openssl commands I need to make in order to create a client.crt and the client.key using the cert argument or alternatively the verify argument. What are the openssl commands I need to make given the files that I have in order to create a client.crt and client.key? Below is the code I'm trying to run in python: import requests r = requests.get(url, cert=('their.pem', 'my_private.key')) print(r.text) I have also tried with my private key password ie: r = requests.get(url, cert=('their.pem', 'my_private.key', 'private_key_password')) But in both of these calls I get prompted to input 'Enter PEM pass phrase' upon which I enter my_private.key password, but both variations fail with the following error: requests.packages.urllib3.exceptions.SSLError: ("bad handshake: Error([('SSL routines', 'ssl3_get_server_certificate', 'certificate verify failed')],)",)
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/88928792
type: Question
has comment: http://stackoverflow.com/comment/88929948
has comment: http://stackoverflow.com/comment/88929489
tagged with: ssl
has comment: http://stackoverflow.com/comment/89053535
tagged with: openssl
has comment: http://stackoverflow.com/comment/88931842
has comment: http://stackoverflow.com/comment/88929511
has comment: http://stackoverflow.com/comment/88932033
has comment: http://stackoverflow.com/comment/88934129
has comment: http://stackoverflow.com/comment/88924884
has answer: http://stackoverflow.com/a/50966925
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/88931678
favorite count: 0
has comment: http://stackoverflow.com/comment/88931211

http://stackoverflow.com/comment/89014087
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51010711
score: 3
has text: Why don't you check first which columns exist in your dataframe. For example, first try `print(df_can.columns)`.

http://stackoverflow.com/a/51043861
answers question: http://stackoverflow.com/q/50883703
score: 21
upvote count: 21
type: AcceptedAnswer
type: Answer
has body: The code you are looking for is here: class list : public object { public: PYBIND11_OBJECT_CVT(list, object, PyList_Check, PySequence_List) explicit list(size_t size = 0) : object(PyList_New((ssize_t) size), stolen_t{}) { if (!m_ptr) pybind11_fail("Could not allocate list object!"); } size_t size() const { return (size_t) PyList_Size(m_ptr); } detail::list_accessor operator[](size_t index) const { return {*this, index}; } detail::list_iterator begin() const { return {*this, 0}; } detail::list_iterator end() const { return {*this, PyList_GET_SIZE(m_ptr)}; } template &lt;typename T&gt; void append(T &amp;&amp;val) const { PyList_Append(m_ptr, detail::object_or_cast(std::forward&lt;T&gt;(val)).ptr()); } }; Also keep in mind that py::list inherits from py::object, which in turn inherits from py::handle (this also means that you are passing by reference). In my experience, there is very little documentation for this kind of usage, and reading the code is your best bet. We can see from the class definition that we can use the member functions size, operator[], begin, end (C++ iterators!) and append (templated!). If this is not enough, you can use attr to access python attributes (including methods). Here is an example: Python code (some_python.py): import cppimport cpp = cppimport.imp("some_cpp") l = [1,2,3,4,5] cpp.test(l) print('after C++', l) cpp.float_cast(l) C++ code (some_cpp.cpp): /* &lt;% setup_pybind11(cfg) %&gt; */ #include &lt;pybind11/pybind11.h&gt; #include &lt;iostream&gt; #include &lt;string&gt; namespace py = pybind11; void test(py::list l) { l.attr("pop")(); std::cout &lt;&lt; "List has length " &lt;&lt; l.size() &lt;&lt; std::endl; for (py::handle obj : l) { // iterators! std::cout &lt;&lt; " - " &lt;&lt; obj.attr("__str__")().cast&lt;std::string&gt;() &lt;&lt; std::endl; } l.append(10); // automatic casting (through templating)! } void float_cast(py::list l) { float f = l.cast&lt;float&gt;(); } PYBIND11_MODULE(some_cpp, m) { m.def("test", &amp;test); m.…
accepted answer of: http://stackoverflow.com/q/50883703
downvote count: 0

http://stackoverflow.com/q/50959350
favorite count: 0
has answer: http://stackoverflow.com/a/50959376
upvote count: 5
tagged with: pivot
tagged with: pivot-table
tagged with: python
type: AnsweredQuestion
downvote count: 0
has body: I'm attempting to create cross-table / pivot table in pandas: import pandas as pd import numpy as np df = pd.DataFrame({'foo': ['one', 'one', 'one', 'two', 'two','two'],'bar': ['A', 'A', 'C', 'B', 'B', 'C']}) however my attempts come up as: pd.pivot(df, index='foo', columns='bar') TypeError: pivot_simple() got multiple values for argument 'index' and the second: pd.pivot_table(data = df, values = 'bar', index = 'bar', columns = 'foo', aggfunc=lambda x: np.count_nonzero(x)) foo one two bar A 4.0 NaN B NaN 4.0 C 2.0 2.0 The output I'm looking to achieve is the below: A B C one 2 1 two 2 1
linked to: http://stackoverflow.com/q/47152691
type: Question
tagged with: numpy
score: 5
has title: create pivot table in pandas using count of occurrence of value
accepted answer: http://stackoverflow.com/a/50959376
tagged with: pandas
answer count: 1
duplicate of: http://stackoverflow.com/q/47152691

http://stackoverflow.com/a/50867681
type: Answer
answers question: http://stackoverflow.com/q/50867478
has body: &gt;&gt;&gt; import bisect &gt;&gt;&gt; someList = ["a", "b", "d"] &gt;&gt;&gt; bisect.insort(someList,'c') &gt;&gt;&gt; someList ['a', 'b', 'c', 'd'] &gt;&gt;&gt;
score: 0

http://stackoverflow.com/q/50873976
has answer: http://stackoverflow.com/a/50874566
has title: How to safely unpack dict in python?
has comment: http://stackoverflow.com/comment/88749371
upvote count: 3
accepted answer: http://stackoverflow.com/a/50874478
answer count: 3
has answer: http://stackoverflow.com/a/50874079
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50874478
possible better answer: http://stackoverflow.com/a/50874566
tagged with: python
has body: I have a wrapper class - it's an abstraction that I return from backend to frontend. from typing import NamedTuple class NewsItem(NamedTuple): id: str title: str content: str service: str published_at: datetime @classmethod def from_payload(cls, payload) -&gt; 'NewsItem': return cls(**payload) For example, when I get data from elastic I convert it to NewsItem: return [NewsItem.from_payload(hit['_source']) for hit in result['hits']['hits']] The problem is I don't want to fail because of unknown fields that can come from elastic. How to ignore them (or put into a separate dedicated attribute list NewsItem.extra)?
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/88750286
downvote count: 0
has comment: http://stackoverflow.com/comment/88749440
type: Question

scaling
tags question: http://stackoverflow.com/q/50910867
type: Tag
tag name: scaling

http://stackoverflow.com/comment/88898056
comment on: http://stackoverflow.com/a/50947775
score: 0
type: AnswerComment
has text: @MattiaVicari - As a workaround you can probably read the values from the newly generated sheet and write them to another sheet. XlsWriter is a library for this. See some examples - https://github.com/Vitosh/Python_personal
type: Comment

http://stackoverflow.com/q/50939825
score: 2
downvote count: 0
favorite count: 0
tagged with: apache-beam
tagged with: python
answer count: 0
upvote count: 2
type: UnansweredQuestion
has body: My task is equivalent to: given a stream of letters (each letter is associated with the author) build the low-latency histogram of ngrams within a fixed window, assuming that correct ngram consists of a sequence of letters from the same author. My pipeline looks like: | 'Extract and assign timestamps' &gt;&gt; Map(..) | 'Extract author from message' &gt;&gt; Map(..) | 'Assign author as key' &gt;&gt; Map(lambda x: (x.author, x)) # :(author,chr) | 'Assign windows' &gt;&gt; WindowInto(window.FixedWindows(5*60), trigger=Repeatedly(AfterAny( AfterCount(2), AfterWatermark())), accumulation_mode=ACCUMULATING) | 'Group letters by author' &gt;&gt; GroupByKey() # :(author,[chr]) | 'Extract many ngrams from every substring' &gt;&gt; ParDo(..) # :[(author, ngram)] | 'Re-key by ngrams' &gt;&gt; Map(lambda x: (x.ngram, 1)) # :(ngram,1) | 'Group again, now by ngrams' &gt;&gt; GroupByKey() # :(ngram,[1]) | 'Sum ngrams counts' &gt;&gt; Map(lambda x: (x[0], sum(x[1]))) # :(ngram,count) | 'Re-key by window' &gt;&gt; ParDo(..) # :(window, (ngram,count)) | 'Group within window' &gt;&gt; GroupByKey # :(window, [(ngram,count)]) My goal is to receive a single output message for every two input messages such that output message summarizes ngram-statistics between: the start of the current 5-minute interval in event-time, and current moment in processing-time. Without AfterCount-trigger, everything works well: each window only has a single pane. I get a single histogram-message for every 5-minutes in event-time. This pipeline doesn't really work as intended with multiple panes per window, because I have 3 GBKs here and each gets triggered by panes, and does so with accumulation. For example: after first two characters come in (let's say ('a','author1') and ('b','author1'), panes trigger in all GBKs; I get an output message which correctly summarizes all ngrams seen so far, which may look like ('[0,300)', [('ab', 1)]); now I have: buffered characters in front of the first 'Group letters by wo…
tagged with: google-cloud-dataflow
has title: How to control accumulation mode when using sequential GroupByKey? Or other idiomatic approach?
type: Question

http://stackoverflow.com/a/50886750
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88777633
type: Answer
accepted answer of: http://stackoverflow.com/q/50886506
has body: Your self.logger has no handler(s), so it actually only delegates ("propagate") to it's parent(s). If all parents levels are above DEBUG, then the message will be discarded indeed. Also, handlers have a level too, so even if a logger's level is set to DEBUG, the handler(s) will still filter message based on their own level. This allow to have different handlers for different levels for a same logger, but can also result in messages being discarded. You did not provide enough informations (here your whole logging config) to positively tell this is the cause of your problem, but given the problem's description it's the most obvious culprit.
answers question: http://stackoverflow.com/q/50886506
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/q/50927555
type: Question
has answer: http://stackoverflow.com/a/50928105
tagged with: python
upvote count: 2
answer count: 1
tagged with: evolutionary-algorithm
has body: I have this code for nsga3(evolutionary algorithm) but I get the error 'numpy.ndarray' object has no attribute 'fitness'.Generates reference points for NSGA-III selection. This code is based onjMetal NSGA-III implementation &lt;https://github.com/jMetal/jMetal&gt;_. Please help to remove this error import copy import random import numpy as np from deap import tools class ReferencePoint(list): # A reference point exists in objective space an has a set of individuals associated with it def __init__(self, *args): list.__init__(self, *args) self.associations_count = 0 self.associations = [] def generate_reference_points(num_objs, num_divisions_per_obj): def gen_refs_recursive(work_point, num_objs, left, total, depth): if depth == num_objs - 1: work_point[depth] = left/total ref = ReferencePoint(copy.deepcopy(work_point)) return [ref] else: res = [] for i in range(left): work_point[depth] = i/total res = res + gen_refs_recursive(work_point, num_objs, left-i, total, depth+1) return res print(gen_refs_recursive([0]*num_objs, num_objs, num_objs*num_divisions_per_obj, num_objs*num_divisions_per_obj, 0)) def find_ideal_point(individuals): 'Finds the ideal point from a set individuals.' current_ideal = [np.infty] * len(individuals[0].fitness.values) # Here th error is coming for ind in individuals: # Use wvalues to accomodate for maximization and minimization problems. current_ideal = np.minimum(current_ideal, np.multiply(ind.fitness.wvalues, -1)) print("Ideal POint is\n",current_ideal) global individulas individulas=np.random.rand(10,4) generate_reference_points(2, 4) find_ideal_point(individulas)
type: UnansweredQuestion
score: 2
tagged with: deap
downvote count: 0
favorite count: 0
has title: 'numpy.ndarray' object has no attribute 'fitness'

http://stackoverflow.com/comment/88968835
score: 0
type: AnswerComment
type: Comment
has text: @Jpp so are you saying it is strictly better to perform `play.applymap(my_func)` alongside `def my_func(): return newdict[x]` compared to `play.applymap(lambda x: newdict[x])` because to me it looks like the same thing
comment on: http://stackoverflow.com/a/50965424

http://stackoverflow.com/a/50965503
has comment: http://stackoverflow.com/comment/88928976
answers question: http://stackoverflow.com/q/50965349
type: Answer
has body: I would suggest to use print(line, file=f) instead, may the optional seperator is set to end="some sign" if you want... EDIT Sorry for writing such complicated: Also print has the ability to "write" into files. It also offers an option for alternative ending see above - For your case it would be: f = open("Answers.txt","a", newline="\n",encoding='utf-8') for i in tqdm(data['answers_body']): line = i.replace('\n','') print(line, file=f) f.close() if wanted or needed for other cases with print(line, file=f, end='\t') instead of a newline a tab is the last sign and the next print() continues after the tab
downvote count: 1
has comment: http://stackoverflow.com/comment/88927636
upvote count: 0
score: -1

hierarchical-clustering
tags question: http://stackoverflow.com/q/50909416
tag name: hierarchical-clustering
type: Tag

http://stackoverflow.com/a/51013976
score: 0
answers question: http://stackoverflow.com/q/50999712
has body: Have you looked into a Python scheme for Global variables, even if a script terminates? I hava a feeling that this issue was raised and solved by the powers that be. Or, perhaps you set up a separate script which contains the variable value and call on it from the other script?
type: Answer

http://stackoverflow.com/comment/120427209
comment on: http://stackoverflow.com/a/50883628
has text: Thanks for helping me get started! There's also an example of getting started with the barh plot here: https://matplotlib.org/stable/gallery/lines_bars_and_markers/barh.html#sphx-glr-gallery-lines-bars-and-markers-barh-py
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50881887
has body: I currently have a python file that, along with an external parameter, will analyze data when run inside of timestamped folders (e.g. I move readA3200dat.py and ParameterFile.ini into a folder named 201806151534, etc.). However I want to use argv to eliminate the need to constantly move these files in and out of folders. Because my code is pretty long, I was hoping to be able to write a function called main that would basically move into &lt;FILENAME&gt; upon entering python readA3200dat.py &lt;FILENAME&gt; to the command line and execute the code as usual. Also, since I require the parameter folder, ParameterFile.ini to be in the same directory, I was hoping for this to be moved, but since it is always the same name, I don't need argv. This is my code (cut down a bit): Note: the code is only relevant to show general coding structure - I am including it strictly because I am unsure where in the code I am supposed to include the argv syntax. import os import numpy as np import re class DataStructure(object): #Data File Class '''Object to contain data file information parsed in readA3200dat''' def __init__(self): self.AxisName = None ## more like this ## def readA3200dat(filename): ''' Takes in the file path of dat file Returns Data structure with information from dat file ''' if filename == None: # if filename is None, return None print("\nWARNING: Filename set to None, returning None") return None, None try: # try to open file f = open(filename, 'r') #open the specified file except IOError as e: print ("\nI/O error({0}): {1}\n".format(e.errno, e.strerror)) raise fileLine = f.readline() #read data in to fileLine list ### Data Reading and Analysis ## cur_dir = os.getcwd() folders = os.listdir(cur_dir) for i in folders: name, ext = os.path.splitext(i) if ext == '.dat': data = readA3200dat(i) ## find average values, std, etc. ## try: from configparser import ConfigParser except ImportError: from ConfigParser import ConfigParser config = ConfigParser() config.read('Param…
tagged with: argv
downvote count: 0
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/88766434
has comment: http://stackoverflow.com/comment/88767117
type: Question
has comment: http://stackoverflow.com/comment/88766513
tagged with: python
has answer: http://stackoverflow.com/a/50882406
upvote count: 1
answer count: 1
type: UnansweredQuestion
has title: Using argv to change directory upon running python file

http://stackoverflow.com/q/50916303
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88832732
answer count: 0
tagged with: matplotlib
upvote count: 1
has comment: http://stackoverflow.com/comment/88832940
downvote count: 1
type: Question
tagged with: numpy
has title: Building contour lines in Python
has body: I need to plot a contour plot (similar to this example) according to the data from the text file. I'm building a coordinate grid. Z values are known only on the main diagonal. To find the values in the remaining points advised extrapolation. How do I extrapolate from the resulting grid? Link to file: https://drive.google.com/open?id=1l4cEVo6SYunwnMNrIIjBPcIe3YxaGsKz Here is a small snippet of code that helps to load this file into a Pandas DataFrame: import pandas as pd df = pd.read_fwf(r'D:\download\image2015010100.col2', skiprows=[1], na_values=[99999.9]) d = { 'YYYY': 'year', 'MM':'month', 'DD':'day', 'HH':'hour', 'MM.1':'minute', 'SS':'second', } df = df.rename(columns=d) df.index = pd.to_datetime(df.iloc[:, :6]) df = df.iloc[:, 6:] This is how this DF looks like: In [171]: df Out[171]: NAL X NAL Y NAL Z LYR X LYR Y LYR Z HOR X HOR Y ... TAR Y TAR Z SUW X SUW Y SUW Z BRZ X BRZ Y BRZ Z 2015-01-01 00:00:00 7154.0 781.9 54297.5 7388.6 1046.0 54320.9 7821.3 1002.6 ... 2479.3 49164.9 -125.4 -114.8 -61.0 18.9 62.6 45.0 2015-01-01 00:00:10 7155.7 782.4 54298.5 7388.3 1046.0 54321.1 7821.3 1002.6 ... 2479.2 49164.9 -125.3 -114.8 -61.0 19.0 62.4 45.0 2015-01-01 00:00:20 7154.3 783.4 54296.8 7388.6 1045.8 54321.1 7821.3 1002.4 ... 2479.1 49165.0 -125.3 -114.9 -61.0 19.0 62.4 45.0 2015-01-01 00:00:30 7153.8 781.9 54296.6 7388.4 1045.5 54321.1 7821.1 1002.2 ... 2479.1 49165.0 -125.3 -115.0 -61.1 19.1 62.3 45.0 2015-01-01 00:00:40 7153.5 782.0 54299.5 7388.4 1045.0 54320.9 7821.1 1001.9 ... 2478.9 49165.0 -125.3 -115.1 -61.1 19.1 62.2 45.0 ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... 2015-01-01 23:59:10 7133.9 768.5 54474.8 7326.1 1082.7 54537.2 7746.0 1058.9 ... 2513.5 49151.7 -127.4 -86.8 -65.4 16.8 94.5 36.3 2015-01-01 23:59:20 7134.1 767.0 54471.9 7328.1 1076.6 54535.9 7743.4 1050.7 ... 2513.4 49151.7 -127.5 -86.8 -65.4 16.8 94.5 36.3 2015-01-01 23:59:30 7133.6 766.0 54468.4 7328.5 1071.4 54534.2 7740.6 1044.8 ... 2513.4 49151.6 -127.6 -86.8 -6…
score: 0
has comment: http://stackoverflow.com/comment/88832729
tagged with: pandas

http://stackoverflow.com/a/50927936
answers question: http://stackoverflow.com/q/50927787
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50927787
score: 2
has body: Using pd.DataFrame.iloc, you can use integer indexers to isolate part of your dataframe. Given a dataframe df: res = df.iloc[5:, 2] Note that indexing in Python begins with 0, so this is the 6th row onwards (or index 5 onwards). Similarly, 2 represents the 3rd row (or column with index 2). The indexing syntax is similar to Python list or NumPy array indexing. Since we specify only one column index, the output will be a pd.Series object, which can be seen as a column. If you specified multiple column indices, your output will be another dataframe. In general, iteration isn't the best option with Pandas. You should aim to use vectorised operations. There are plenty of examples in the Pandas docs demonstrating vectorised calculations. If your column index consists of strings, you can use get_loc to extract an integer location given a name: res = df.iloc[5:, df.columns.get_loc('some_name')]
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/88881335

http://stackoverflow.com/a/50940622
has body: Here is my 'settings.py' file.I did add 'www.mysticprogrammer.net' already. I've even added it in the 'allowed_hosts' of 'request.py' file,as mentioned in the exception location. I've also added 'service gunicorn restart',in my Putty CLI,after connecting to my droplet in DigitalOcean. The link to the tutorial I followed,to reach till this point is this :https://www.youtube.com/watch?v=FNQxxpM1yOs&amp;list=PLQVvvaa0QuDeA05ZouE4OzDYLHY-XH-Nd And,the particular video is : https://www.youtube.com/watch?v=Y-CT_l1dnVU&amp;list=PLQVvvaa0QuDeA05ZouE4OzDYLHY-XH-Nd&amp;index=11
type: Answer
answers question: http://stackoverflow.com/q/50877547
score: 0

gaps-in-data
tag name: gaps-in-data
type: Tag
tags question: http://stackoverflow.com/q/50942418

knn
tags question: http://stackoverflow.com/q/50993867
tag name: knn
type: Tag
tags question: http://stackoverflow.com/q/50961658
tags question: http://stackoverflow.com/q/50979395
tags question: http://stackoverflow.com/q/50896495

http://stackoverflow.com/comment/88894474
has text: `result['subfolders'] = some_dictionary` after the loop. Build that inner dictionary within the loop... You're already building a dictionary. `result[label]` and `{'id' : folderTypeId}`
comment on: http://stackoverflow.com/q/50948320
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50968163
tagged with: python
type: Question
has body: My bot sends a message and two buttons. After the user clicks the + or - button, I want this built-in keyboard to disappear. Here's how I make the buttons: markup_command = types.InlineKeyboardMarkup() btn_p1 = types.InlineKeyboardButton(text='+', callback_data='like') btn_p2 = types.InlineKeyboardButton(text='-', callback_data='disslike') markup_command.add(btn_p1, btn_p2) bot.send_message(message.chat.id, 'choose +/-', reply_markup=markup_command) that's what will happen if you press the button: @bot.callback_query_handler(func=lambda call: True) def callback_inline(call): if call.data == 'like': bot.send_message(call.from_user.id, 'like') How can I make this buttons to disappear after the click?
has answer: http://stackoverflow.com/a/51957499
tagged with: telegram-bot
score: 0
has title: How can I remove inline keyboard after click? (python)
answer count: 1
tagged with: python-3.x
tagged with: python-telegram-bot
tagged with: telegram
type: UnansweredQuestion

http://stackoverflow.com/comment/88938935
type: Comment
comment on: http://stackoverflow.com/q/50971075
has text: Check out the following threads: https://stackoverflow.com/questions/1015592/why-is-self-in-python-objects-immutable https://stackoverflow.com/questions/1216356/is-it-safe-to-replace-a-self-object-by-another-object-of-the-same-type-in-a-meth
score: 0
type: QuestionComment

http://stackoverflow.com/comment/89005396
has text: No, see. They want to merge on common months and then have the merged result exist as separate rows. They've even used an explicit indicator column.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51005946

http://stackoverflow.com/a/52953129
has body: try: jupyter notebook --no-browser
score: 23
upvote count: 23
answers question: http://stackoverflow.com/q/50882266
downvote count: 0
type: Answer

right-click
tags question: http://stackoverflow.com/q/50868751
tag name: right-click
type: Tag

http://stackoverflow.com/q/50865274
favorite count: 0
upvote count: 3
has answer: http://stackoverflow.com/a/55316538
type: UnansweredQuestion
tagged with: pipfile
downvote count: 1
tagged with: heroku
score: 2
has title: Pipfile.lock is out of date.
linked to: http://stackoverflow.com/q/49460486
type: Question
duplicate of: http://stackoverflow.com/q/49460486
has body: Trying to push a python script to heroku, It's complaining that my pipfile.lock is out of date. I'm using pipenv to manage dependencies, and I've tried running pipenv lock to update the lock file to no avail. Counting objects: 11, done. Delta compression using up to 4 threads. Compressing objects: 100% (11/11), done. Writing objects: 100% (11/11), 2.39 KiB | 817.00 KiB/s, done. Total 11 (delta 3), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----&gt; Python app detected remote: -----&gt; Found python-3.6.5, removing remote: -----&gt; Installing python-2.7.15 remote: -----&gt; Installing pip remote: -----&gt; Installing dependencies with Pipenv 11.8.2. remote: Your Pipfile.lock (c7d2bf) is out of date. Expected: (29c137). remote: Aborting deploy. remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to bot_testbed. remote: Warning: Your console font probably doesn't support Unicode. If you experience strange characters in the output, consider switching to a TrueType font such as Consolas! To https://git.heroku.com/peopleoftherealms.git ! [remote rejected] master -&gt; master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/bot_testbed.git
has comment: http://stackoverflow.com/comment/109996092
answer count: 1
tagged with: python

http://stackoverflow.com/q/50948320
answer count: 1
has comment: http://stackoverflow.com/comment/88894474
accepted answer: http://stackoverflow.com/a/50948683
has comment: http://stackoverflow.com/comment/88894368
has comment: http://stackoverflow.com/comment/88894313
downvote count: 0
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/88894153
tagged with: http://stackoverflow.com/tag/xml
favorite count: 0
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/50948683
type: Question
has body: I made a python script and need to have some parameters in an XML. So here is the XML : <ROOT> <FOLDERTYPE_ID> FOURNISSEUR 2 Administratif 4 Commandes 5 Factures 6 </FOLDERTYPE_ID> <FOLDERTYPE_ID> CLIENT 3 Administratif 4 Commandes 5 Factures 6 Logistique 7 </FOLDERTYPE_ID> For now, I'm just capable to get the "name" and "ID" like the following : {'FOURNISSEUR': {'id': '2'}, 'CLIENT': {'id': '3'}} But I need to have all of the subfolders, in a dict like this : {'FOURNISSEUR': {'id': '2', 'subfolders' : {'Administratif':'4','Commandes':'5','Factures':'6'}}, 'CLIENT': {'id': '3', 'subfolders' : {'Administratif':'4','Commandes':'5','Factures':'6','Logistique':'7'}} Here is the piece of code I have for now : def getFolderTypeArray(fileName): result = {} with open(fileName, 'rb') as config_file: content = config_file.read() config = BeautifulSoup(content, "lxml") folderTypesId = config.find_all('foldertype_id') for folderType in folderTypesId: label = folderType.find('name').string folderTypeId = folderType.find('id').string result[label] = {'id' : folderTypeId}
upvote count: 1
tagged with: python
has title: PYTHON How to make "associative array"
has comment: http://stackoverflow.com/comment/88894371

http://stackoverflow.com/q/50957861
has comment: http://stackoverflow.com/comment/88913276
tagged with: web-scraping
has body: import requests import re from bs4 import BeautifulSoup #The website I like to get, converts the contents of the web page to lxml format base_url = "https://festivalfans.nl/event/dominator-festival" url = requests.get(base_url) soup = BeautifulSoup(url.content, "lxml") #Modifies the given string to look visually good. Like this: #['21 / JulZaterdag2018'] becomes 21 Jul 2018 def remove_char(string): #All blacklisted characters and words blacklist = ["/", "[", "]", "'", "Maandag", "Dinsdag", "Woensdag", "Donderdag", "Vrijdag", "Zaterdag", "Zondag"] #Replace every blacklisted character with white space for char in blacklist: string = string.replace(char,' ') #Replace more than 2 consecutive white spaces string = re.sub("\s\s+", " ", string) #Gets the date of the festival I'm interested in def get_date_info(): #Makes a list for the data raw_info = [] #Adds every "div" with a certain name to list, and converts it to text for link in soup.find_all("div", {"class": "event-single-data"}): raw_info.append(link.text) #Converts list into string, because remove_char() only accepts strings raw_info = str(raw_info) #Modifies the string as explained above final_date = remove_char(raw_info) #Prints the date in this format: 21 Jul 2018(example) print(final_date) get_date_info() Hi there! So I'm currently working on a little webscraping project. I thought I had a good idea and I wanted to get more experienced with Python. What it basically does is it gets festival information like date, time and price and puts it in a little text file. I'm using BeautifulSoup to navigate and edit the web page. Link is down there! But now I'm kinda running into a problem. I can't figure out what's wrong. Maybe I'm totally looking over it. So when I run this program it should give me this: 21 Jul 2018. But instead it returns 'None'. For some reason every character in the string gets removed. I tried running remove_char() on its own, with the same list(converted it to string first) as input. This worked…
type: Question
has answer: http://stackoverflow.com/a/50957956
has answer: http://stackoverflow.com/a/50957949
score: 0
has comment: http://stackoverflow.com/comment/88913236
answer count: 3
tagged with: beautifulsoup
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50958034
type: UnansweredQuestion
has title: Why doesn't this function return the same output in both situations(webscraping project)?
tagged with: python

http://stackoverflow.com/comment/88988456
score: 0
type: Comment
type: QuestionComment
has text: As it turns out, yes, no unittests. :-( There's a fairly complex tox.ini, a tests tree, and test files, but no actual tests in them. I keep thinking I must be blind and just not seeing some files.
comment on: http://stackoverflow.com/q/50977613

http://stackoverflow.com/comment/88938866
type: Comment
type: QuestionComment
has text: No it doesn't show, even with `{{ form }}`. Edited my question for LexiconForm. Also corrected indent in my post as you suggested.
comment on: http://stackoverflow.com/q/50970667
score: 0

http://stackoverflow.com/comment/88862580
comment on: http://stackoverflow.com/a/50930916
has text: Since you're running graph-tool and jupyter using Docker it's better to know a little bit more about how Docker works.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/50936634
answer count: 1
has comment: http://stackoverflow.com/comment/88872071
accepted answer: http://stackoverflow.com/a/50937032
type: AnsweredQuestion
favorite count: 0
has comment: http://stackoverflow.com/comment/88872190
type: Question
has comment: http://stackoverflow.com/comment/88871839
tagged with: python
has title: Override class attributes in Python
upvote count: 6
has body: Ultimately looking to create a random music scale generator. I’m working on building classes for each mode and wanted to use major or minor scales as a True or False boolyan as a starting point. Can someone tell me where I’m off with overriding this attribute for Mode2? Here is my code: class Mode(): def __init__(self,title,major): self.title = title self.major= True def __str__(self): return "Title: {}, Major: {}".format(self.title,self.major) Mode1 = Mode("Ionian", "Major") print(Mode1) class Mode2(Mode): def major(self): print(False) Mode2 = Mode("Dorian", "Minor") print(Mode2)
score: 4
has answer: http://stackoverflow.com/a/50937032
has comment: http://stackoverflow.com/comment/128484868
downvote count: 2

http://stackoverflow.com/q/50860166
favorite count: 0
has body: How can I write a script in Windows that runs the following command? autoflake -i -r --remove-all-unused-imports %file_directory% My script looks like this: file_directory = input("Enter directory name to run autoflake: ") def autoflake_run(): try: # I would like to run the command here. except: print("Path file error. Please make sure directory exists.") autoflake_run()
type: Question
upvote count: 1
tagged with: python
has title: Write a script that runs a command with arguments
accepted answer: http://stackoverflow.com/a/50860253
answer count: 1
has answer: http://stackoverflow.com/a/50860253
type: AnsweredQuestion
tagged with: windows
downvote count: 0
score: 1

http://stackoverflow.com/q/51001182
has answer: http://stackoverflow.com/a/51001397
tagged with: python
answer count: 4
has body: I need to write a program that takes a line of input of the form «number1»+«number2» and outputs the sum of the two numbers. The following doesn't work: S = input() s_len = len(S) for i in range(0, s_len): if i == '+': num1 = int(S[:i]) num2 = int(S[:i]) add = num1+num2 print(add)
has comment: http://stackoverflow.com/comment/89006824
score: -4
has comment: http://stackoverflow.com/comment/88996173
upvote count: 1
has answer: http://stackoverflow.com/a/51001236
has answer: http://stackoverflow.com/a/51001523
type: AnsweredQuestion
has title: Sum of two numbers using a for loop
accepted answer: http://stackoverflow.com/a/51001397
possible better answer: http://stackoverflow.com/a/51001523
downvote count: 5
has comment: http://stackoverflow.com/comment/88996154
type: Question
has comment: http://stackoverflow.com/comment/88996188
favorite count: 0
has comment: http://stackoverflow.com/comment/88996216
has answer: http://stackoverflow.com/a/51002271

http://stackoverflow.com/a/50946027
has comment: http://stackoverflow.com/comment/88895666
has comment: http://stackoverflow.com/comment/88895375
has comment: http://stackoverflow.com/comment/89053757
has comment: http://stackoverflow.com/comment/88997597
score: 0
has comment: http://stackoverflow.com/comment/89053831
has body: Based on the discussion, I think you can extract the time with a function below and compare it later in if statement: from datetime import datetime def extract_seconds(text: str): pat = '%Mm%Ss' # convenient reference: http://strftime.org/ try: x = datetime.strptime(text, pat) except ValueError: raise ValueError('Cannot extract time from {} with {}'.format(x, pat)) return x.minute * 60 + x.second assert extract_seconds('30m34s') == 1834 If you are willing to work with datetime object, this is even shorter: def extract(text: str): pat = '%Mm%Ss' # convenient reference: http://strftime.org/ try: return datetime.strptime(text, pat).time() except ValueError: raise ValueError('Cannot extract time from {} with {}'.format(x, pat))
type: Answer
answers question: http://stackoverflow.com/q/50906387
has comment: http://stackoverflow.com/comment/88896736
has comment: http://stackoverflow.com/comment/102751039

http://stackoverflow.com/comment/88963440
type: QuestionComment
comment on: http://stackoverflow.com/q/50982315
has text: My question is actually not to get hypernym of word or "Get common hypernym of two words" . But basically I don't know the actual title for my desired output. thats why I gave an example. If you understand my question's example could you please help me to get the title for this question? @WolfgangK
score: 0
type: Comment

http://stackoverflow.com/a/50962674
has comment: http://stackoverflow.com/comment/88927016
has comment: http://stackoverflow.com/comment/88922652
has body: For update the record you have to find it first!! model 'ecole.partner.school' must not be the Transient model. Please create domain that suits for your requirement instead of []. @api.multi def set_student_level(self): domain = [] for record in self: for student in record.student_ids: update_student = self.env['ecole.partner.school'].search(domain,limit=1) if update_student: partner_id = update_student.partner_id school_year = update_student.school_year school_name = update_student.school_name half_pension = update_student.half_pension nursery = update_student.nursery student.school_year = school_year student.school_level = self.school_level student.school_name = school_name vals = {'partner_id': partner_id, 'nursery': nursery} res = update_student.create(vals) return True
type: Answer
has comment: http://stackoverflow.com/comment/88926275
has comment: http://stackoverflow.com/comment/88926436
has comment: http://stackoverflow.com/comment/88927071
answers question: http://stackoverflow.com/q/50962097
has comment: http://stackoverflow.com/comment/88923029
score: 0

http://stackoverflow.com/comment/88776602
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50887604
has text: sorry, it worked. I am working on pycharm and it says that this is an error but when i run the code its working

http://stackoverflow.com/q/50983386
answer count: 3
tagged with: pandas
downvote count: 0
accepted answer: http://stackoverflow.com/a/50983921
favorite count: 0
tagged with: aggregate
upvote count: 2
possible better answer: http://stackoverflow.com/a/50983775
has body: I am new to Python. How do I sum data based on date and plot the result? I have a Series object with data like: 2017-11-03 07:30:00 NaN 2017-11-03 09:18:00 NaN 2017-11-03 10:00:00 NaN 2017-11-03 11:08:00 NaN 2017-11-03 14:39:00 NaN 2017-11-03 14:53:00 NaN 2017-11-03 15:00:00 NaN 2017-11-03 16:00:00 NaN 2017-11-03 17:03:00 NaN 2017-11-03 17:42:00 800.0 2017-11-04 07:27:00 600.0 2017-11-04 10:10:00 NaN 2017-11-04 11:48:00 NaN 2017-11-04 12:58:00 500.0 2017-11-04 13:40:00 NaN 2017-11-04 15:15:00 NaN 2017-11-04 16:21:00 NaN 2017-11-04 17:37:00 500.0 2017-11-04 21:37:00 NaN 2017-11-05 03:00:00 NaN 2017-11-05 06:30:00 NaN 2017-11-05 07:19:00 NaN 2017-11-05 08:31:00 200.0 2017-11-05 09:31:00 500.0 2017-11-05 12:03:00 NaN 2017-11-05 12:25:00 200.0 2017-11-05 13:11:00 500.0 2017-11-05 16:31:00 NaN 2017-11-05 19:00:00 500.0 2017-11-06 08:08:00 NaN I have the following code: # load packages import pandas as pd import matplotlib.pyplot as plt # import painkiller data df = pd.read_csv('/Users/user/Documents/health/PainOverTime.csv',delimiter=',') # plot bar graph of date and painkiller amount times = pd.to_datetime(df.loc[:,'Time']) ts = pd.Series(df.loc[:,'acetaminophen'].values, index = times, name = 'Painkiller over Time') ts.plot() This gives me the following line(?) graph: It's a start; now I want to sum the doses by date. However, this code fails to effect any change: The resulting plot is the same. What is wrong? ts.resample('D',closed='left', label='right').sum() ts.plot() I have also tried ts.resample('D').sum(), ts.resample('1d').sum(), ts.resample('1D').sum(), but there is no change in the plot. Is .resample even the correct function? I understand resampling to be sampling from the data, e.g. randomly taking one point per day, whereas I want to sum each day's values. Namely, I'm hoping for some result (based on the above data) like: 2017-11-03 800 2017-11-04 1600 2017-11-05 1900 2017-11-06 NaN
tagged with: python
has answer: http://stackoverflow.com/a/50983921
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/50983775
has answer: http://stackoverflow.com/a/50984059
type: Question
has title: How do I sum time series data by day in Python? resample.sum() has no effect
tagged with: sum
tagged with: dataframe
linked to: http://stackoverflow.com/q/39400115

http://stackoverflow.com/a/50934675
answers question: http://stackoverflow.com/q/50934561
has body: There's no cross-platform way to do what you want, of course. Python is just passing these values through to the underlying C API. So, on a platform with a complete BSD sockets API including the packet interface, you can just use AF_PACKET and the other appropriate flags. (I think you'd want ETH_P_ALL or ETH_P_802_2 rather than IPPROTO_RAW, or you might want SOCK_DGRAM… anyway, read your platform's man packet and figure it out based on what you actually need to do.) On Linux, at least most of these flags should be available on the SOCKET module; on other Unixes, they often don't get picked up, so you have to manually look them up in the system headers and use hardcoded constant ints in your code. Unfortunately, if you're on Windows, this doesn't do any good. While WinSock has a feature they call TCP/IP Raw Sockets, accessed via SOCK_RAW, and recent versions of Python do expose this, it's just an emulation of a small subset of what actual BSD sockets implementations can do, and doesn't offer any way to go below the IP level (hence the name of the feature). Microsoft's solution to this used to be that you'd write a TDI provider with the DDK, which would implement whatever protocol you wanted to expose as another WinSock protocol, and then your application-level code could just use that protocol the same way it would use, e.g., TCP. From the linked document above, it looks like this is obsolete, but the replacement seems like the same idea but with different acronyms (and, presumably, different APIs). On the other hand, I'm pretty sure Windows already comes with protocols for ARP, ICMP, and anything other protocols needed for its usermode tools (because they obviously can't be written around raw packets). I'm just not sure how to access them. As far as I know, the usual alternative is to use WinPcap. While this was originally designed to be a packet capture library, it also implements a complete link-level socket interface that you can use for sending and receiving raw…
type: Answer
has comment: http://stackoverflow.com/comment/88868364
has comment: http://stackoverflow.com/comment/88868783
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/88868239
has comment: http://stackoverflow.com/comment/88868065
score: 0

http://stackoverflow.com/a/51012347
score: 2
upvote count: 2
has body: First of all, following How to create a Minimal, Complete, and Verifiable example you should post or give a link to your image img3.pgm, if possible. Then, you wrote that: # Results of the print: # ('max', 255, 255, 255) # ('rho', 1, 1, 1) # ('theta', 183, 184, 186) so rho is the same for the three lines and theta is not so different varying between 183 and 186; so the three lines are almost equal each other and this fact does not depend on the method you use to get the line equation and draw it. According to the tutorial Hough Line Transform it seems to me that your method for finding two points on a line is correct. That's is what the tutorial is suggesting and it seems to me equivalent to your code: lines = cv2.HoughLines(edges,1,np.pi/180,200) for rho,theta in lines[0]: a = np.cos(theta) b = np.sin(theta) x0 = a*rho y0 = b*rho x1 = int(x0 + 1000*(-b)) y1 = int(y0 + 1000*(a)) x2 = int(x0 - 1000*(-b)) y2 = int(y0 - 1000*(a)) cv2.line(img,(x1,y1),(x2,y2),(0,0,255),2) I suspect the peak finding algorithm may not be correct. Your peak finding algorithm finds the location of the largest peak and then the two locations very close to that maximum. For the sake of simplicity see what happens in just one dimension, a peak finding algorithm is expected to find three peak locations at x=-1, x=0 and x=1 and the peak values should be close to .25, .5 and 1. import numpy as np import matplotlib.pyplot as plt x = np.linspace(-2, 2, 1000) y = np.exp(-(x-1)**2/0.01)+.5*np.exp(-(x)**2/0.01)+.25*np.exp(-(x+1)**2/0.01) max1, max2, max3 = 0, 0, 0 m1 = np.zeros(1000) m2 = np.zeros(1000) m3 = np.zeros(1000) x1position, x2position, x3position = 0, 0, 0 for i in range(0,1000): value = y[i] if(value &gt; max1): max1 = value x1position = x[i] elif(value &gt; max2): max2 = value x2position = x[i] elif(value &gt; max3): max3 = value x3position = x[i] m1[i] = max1 m2[i] = max2 m3[i] = max3 print('xposition',x1position, x2position, x3position ) print('max', max1, max2, max3) plt.figure() plt.s…
downvote count: 0
answers question: http://stackoverflow.com/q/51009135
type: Answer

http://stackoverflow.com/comment/88893748
type: Comment
has text: It is not working for all images while squeezing it ,it is showing correct outputs only for few.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50872497

tabs
type: Tag
tags question: http://stackoverflow.com/q/50955180
tag name: tabs
tags question: http://stackoverflow.com/q/50990697

http://stackoverflow.com/comment/88790077
type: QuestionComment
comment on: http://stackoverflow.com/q/50894963
type: Comment
has text: Thanks, For now I am using spark on local (only 1 pc) therefore versions across cluster should not be a problem at this stage.
score: 0

http://stackoverflow.com/a/50899977
has comment: http://stackoverflow.com/comment/88831788
score: 0
has comment: http://stackoverflow.com/comment/88907097
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/50898876
has comment: http://stackoverflow.com/comment/88884593
answers question: http://stackoverflow.com/q/50898876
has comment: http://stackoverflow.com/comment/88869047
has body: You have the same value for "p_arg_names" twice. It should be two different values. Try passing it in as a list like this (completely untested code as I don't have a user-name or password.): import requests from bs4 import BeautifulSoup logurl = "https://login.flash.co.za/apex/f?p=pwfone:login" posturl = 'https://login.flash.co.za/apex/wwv_flow.accept' with requests.Session() as s: s.headers = {"User-Agent":"Mozilla/5.0"} res = s.get(logurl) soup = BeautifulSoup(res.text,"lxml") arg_names =[] for name in soup.select("[name='p_arg_names']"): arg_names.append(name['value']) values = { 'p_flow_id': soup.select_one("[name='p_flow_id']")['value'], 'p_flow_step_id': soup.select_one("[name='p_flow_step_id']")['value'], 'p_instance': soup.select_one("[name='p_instance']")['value'], 'p_page_submission_id': soup.select_one("[name='p_page_submission_id']")['value'], 'p_request': 'LOGIN', 'p_t01': 'username', 'p_arg_names': arg_names, 'p_t02': 'password', 'p_md5_checksum': soup.select_one("[name='p_md5_checksum']")['value'], 'p_page_checksum': soup.select_one("[name='p_page_checksum']")['value'] } s.headers.update({'Referer': logurl}) r = s.post(posturl, data=values) print (r.content)
has comment: http://stackoverflow.com/comment/88853739
has comment: http://stackoverflow.com/comment/88826082

http://stackoverflow.com/q/50982008
accepted answer: http://stackoverflow.com/a/50984990
has comment: http://stackoverflow.com/comment/88964468
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88964871
score: 1
has comment: http://stackoverflow.com/comment/88962122
type: Question
has comment: http://stackoverflow.com/comment/88964890
has body: the code: s = pd.DataFrame(df) print(s.head(3)) print(s.loc[s.Product=='A']) output: Product Sales Date --------------------------------------------------------------------- 0 A 20 2017-5-16 1 A 60 2016-6-16 2 A 30 2015-6-16 Empty DataFrame Columns: [Product, Sales, Date] Index: [ ] Why is the data frame empty in this case? The iloc function works perfectly, but is a hassle and I don't want to use it for 185 products with 31,000 data points. Yes, the name of the product is typed in right. I tried the isin function as well which threw the same error. Note: The type is Series, but I converted it to a DataFrame. However, even after the conversion, it shows the type to be Series. This might be a key insight as to what is wrong.
answer count: 2
has comment: http://stackoverflow.com/comment/88965445
downvote count: 0
has answer: http://stackoverflow.com/a/50984990
tagged with: pandas
has comment: http://stackoverflow.com/comment/88960892
has title: Empty data frame when it is not supposed to be empty
has comment: http://stackoverflow.com/comment/88964443
favorite count: 0
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/50982928
has answer: http://stackoverflow.com/a/50982928
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/88964558

http://stackoverflow.com/comment/88952368
comment on: http://stackoverflow.com/q/50977764
score: 0
type: Comment
type: QuestionComment
has text: I am doing the Kalman Filter so that state and covariance estimation are almost same in some situation but I want to see the differences in the plot. If the people see the plot, state estimation should be under the covariance estimation so that if data are about 100, these are not visible to see.

arima
tag name: arima
tags question: http://stackoverflow.com/q/50867221
type: Tag

http://stackoverflow.com/a/50893453
has comment: http://stackoverflow.com/comment/88787590
accepted answer of: http://stackoverflow.com/q/50893266
answers question: http://stackoverflow.com/q/50893266
has body: You can save your values and attached values as a key and value pair. So something like: 3 : asd 7 : sdf 25 : dfg You iterate through the first column to find the max. Then to find the corresponding attached value (dfg), just find it as the value of that key value (25). #creating a dict mydict = {3: "asd", 7:"sdf", 25:"dfg"} maxKey=0 attachedValue=None for x in mydict.items(): key=x[0] value=x[1] if (key &gt; maxKey): maxKey=key attachedValue=value This should return you the max key and its corresponding value.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88787899
has comment: http://stackoverflow.com/comment/88787364
type: Answer
has comment: http://stackoverflow.com/comment/88787510
has comment: http://stackoverflow.com/comment/88787901
score: 0

http://stackoverflow.com/q/50893335
type: Question
upvote count: 2
tagged with: javascript
favorite count: 0
has answer: http://stackoverflow.com/a/50894129
tagged with: pandas
accepted answer: http://stackoverflow.com/a/50894129
answer count: 1
has body: Inheriting from this question which wasn't completed to a workable code solution from what I can tell. I'm trying to get a very simple wenzhixin/bootstrap-table to work. I can print the columns and data objects to the console - so they work. Here are the code snippets: #variables qs = a django queryset df = a pandas dataframe #views.py class MyView(generic.ListView): # some stuff to get qs = queryset df = read_frame(qs) json = df.to_json() columns = [{'field':f, 'title': f} for f in MyModel._meta.fields] context = { 'columns': columns, 'data': json,} return context #MyView.html &lt;script src='/path/to/bootstrap-table.js'&gt; &lt;script src='/path/to/pandas_bootstrap_table.js'&gt; &lt;script src='/path/to/bootstrap-table.css'&gt; &lt;script src='/path/to/pandas_bootstrap_table.js'&gt; &lt;script src='/path/to/bootstrap.min.cs &lt;script src='/path/to/jquery-3.3.1.slim.min.js &lt;script src='/path/to/popper.min.js &lt;script src='/path/to/bootstrap.min.js &lt;script src='/path/to/jquery.min.js &lt;table id='datatable'&gt;&lt;/table&gt; There are other elements in the view using bootstrap - everything else works - just the last line where it has a table with id='datatable' isn't rendering. The pandas_bootstrap_table.js is where I've spent my most time trying to get the function to call. I believe this is where the problem is. #pandas_bootstrap_table.js $(function() { $('#datatable').bootstrapTable({ striped: true, pagination: true, showColumns: true, showToggle: true, showExport: true, sortable: true, paginationVAlign: 'both', pageSize: 25, pageList: [10, 25, 50, 100, 'ALL'], columns:, data:, }); }); I'm using VSCode for the editing and it is throwing errors on the django template tag references within the js file - but it either isn't hitting the js file or there isn't really an error (linting?) In the above referenced SO post the answer is market accepted, but the comments below indicate that it required some additional modificatio…
tagged with: python-3.x
has title: Django template using Bootstrap-Table with Pandas DF
tagged with: django
tagged with: python
score: 2
type: AnsweredQuestion
downvote count: 0
linked to: http://stackoverflow.com/q/39003732

http://stackoverflow.com/q/50973632
type: Question
has body: I am having trouble using a builtin style in openpyxl. I am able to change the font and other attributes of a cell by doing something such as: cell.font = openpyxl.styles.Font(size=10) but am lost when it comes to builtin styles such as accents and number formatting. I have tried the following line of code: cell.style = openpyxl.styles.builtins.currency but this results in the following error: File "C:\Python27\lib\site-packages\openpyxl\styles\styleable.py", line 81, in __set__ raise ValueError("{0} is not a known style".format(value)) Any help is appreciated.
has answer: http://stackoverflow.com/a/50974434
upvote count: 2
score: 0
downvote count: 2
has title: Trouble using a "builtin" style in openpyxl
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: openpyxl

http://stackoverflow.com/comment/97177115
comment on: http://stackoverflow.com/a/54875304
has text: Unfortunately not I have also been looking for one. There is a pretty good nodejs API though
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/50860253
answers question: http://stackoverflow.com/q/50860166
upvote count: 2
type: AcceptedAnswer
type: Answer
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50860166
has body: Use the subprocess module. import subprocess file_directory = input('Enter directory name to run autoflake: ') def autoflake_run(): try: subprocess.run('autoflake -i -r --remove-all-unused-imports {}' .format(file_directory)) except: print('Path file error. Please make sure directory exists.') autoflake_run()

http://stackoverflow.com/comment/88738536
type: QuestionComment
type: Comment
has text: What's your question?
score: 1
comment on: http://stackoverflow.com/q/50868261

http://stackoverflow.com/comment/88749044
score: 0
comment on: http://stackoverflow.com/q/50873725
has text: The second example has the same number of rows as the first dataframe. However the segment_id simply states which segment the row belongs to. That was my first approach as i want to be able to groupby based on the segment_id. (Notice that each trajectory in the first dataframe, can have a number of rows associated with it, typically more than 100)
type: Comment
type: QuestionComment

sqlite
tags question: http://stackoverflow.com/q/51010048
tags question: http://stackoverflow.com/q/50970582
type: Tag
tags question: http://stackoverflow.com/q/50984179
tags question: http://stackoverflow.com/q/50872746
tags question: http://stackoverflow.com/q/50868607
tags question: http://stackoverflow.com/q/50916517
tags question: http://stackoverflow.com/q/50892275
tags question: http://stackoverflow.com/q/50887479
tags question: http://stackoverflow.com/q/50996820
tags question: http://stackoverflow.com/q/50892740
tags question: http://stackoverflow.com/q/50910558
tags question: http://stackoverflow.com/q/50906405
tags question: http://stackoverflow.com/q/50856406
tags question: http://stackoverflow.com/q/50890997
tags question: http://stackoverflow.com/q/50956459
tags question: http://stackoverflow.com/q/50947689
tags question: http://stackoverflow.com/q/50886719
tags question: http://stackoverflow.com/q/50977031
tags question: http://stackoverflow.com/q/50884818
tags question: http://stackoverflow.com/q/50950009
tags question: http://stackoverflow.com/q/50926312
tags question: http://stackoverflow.com/q/51004938
tags question: http://stackoverflow.com/q/50868137
tag name: sqlite
tags question: http://stackoverflow.com/q/50931988

http://stackoverflow.com/comment/88858265
type: AnswerComment
score: 0
type: Comment
has text: yes but I'm automating this process for hundreds of such plots all of them in different ranges, due to which manual adjustment wouldn't be a feasible solution in my case
comment on: http://stackoverflow.com/a/50881356

http://stackoverflow.com/q/50936174
answer count: 1
has comment: http://stackoverflow.com/comment/88871014
favorite count: 0
has comment: http://stackoverflow.com/comment/117880653
linked to: http://stackoverflow.com/q/49353034
tagged with: exception
tagged with: http://stackoverflow.com/tag/html
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50936413
upvote count: 1
downvote count: 1
type: Question
has title: Embedding hyperlink in python error message
tagged with: hyperlink
has comment: http://stackoverflow.com/comment/88871412
accepted answer: http://stackoverflow.com/a/50936413
has body: I'm trying to create a more helpful experience to a user by providing links to pages that may be the source of some kind of error. Basically, I'm dealing with an issue where if a user tries to change their hostname for a service to the same name as an external URL they have defined in that same service. If there is a match (meaning the entered value is a duplicate and therefore invalid) I want to raise an error message and hyperlink to the application in question so that they can immediately change it. However, because this error message is displayed after an exception is raised and within a .py file, I'm having trouble with how to hyperlink that text without using HTML. Any help would be appreciated!
score: 0
linked to: http://stackoverflow.com/q/23482748

http://stackoverflow.com/q/50936833
has body: I'm trying to solve a problem about customer preferences on restaurants. I have two different CSVs, one which has the customer information: And the other one has restaurant ratings: So I want to try out supervised training based on customer preferences in order to determine what the restaurant rating will be. In order for this to happen I think I have to append the customer information for each rating (so I will have variables to analyze). Im trying this using python &amp; pandas. I have tried this: import pandas as pd from pandas.plotting import scatter_matrix import matplotlib.pyplot as plt from sklearn import model_selection from sklearn.metrics import classification_report from sklearn.metrics import confusion_matrix from sklearn.metrics import accuracy_score from sklearn.linear_model import LogisticRegression from sklearn.tree import DecisionTreeClassifier from sklearn.neighbors import KNeighborsClassifier from sklearn.discriminant_analysis import LinearDiscriminantAnalysis from sklearn.naive_bayes import GaussianNB from sklearn.svm import SVC from pandas.plotting import scatter_matrix import numpy as np df1 = pd.read_csv('/2_user_profile.csv', index_col = [0]) df2 = pd.read_csv('/3_Ratings.csv') #Create empty dataframe with named columns df = pd.DataFrame(columns=(np.concatenate((df2.columns.values, df1.columns.values), axis=0))) #Joining the tables for index, row in df2.iterrows(): userID= row['userID'] frame=[row, df1.loc[userID]] print(frame) df = pd.concat([df, pd.DataFrame(frame)], axis=0) print(df) The print(frame) will give me this result: And that makes sense but when I print df it gives me this: Which means that each frame I create makes a double record on the dataframe, one with the information from df1 and all values that correspond to data on df2 are empty and another register for all values on df2 and empty values that correspond to df1. This is my first go at python+machine learning so let me know if you also have a comment on my approach.
has answer: http://stackoverflow.com/a/50937722
has title: Concatenate two pandas dataframes for analysis
answer count: 1
has comment: http://stackoverflow.com/comment/88872787
score: 0
tagged with: pandas
tagged with: python
accepted answer: http://stackoverflow.com/a/50937722
type: AnsweredQuestion
tagged with: python-3.x
type: Question

http://stackoverflow.com/q/50984179
tagged with: python
has body: I have three python lists with about 1.5 million entries each and would like to insert these into a new SQLite table. When doing this I get the error: OperationalError: no such column: days This is the code I have: con = sqlite3.connect('database.db') cur = con.cursor() ... cur.execute("DROP TABLE IF EXISTS days") cur.execute("CREATE TABLE IF NOT EXISTS days(DAYS_NEEDED integer, RAISED_TIME text, POSTED_TIME text)") cur.execute("INSERT INTO days (DAYS_NEEDED, RAISED_TIME, POSTED_TIME) VALUES (days, rt_list, pt_list)") con.commit() "days" is a list of integers, rt_list and pt_list are both lists of strings. Does anyone know what I'm doing wrong here? Any help is much appreciated!
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/50984361
accepted answer: http://stackoverflow.com/a/50984361
has comment: http://stackoverflow.com/comment/88963453
upvote count: 1
downvote count: 1
type: Question
has title: Insert python list into SQLite3 column
has comment: http://stackoverflow.com/comment/88963295
has answer: http://stackoverflow.com/a/50984820
tagged with: sql-insert
score: 0
answer count: 2
tagged with: sqlite
favorite count: 0
has comment: http://stackoverflow.com/comment/88963803
possible better answer: http://stackoverflow.com/a/50984820

checkbox
tag name: checkbox
tags question: http://stackoverflow.com/q/50991338
type: Tag

http://stackoverflow.com/q/50891021
answer count: 0
has body: I made a very basic calculator (im fairly new), here is the Code i'm unsure about def main(): var1 = int(input("enter number 1")) var2 = int(input("enter number 2")) operation = input ("What do you want to do? (add, subtract, multiply, divide)") if (var1 != int) or (var2 != int): print('please input a number') main() im trying to make it so that if you don't input a number it will ask you to input a number and return you to the start (var1) but the if command im using isn't working, i assume because the "!= int" is not the correct way to phrase it. instead if i put something that isn't an integer i get an actual error message and it doesn't work. any help would be appreaciated
type: UnansweredQuestion
upvote count: 1
has title: how to return user if they do not input integer
type: Question
duplicate of: http://stackoverflow.com/q/1265665
downvote count: 0
score: 1
favorite count: 0
linked to: http://stackoverflow.com/q/23294658
tagged with: python
has comment: http://stackoverflow.com/comment/88782970
duplicate of: http://stackoverflow.com/q/23294658
tagged with: python-3.x

http://stackoverflow.com/comment/88753019
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50875553
has text: What do you mean by "read the file globally" ?
score: 4

http://stackoverflow.com/q/50969641
has title: Tornado client with stdin
tagged with: python
has answer: http://stackoverflow.com/a/50974554
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50979171
has body: I am trying to build a multiplayer game that uses Python. I am using Tornado to build the client and server. Ideally, what I would like to happen are as follows: (a) For the client to wait for user input from the command line (b) When the client gets user input, to send the user input to the server (c) for the server to simulate some processing(which will be the game engine) on it and send the response back to a client. The server """ Server module for game server """ import tornado.httpserver import tornado.ioloop import tornado.options import tornado.web import tornado.websocket import uuid import json class Controller(object): def __init__(self): self.players = () self.connections = () def check(self): return "Hi" def run_somthing(self, text): new_text = "Server: " + text return new_text class InitMessageHandler(tornado.web.RequestHandler): def get(self): user_data = {} user_data['user_id'] = str(uuid.uuid4()) self.write(json.dumps(user_data)) class GameHandler(tornado.websocket.WebSocketHandler): def open(self): # called anytime a new connection with this server is opened print("Client connected") print("Client sent: ", self) if seif not in self.application.controller.connections: self.application.controller.connections.add(self) def on_message(self): # called anytime a new message is received pass def check_origin(self, origin): return True def on_close(self): # called a websocket connection is closed if self in self.application.controller.connections: self.application.controller.connections.remove(self) class Server(tornado.web.Application): def __init__(self): self.controller = Controller() handlers = [ (r"/join", InitMessageHandler), (r"/game", GameHandler) ] tornado.web.Application.__init__(self, handlers) if __name__ == "__main__": tornado.options.parse_command_line() try: application = Server() server = tornado.httpserver.HTTPServer(application) server.listen(8888) tornado.ioloop.IOLoop.instance().start() except KeyboardInterrupt: tornado.ioloop.IOLoop.in…
has answer: http://stackoverflow.com/a/50979171
tagged with: coroutine
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/50974554
tagged with: game-development
tagged with: tornado
score: 0
tagged with: asynchronous

http://stackoverflow.com/q/50896992
favorite count: 0
answer count: 3
tagged with: argparse
tagged with: python
has answer: http://stackoverflow.com/a/62863301
score: 33
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/79459443
has comment: http://stackoverflow.com/comment/88793890
type: Question
has body: Is there a way to create an alias using argparse? For example, I want to do something like this: parser.add_argument('--foo' ...) parser.add_argument_alias('--bar', '--foo') That is, using --bar should be equivalent to using --foo.
upvote count: 33
has answer: http://stackoverflow.com/a/52994694
has title: argparse add_argument alias
downvote count: 0

http://stackoverflow.com/comment/88999207
type: Comment
type: QuestionComment
has text: I have edited the post to make a working example. Sorry for the long post, but I had to save the functions in here as well as per the initial request.
comment on: http://stackoverflow.com/q/50998022
score: 0

http://stackoverflow.com/a/50924201
answers question: http://stackoverflow.com/q/50899612
type: Answer
has body: The final code which works on python version 2.7.15, which is drawn from that posted by Martin Evans is as follows: from datetime import datetime import csv with open('f:\Downloads\Sample.csv') as f_input, open('f:\Downloads\Temp.csv', 'w') as f_output: csv_input = csv.reader(f_input) csv_output = csv.writer(f_output) csv_input.next() # skip header line for row in csv_input: dt = datetime.strptime(row[0], '%Y-%m-%dT%H:%M:%S+0530') #parse the datetime row[0] = dt.strftime('%d/%m/%Y %H:%M:%S') #assign the revised format csv_output.writerow(row) Thanx everyone..
score: 0
accepted answer of: http://stackoverflow.com/q/50899612
type: AcceptedAnswer

http://stackoverflow.com/comment/88822716
type: QuestionComment
comment on: http://stackoverflow.com/q/50910867
score: 1
has text: Why not write a custom `TransformerMixin` that only fits the non-nan samples and then apply your -1/-99 imputation after that scaling?
type: Comment

http://stackoverflow.com/comment/88868452
score: 2
has text: `nthroot` takes two arguements and **returns** a `c` (the name is not important)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50934938

http://stackoverflow.com/comment/88788867
type: QuestionComment
has text: Does it means that my storage order is incorrect?
comment on: http://stackoverflow.com/q/50894096
score: 0
type: Comment

http://stackoverflow.com/q/50901045
tagged with: http://stackoverflow.com/tag/r
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/50901185
tagged with: python
tagged with: regex
favorite count: 0
accepted answer: http://stackoverflow.com/a/50901185
has body: An example slice from 2 columns in my data set, needed for later. **City** **Ranking** Boston 9 of 2972 Boston 60 of 2972 Miami 6 of 1444 Miami 200 of 1444 Miami 3 of 1444 Miami 1 of 1444 I want to create a new column called individual.rank. it's based on the Ranking column. I know how to print data rows related to each city, I just need to know how to extract and how to do the individual.rank column. the result should be like that for table of Miami for example: **City** **Ranking** **individual.rank** Miami 1 of 1444 1 Miami 2 of 1444 2 Miami 3 of 1444 3 sorting the Ranking I can do like that for a specific city: MiamiTable = data.loc[data['City'] == 'Miami'] MiamiTable.sort_values('Ranking') I have this in R using functions I don't understand, and regex. but I don't know how to do it in Python. (df.restaurant.data is the data set) : pattern &lt;- "[0-9?,]+" # pattern.end &lt;- "[0-9?,]+$" df.restaurant.data &lt;- df.restaurant.data %&gt;% mutate(individual.rank = str_replace(str_extract(Ranking, pattern), ",", "") %&gt;% as.numeric())
upvote count: 1
has comment: http://stackoverflow.com/comment/88802173
downvote count: 1
has comment: http://stackoverflow.com/comment/88801995
type: AnsweredQuestion
type: Question
possible better answer: http://stackoverflow.com/a/50901488
has title: How to extract and create a new column in a data set, based on an already existing column
has answer: http://stackoverflow.com/a/50901609
has answer: http://stackoverflow.com/a/50901488
has comment: http://stackoverflow.com/comment/88802109

http://stackoverflow.com/comment/88836640
comment on: http://stackoverflow.com/a/50917400
has text: a regular user shouldn't be able to kill other user's processes. you can limit `pkill` to your own processes using `pkill -u`
score: 2
type: AnswerComment
type: Comment

http://stackoverflow.com/a/50970402
has comment: http://stackoverflow.com/comment/88949970
accepted answer of: http://stackoverflow.com/q/50933127
answers question: http://stackoverflow.com/q/50933127
score: 2
type: AcceptedAnswer
downvote count: 0
has body: When a pod is created, the scheduler gets three "Pending" events: Pod is not scheduled yet ('node_name': None, 'status': {'conditions': None,...}) Pod is scheduled ('node_name': 'some_node_name','status': {'conditions': [...,'status': True, 'type':'PodScheduled'],...} ) Pod is initialized but not ready yet ('node_name': 'minikube','status': {'conditions': [...,'status': True, 'type':'Initialized'], ... ,'status': False, 'type':'Ready']} ) Therefore, your custom scheduler should bind pod to the node on the first event, check the status of the pod and make sure it is scheduled when the second event appears, and then check if the pod is initialized when the third event appears. If something goes wrong, the scheduler may need to take into account the previous errors and probably try to schedule the pod to different nodes. In your case, your scheduler threats all three events like the first one and tries to schedule the pod again and again. That's why you see that "pod xxx is already assigned to node yyy" error.
upvote count: 2
type: Answer

http://stackoverflow.com/comment/88773130
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50881053
has text: @EvgenyPogrebnyak not sure why we have to do that, anyway changed to text.
type: AnswerComment

http://stackoverflow.com/comment/88724480
has text: These types of data sets usually have info on *only* business days.. If that is your case, basicaly separate in weeks (tons of posts on this, https://stackoverflow.com/questions/14530556/resample-time-series-in-pandas-to-a-weekly-interval) and get last day of each
type: Comment
comment on: http://stackoverflow.com/q/50860877
score: 0
type: QuestionComment

http://stackoverflow.com/a/50892805
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50892489
has body: i fixed this by using a different way to make the webserver... thanks though!

http://stackoverflow.com/q/50874157
has comment: http://stackoverflow.com/comment/88749826
has answer: http://stackoverflow.com/a/50874547
type: Question
tagged with: spyder
has body: Trying to install spyder using pip (python 3.5.0), the installation is completed but when I try to execute it. window just pops saying python stopped working pip install spyder spyder3 Any Ideas? I am using windows 64x and I am installing it via pip and not anaconda. I am also installing it in a virtual env folder.
tagged with: python
has answer: http://stackoverflow.com/a/50874261
has title: Installing spyder in python 3.5.0
score: 0
answer count: 2
type: UnansweredQuestion

http://stackoverflow.com/comment/88838426
comment on: http://stackoverflow.com/a/50911826
type: AnswerComment
type: Comment
score: 0
has text: I have another problem, I wan't the number of the each group is the same, (split by min 25% 50% 75% max). Does **Numpy** have this method?

http://stackoverflow.com/q/50969152
linked to: http://stackoverflow.com/q/38987
possible better answer: http://stackoverflow.com/a/50969181
accepted answer: http://stackoverflow.com/a/50969191
tagged with: python
has comment: http://stackoverflow.com/comment/88934828
answer count: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50970419
has answer: http://stackoverflow.com/a/50969191
type: Question
score: 5
has title: Append a list of tuples into a existing dictionary
has answer: http://stackoverflow.com/a/50969181
upvote count: 6
has answer: http://stackoverflow.com/a/50969194
linked to: http://stackoverflow.com/q/6522446
has body: I have an existing dictionary and I want to add a list of tuples into this dictionary. Existing dictionary structure: myD = {'key1': 123 , 'key2': 456} List of tuples structure: myL = [('fkey1',321),('fkey2',432),('fkey3',543)] Expected dictionary after adding list of tuples myD = {'key1': 123 ,'key2': 456 ,'fkey': 321 ,'fkey2': 432 ,'fkey3': 543} How can I implement this in python?
downvote count: 1
favorite count: 0

http://stackoverflow.com/a/71769135
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/50940302
score: 1
has body: Following did the trick for me, Using mac. brew install leveldb gmp pkg-config After this just run pip3 install MySQL-python
downvote count: 0

http://stackoverflow.com/comment/89048767
type: Comment
comment on: http://stackoverflow.com/a/50985990
type: AnswerComment
score: 0
has text: @hyperpallium (1) Most engines compile the regex to interpreter opcodes, which could be an AST-like graph. Some even JIT-compile the opcodes. (2) A function `(position) → (result, position)` is a parsing function as used in parser combinators. (3) Backtracking is limited if you use “naive” recursive descent/PEG. E.g. a PEG `(aa/a)a` will match `aaa` but not `aa`, and the PEG `a*a` will never match because `a*` is *greedy* and consumes all `a`s. So PEG is an unsuitable algorithm for vanilla regexes. I don't know how mature engines avoid this problem without the high memory overhead of my demos.

http://stackoverflow.com/q/50967625
has answer: http://stackoverflow.com/a/50972970
type: Question
has title: Argparse default as function is always called
has comment: http://stackoverflow.com/comment/88931513
score: 1
favorite count: 0
has body: //edit 1: Changed slightly get_variable - forgot to add another argument that is passed to it (was writing it from memory, sorry for that). I have a problem with default values from argparser. Some values if not present in command line, are taken from environment using os.env, and if there is none, get it from DEFAULT_FOR_VARIABLE: def get_variable(name, DEFAULT_FOR_VARIABLE = ''): if name in os.environ: return os.environ[name] print("no default value") return DEFAULT_FOR_VARIABLE This is how it's parsed in main(): parser = argparse.ArgumentParser(description=MODULE_NAME) parser.add_argument('--test_arg', default=get_variable(VAR_NAME, DEFAULT_FOR_TEST_ARG)) args = parser.parse_args() print(args.test_arg) No matter if I pass down arguments or not, get_variable function is called and if there is no value in os.environ, print gets executed (to let me know there is missing argument), even when there is a value passed: λ python Parser_Test.py --test_arg test_arg no default value test_arg It's working as expected when arguments are not passed: λ python Parser_Test.py No default value But when for DEFAULT_FOR_TEST_ARG is set: λ python Parser_Test.py No default value DEFAULT_VALUE_FOR_TEST_ARG Also checking each parsed argument would be hard, since there is no way of iterating them the way it's provided by argparse - I have quite few of them to check for from the user. Is there a way to change this behavior? Or should I use non-standard module for parsing arguments in such a case?
tagged with: argparse
tagged with: python
answer count: 4
has comment: http://stackoverflow.com/comment/88931884
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50968094
downvote count: 1
has answer: http://stackoverflow.com/a/64464214
has answer: http://stackoverflow.com/a/70871016

http://stackoverflow.com/a/50930234
has comment: http://stackoverflow.com/comment/130763719
type: Answer
answers question: http://stackoverflow.com/q/50929948
has body: Your best bet would be to set a one-way flag variable to indicate this, and have the program check this before finishing after the for loop. def some_function(x, activation): """ Arguments: x = data activation stored as text string: "yes" or "no" Returns: z """ for i in range(10): if activation == "yes": y = 2 * x elif activation == "no": y = 100 * x else: print("ERROR: you must choose an activation. activation types: \"yes\" or \"no\"") error = True break if(error == True): z = y + 200 return z Another option would be to replace the break with a return statement. Whenever a function returns, it immediately stops. In the example below, I have the function return -1 as that is the general standard for indicating errors in returned integers. You could obviously do whatever was convenient.
score: 0

http://stackoverflow.com/q/50969989
has title: How to handle exceptions in Robot Framework?
has answer: http://stackoverflow.com/a/51022339
has comment: http://stackoverflow.com/comment/88936692
tagged with: java
type: Question
tagged with: robotframework
answer count: 2
score: 0
has answer: http://stackoverflow.com/a/51067301
type: UnansweredQuestion
has body: I want to understand how Exception Handling is done in Robot. I want to handle exceptions from multiple testcases using some generic way.
tagged with: python

http://stackoverflow.com/a/51009315
accepted answer of: http://stackoverflow.com/q/50897244
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50897244
type: Answer
score: 1
upvote count: 1
has body: You have a couple of different options here, though none are very smooth. A) Embed Python into your Android app Quite complicated, especially for libraries with native C extensions like scikit-learn. However once the setup is done, you can use any Python code your want. Some tools to simplify the process are available in the Python-for-Android project. https://github.com/kivy/python-for-android Kivy is a GUI framework that allows to write Android apps in pure Python. If you don't already know Java and have an existing app, that might be easiest way to go. B) Rewrite your ML algorithm in Java For instance using Weka framework and their RandomForests implementation. Once the rewrite is done, integration in an Android app will be pain-free.
has comment: http://stackoverflow.com/comment/92126587

http://stackoverflow.com/q/50921768
has comment: http://stackoverflow.com/comment/88845774
has title: Python and Wordpress, slow XMLRPC calls
favorite count: 0
answer count: 0
type: UnansweredQuestion
tagged with: python
downvote count: 0
score: 1
tagged with: wordpress
has body: Well lately I’m trying to work with remote posts upload. But i see that – because i am doing a lot of calls – each call after another is slower and slower. I am using python's python-wordpress-xmlrpc library. It is like WordPress has some kind of mechanism to slow down the calls if they are many. I contacted my host provider but he said that they didnt lock anything and it has something to do with WordPress security maybe. Anyone has come across this situation? I am not using any kind of plugins or security, I tested it in a clean Wordpress environment. I tried to call the function with and without "safe transport" option (User-agent etc). Thanks in advance!
type: Question
has comment: http://stackoverflow.com/comment/88843934
upvote count: 1

http://stackoverflow.com/q/50931319
upvote count: 2
has answer: http://stackoverflow.com/a/50934563
tagged with: python
has title: How to make a histogram of pandas datetimes per specific time interval?
type: AnsweredQuestion
score: 1
tagged with: python-datetime
has comment: http://stackoverflow.com/comment/88861763
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/50934563
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/88862319
has body: I want to plot some datetimes and would like to specify a time interval in order to bundle them together and make a histogram. So for example, if there happen to be n datetimes in the span of one hour, group them together or parse them as year, month, day, hour. And omit minutes and seconds. Let's say I have a data frame with some datetime values: import pandas as pd import numpy as np from datetime import datetime, timedelta date_today = datetime.now() days = pd.date_range(date_today, date_today + timedelta(7), freq='D') np.random.seed(seed=1111) data = np.random.randint(1, high=100, size=len(days)) df = pd.DataFrame({'test': days, 'col2': data}) df = df.set_index('test') print(df) 2018-06-19 17:10:32.076646 29 2018-06-20 17:10:32.076646 56 2018-06-21 17:10:32.076646 82 2018-06-22 17:10:32.076646 13 2018-06-23 17:10:32.076646 35 2018-06-24 17:10:32.076646 53 2018-06-25 17:10:32.076646 25 2018-06-26 17:10:32.076646 23 Ideally, I would like to specify a more flexible time interval, such as "6 hours" in order to make some sort of modulo operation on the datetimes. Is this possible?
favorite count: 0

http://stackoverflow.com/comment/88907584
type: Comment
comment on: http://stackoverflow.com/q/50954906
has text: Your example result is not valid syntax because the brackets don't match. Fixing the brackets gives a list with one element (a dictionary) which is pointless. Please have another go at your desired output. Also, unless you're using the right version of Python, dictionaries don't have a concept of order, and thus can't be sorted.
score: 3
type: QuestionComment

http://stackoverflow.com/a/50870327
score: 0
answers question: http://stackoverflow.com/q/50869910
has body: You have couple of issues in your code. By x = map(int,args) (line 16), x becomes a map object. To obtain integer from this map, first convert it into a list and then use indexing. x = list(map(int,args))[0] will solve your issue. Or you could simply use x = int(args[0]). list has no sorted function, change l.sorted() to l.sort().
type: Answer

http://stackoverflow.com/q/50949238
answer count: 1
has answer: http://stackoverflow.com/a/50950856
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
linked to: http://stackoverflow.com/q/26521266
has title: Referencing different tables/sheets in a database
tagged with: excel
type: Question
has comment: http://stackoverflow.com/comment/88897105
tagged with: database
has body: I want to reference a Questions table/sheet in my database called StudentNames Where would I implement the reference point so only the Questions sheet is accessed def QuestionGenerator(): questionlist_file = open('StudentNames.csv') reader=csv.reader(questionlist_file) rownum=0 array2=[] for row in reader: array2.append(row) rownum=rownum+1 print(array2)
score: 0

http://stackoverflow.com/comment/88922213
score: 0
type: Comment
type: QuestionComment
has text: What version of python are you using, if its 3.x file mode 'a+', should work fine for you
comment on: http://stackoverflow.com/q/50960123

http://stackoverflow.com/a/50990220
has comment: http://stackoverflow.com/comment/88976090
has comment: http://stackoverflow.com/comment/88978141
type: AcceptedAnswer
has body: Just use json_normalize() on the series directly, and then use pandas.concat() to merge the new dataframe with the existing dataframe: pd.concat([df, json_normalize(df['Metadata'])]) You can add a .drop('Metadata', axis=1) if you no longer need the old column with the JSON datastructure in it. The columns produced for the my_custom_data nested dictionary will have my_custom_data. prefixed. If all the names in that nested dictionary are unique, you could drop that prefix with a DataFrame.rename() operation: json_normalize(df['Metadata']).rename( columns=lambda n: n[15:] if n.startswith('my_custom_data.') else n) If you are using some other means to convert each dictionary value to a flattened structure (say, with flatten_json, then you want to use Series.apply() to process each value and then return each resulting dictionary as a pandas.Series() object: def some_conversion_function(dictionary): result = something_that_processes_dictionary_into_a_flat_dict(dictionary) return pd.Series(something_that_processes_dictionary_into_a_flat_dict) You can then concatenate the result of the Series.apply() call (which will be a dataframe) back onto your original dataframe: pd.concat([df, df['Metadata'].apply(some_conversion_function)])
downvote count: 0
has comment: http://stackoverflow.com/comment/88975224
has comment: http://stackoverflow.com/comment/88977483
has comment: http://stackoverflow.com/comment/88976585
type: Answer
upvote count: 3
accepted answer of: http://stackoverflow.com/q/50990123
has comment: http://stackoverflow.com/comment/88975280
answers question: http://stackoverflow.com/q/50990123
score: 3
has comment: http://stackoverflow.com/comment/88977022
has comment: http://stackoverflow.com/comment/88977628

http://stackoverflow.com/comment/88726962
score: 0
has text: @NieDzejkob and where is your `staticmethod` decorator ?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50862169

http://stackoverflow.com/comment/89096260
has text: What browser are you using? If Firefox and your geckodriver is 0.21.0, try downgrading geckodriver to 0.20.1.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50946760

http://stackoverflow.com/q/50988437
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/50988599
has body: Given the following series of events anonymous user opens home page, which contains a form (with a valid csrf token) the user opens a secondary tab and logs in. the user returns to the original tab and submits the form. Is the resulting csrf failure expected, and if so, are there any solutions that will give the user a better experience?
type: Question
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/51002766
has comment: http://stackoverflow.com/comment/88971587
tagged with: django-csrf
has title: Is this csrf failure expected?
type: UnansweredQuestion

http://stackoverflow.com/q/50917141
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
has body: I am using Uber's vertica-python native python adaptor (https://github.com/uber/vertica-python), and I am trying to integrate kerberos authentication with it. Is there a way I can do it? Problem: The database user I want to use with my script has authentication method kerberos set to highest priority, seems that vertica-python adaptor has only password based authentication. I read Vertica documentation it said if the priority is set to use Kerberos then its the only authentication method that Vertica asks for.
type: Question
tagged with: kerberos
tagged with: vertica
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/54193494
score: 1
has title: Python Vertica: How to use Kerberos authentication with vertica-python module?

http://stackoverflow.com/q/50875637
tagged with: plot
type: Question
has body: I have a problem with Python (WinPython-64bit-3.6.5.0Qt5)/MATPLOTLIB (version 2.2.2) when rendering text with TeX (MikTeX 2.9) and application of the font "Times", which is in the list of standard fonts (see Customizing matplotlib) In the minimal example below, I get the following error message: File "C:\WinPython-64bit-3.6.5.0Qt5\python-3.6.5.amd64\lib\site-packages\matplotlib\dviread.py", line 471, in _fnt_def_real raise error_class("missing font metrics file: %s" % fontname) FileNotFoundError: missing font metrics file: rsfs10 Here is an example to reproduce the problem: import numpy as np import matplotlib.pyplot as plt # Example data t = np.arange(0.0, 1.0 + 0.01, 0.01) s = np.cos(4 * np.pi * t) + 2 from matplotlib import rc rc('font',**{'family':'serif','serif':['Times']}) rc('text', usetex=True) plt.plot(t, s) plt.xlabel(r'\textbf{time} (s)') plt.ylabel(r'\textit{voltage} (mV)',fontsize=16) plt.title(r"\TeX\ is Number " r"$\displaystyle\sum_{n=1}^\infty\frac{-e^{i\pi}}{2^n}$!", fontsize=16, color='gray') # Make room for the ridiculously large title. plt.subplots_adjust(top=0.8) plt.savefig('tex_demo') plt.show() It looks like that python has no access to the TeX fonts, e.g. the rsfs10 which is located in my MikTeX installation folder C:\Program Files\MiKTeX 2.9\fonts\source\public\rsfs If I do not specify the font name, it works with standard serif font (it look like computer modern serif). from matplotlib import rc rc("pdf", fonttype=3) rc('font',**{'family':'serif'}) rc('text', usetex=True) I have to add the following: In the minimal example below, I first get a warning message (which I do not get in my full source code, and it is probably not related to the main problem): C:\WinPython-64bit-3.6.5.0Qt5\python-3.6.5.amd64\lib\site-packages\matplotlib\font_manager.py:1328: UserWarning: findfont: Font family ['serif'] not found. Falling back to DejaVu Sans (prop.get_family(), self.defaultFamily[fontext])) I already tried the solution for Windows described here…
tagged with: matplotlib
score: 4
answer count: 3
linked to: http://stackoverflow.com/q/42097053
favorite count: 0
has answer: http://stackoverflow.com/a/65965075
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/76136553
tagged with: tex
tagged with: python
upvote count: 4
has title: MATPLOTLIB: How do I have to provide font metrics files for rendering text by TeX?
has answer: http://stackoverflow.com/a/51515028
downvote count: 0
tagged with: fonts
has comment: http://stackoverflow.com/comment/89774947

http://stackoverflow.com/comment/88786857
type: AnswerComment
has text: @AdrianTran `stdout` is just the place where normal `print` output goes. That usually means your terminal (console) window.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50893202

http://stackoverflow.com/comment/88981904
comment on: http://stackoverflow.com/a/50993178
score: 0
type: AnswerComment
type: Comment
has text: It does have live preview which creates a webserver.

http://stackoverflow.com/comment/88936424
type: QuestionComment
type: Comment
has text: You're not updating an existing option menu, you're creating a brand new one each time you call `update`.
comment on: http://stackoverflow.com/q/50969928
score: 0

http://stackoverflow.com/q/50859664
accepted answer: http://stackoverflow.com/a/50969703
has body: I am working on python Scripting in ABAQUS. I wanted to know the displacements of all the nodes pertaining to just a particular nodeset(PU-NODES-FATIGUE). I try to access it by writing the following code but encountered an error saying: keyError : PU-NODES-FATIGUE I tried to even change the name to different set so as to check the output but it is still the same error. It would be very greatful if anyone can throw some light on this. Thank you in advance. The code is: &gt;&gt;&gt; print 'Node sets = ',odb.rootAssembly.nodeSets.keys() Node sets = [' ALL NODES', 'BC-PU-SYM-Z', 'PU-NODES-FATIGUE', 'SET-8'] &gt;&gt;&gt; fatigue = odb.rootAssembly.instances['PU-1'].nodeSets['PU-NODES-FATIGUE'] KeyError: PU-NODES-FATIGUE
answer count: 1
score: 0
tagged with: python
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/50969703
has title: To know the displacements of all the nodes pertaining to just a particular nodeset

http://stackoverflow.com/comment/88843468
comment on: http://stackoverflow.com/q/50921241
score: 0
type: Comment
type: QuestionComment
has text: @erhan: you will have to dump the file in txt. You will also need to manage index of the z value in the list.

http://stackoverflow.com/comment/88863061
comment on: http://stackoverflow.com/a/50931771
type: AnswerComment
has text: What if I have NaN values? "('cannot convert float NaN to integer', 'occurred at index ACT1')"
score: 0
type: Comment

http://stackoverflow.com/a/66599323
upvote count: 3
downvote count: 0
type: Answer
has body: It did work for me just by installing tesseract using conda. conda install -c conda-forge tesseract
answers question: http://stackoverflow.com/q/50951955
score: 3

http://stackoverflow.com/comment/89001713
comment on: http://stackoverflow.com/q/51003941
score: 0
type: Comment
type: QuestionComment
has text: can you add a sample input + desired output? It's kind of hard to understand what this script is intended to do

http://stackoverflow.com/q/50995404
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88985558
has comment: http://stackoverflow.com/comment/88988197
has body: the input does not have any NaN value, but the accuracy is always 0. n_nodes_hl1 = 3000 n_nodes_hl2 = 1500 n_nodes_hl3 = 1000 n_classes = 3 batch_size = 5 hm_epochs = 5 def train_neural_network(x): prediction=neural_network_model(x) cost=tf.nn.softmax_cross_entropy_with_logits_v2(logits = prediction, labels = y) optimizer=tf.train.AdamOptimizer(learning_rate=0.001).minimize(cost) saver = tf.train.Saver() with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for epoch in range(hm_epochs): epoch_loss = 0 i = 0 #while i &lt; len(train_x): t = len(train_x) f = t%batch_size while i &lt; (t-f): start = i end = i+batch_size batch_x = np.array(train_x[start:end]) batch_y = np.array(train_y[start:end]) _, c = sess.run([optimizer, cost], feed_dict={x: batch_x, y: batch_y}) epoch_loss += c #epoch_loss = epoch_loss + c i+=batch_size #i = i + batch_size print('Epoch =', epoch+1, '/',hm_epochs,'loss:',epoch_loss) save_path = saver.save(sess, "sesionestensorflow/model1802.ckpt") print("Model saved in path: %s" % save_path) correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1)) accuracy = tf.reduce_mean(tf.cast(correct, 'float')) print('Accuracy:',accuracy.eval({x:test_x, y:test_y})) i understand that it could be the loss function and if it is the case, the neural network need a clip by value procedure.
has comment: http://stackoverflow.com/comment/88985768
tagged with: tensorflow
has title: Neural Network in Tensorflow give 0 Accuracy
type: Question
has comment: http://stackoverflow.com/comment/88987198
tagged with: neural-network
score: 0
has comment: http://stackoverflow.com/comment/88987171

http://stackoverflow.com/a/50964829
score: 1
accepted answer of: http://stackoverflow.com/q/50964401
answers question: http://stackoverflow.com/q/50964401
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88960144
downvote count: 0
has body: The strategy that you will choose depends mainly on the structure of the CNN that you are going to create. If you train a model that is able to recognize if an image contains a spoon or a fork, you will not be able to test on a table with several table-cloth items (e.g. both a fork and a spoon) because the network will try to answer if in the image there is a spoon or a fork indeed. Anyway, it is still possible to train the network to classify several features (strategy "A") but in that case you need a model that is able to do Multi-label classification. Finally, I would suggest to go for the "B" strategy because, in my humble opinion, it fits good the application domain. Hope this answer is clear and helpful! Cheers.
type: Answer
has comment: http://stackoverflow.com/comment/88941050

http://stackoverflow.com/comment/88816670
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50906899
has text: @Dillon all the matters is if it worked for the OP :)

http://stackoverflow.com/q/50904156
possible better answer: http://stackoverflow.com/a/50904547
has comment: http://stackoverflow.com/comment/88808132
has answer: http://stackoverflow.com/a/50904547
upvote count: 1
has comment: http://stackoverflow.com/comment/88808406
type: Question
has answer: http://stackoverflow.com/a/50904359
has comment: http://stackoverflow.com/comment/88808319
has comment: http://stackoverflow.com/comment/88808551
accepted answer: http://stackoverflow.com/a/50904359
answer count: 2
tagged with: xml-parsing
downvote count: 0
score: 1
favorite count: 0
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/88808222
has comment: http://stackoverflow.com/comment/88808119
has body: I have this xml file which I wish to parse. This is the code I have written. However it seems that it is unable to parse the file since it outputs none. from bs4 import BeautifulSoup f=open("1.txt",'r') y=BeautifulSoup(f, "lxml-xml") print(y.url) Output None
tagged with: python
has title: Issues with Beautiful Soup XML Parsing in Python
has comment: http://stackoverflow.com/comment/88808214
type: AnsweredQuestion

http://stackoverflow.com/q/50915931
has comment: http://stackoverflow.com/comment/88833675
has title: ElasticSearch throwing 400 when deleting index on python
type: Question
tagged with: http-status-code-400
tagged with: amazon-web-services
has comment: http://stackoverflow.com/comment/100301330
score: 0
has body: I am getting a 400 error when trying to delete an index from elastic search using the python api res = es.indices.delete(index=index_name) and we are getting this exception RequestError: TransportError(400, u'illegal_argument_exception') However when deleting the index manually through postman, it works. It's also worth noting we don't get this error everyday which is very odd. Also just for note, this is a relatively big search index, not sure if that has to do with anything though (>10gb). We have also checked that the index exists before getting this error.
tagged with: elasticsearch
tagged with: rest
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88833206
tagged with: python
has comment: http://stackoverflow.com/comment/88839805
has comment: http://stackoverflow.com/comment/88839773

http://stackoverflow.com/a/50880859
type: Answer
has body: You can use: list = [abs(number)%100 for number in list] And it's a bad practice to name lists list. Use another name.
downvote count: 0
answers question: http://stackoverflow.com/q/50880762
score: 1
has comment: http://stackoverflow.com/comment/88763949
has comment: http://stackoverflow.com/comment/88764441
upvote count: 1

http://stackoverflow.com/comment/88908311
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50955005
score: 0
has text: The primary reasoning makes sense. I am going to update my original question to ask "What can I do about it?"

python-datetime
tag name: python-datetime
tags question: http://stackoverflow.com/q/50988451
tags question: http://stackoverflow.com/q/50993165
tags question: http://stackoverflow.com/q/51005263
tags question: http://stackoverflow.com/q/50931319
tags question: http://stackoverflow.com/q/50871693
type: Tag

http://stackoverflow.com/comment/88795777
has text: @PM2Ring: it's not that funky an order, and again, it depends on the exact use case if the order actually matters!
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50897981
type: Comment

http://stackoverflow.com/a/51011418
has comment: http://stackoverflow.com/comment/89046608
upvote count: 1
has body: shouldn't the index 3 return all the columns that come after "CMS" What should be mentioned is that pd.read_html function returns dfs : list of DataFrames and df[3] would just contain the one of those dataframes. To use table-header cells ( action address machinie_id ....) as column names - set header option to 1 (row number). header : int or list-like or None, optional The row (or list of rows for a :class:~pandas.MultiIndex) to use to make the columns headers. Test: In [21]: df = pd.read_html('data.html', header=1) In [22]: df[3].columns Out[22]: Index(['action', 'address', 'machinie_id', 'portal', 'supplier', 'created_by', 'date', 'portal deficit', 'Load Value 1', 'Load Value 2', 'Load Value 3', 'Load Value 4', 'Load Value 5', 'Sub Load 1', 'Sub Load 2', 'Sub Load 3', 'Sub Load 4', 'Sub Load 5', 'Coordinates', 'Area Code', 'pending case id', 'project details', 'identification number APAC', 'site_id', 'state', 'status', 'timestamp', 'Unnamed: 27', 'Unnamed: 28', 'Unnamed: 29', 'Unnamed: 30', 'Unnamed: 31', 'Unnamed: 32', 'Unnamed: 33', 'Unnamed: 34', 'Unnamed: 35', 'Unnamed: 36', 'Unnamed: 37', 'Unnamed: 38', 'Unnamed: 39', 'Unnamed: 40', 'Unnamed: 41', 'Unnamed: 42', 'Unnamed: 43', 'Unnamed: 44', 'Unnamed: 45', 'Unnamed: 46', 'Unnamed: 47', 'Unnamed: 48', 'Unnamed: 49', 'Unnamed: 50', 'Unnamed: 51', 'Unnamed: 52', 'Unnamed: 53', 'Unnamed: 54', 'Unnamed: 55'], dtype='object') In [23]:
answers question: http://stackoverflow.com/q/51010319
score: 1
has comment: http://stackoverflow.com/comment/89017039
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51010319
has comment: http://stackoverflow.com/comment/89017921
type: Answer

http://stackoverflow.com/a/50910383
has body: You are not using the adequat data structure for this problem. First off, consider using a database when items stored in a file are meant to have relationships. Although, if all you require is a one time parsing of the file, using a dict should be sufficient and yet efficient enough. Code def find_one_to_one(d): for k, v in d.items(): if v in d and d[v] == k: return k, v else: return None with open('test_file.txt') as file: d = {left.strip(): right.strip() for left, right in [row.split(',') for row in file]} print(find_one_to_one(d)) Test file content 1234 Address , Billy Joel Joe Martin, 45 Other Address 63 OtherOther Address, Joe Martin Billy Joel, 1234 Address Output ('1234 Address', 'Billy Joel')
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50910136

http://stackoverflow.com/comment/88876106
has text: windows! I think the problem is with the 32 bits or 64 its python
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50938895

http://stackoverflow.com/comment/129370658
comment on: http://stackoverflow.com/a/57893568
score: 1
has text: It's not working for me. It's still formatting it. Any ideas for debugging why?
type: AnswerComment
type: Comment

http://stackoverflow.com/a/50867584
upvote count: 1
has comment: http://stackoverflow.com/comment/88763718
score: 1
type: AcceptedAnswer
downvote count: 0
has body: Depends on where your coordinate origin is. If it is top left go with fft. If it is in the center go with convolve. &gt;&gt;&gt; a = (1, 0, 0, 0, 0) &gt;&gt;&gt; a = np.outer(a, a) &gt;&gt;&gt; a array([[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]]) &gt;&gt;&gt; np.real(ifft2(fft2(a) * fft2(a))) array([[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.]]) &gt;&gt;&gt; &gt;&gt;&gt; a = (0, 0, 1, 0, 0) &gt;&gt;&gt; a = np.outer(a, a) &gt;&gt;&gt; a array([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]) &gt;&gt;&gt; scipy.signal.convolve2d(a, a, boundary="wrap", mode="same") array([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]])
has comment: http://stackoverflow.com/comment/88748564
type: Answer
accepted answer of: http://stackoverflow.com/q/50864884
answers question: http://stackoverflow.com/q/50864884

http://stackoverflow.com/a/50932123
answers question: http://stackoverflow.com/q/50928679
type: Answer
upvote count: 3
has body: So the problem is not really about Yattag, right? Your problem is to take the elements by groups of 5 (or whatever fixed number). For this I'd use the islice method from the itertools module. You have an example of how to use this function to create a take function that takes the first n elements of an iterable: https://docs.python.org/3/library/itertools.html#itertools-recipes Using this take function, you can consume an iterable by groups of n elements. Here's the solution to your particular problem: from itertools import islice from yattag import Doc, indent def take(n, iterable): "Return first n items of the iterable as a list" return list(islice(iterable, n)) def zones_to_html(zones): zones_iterator = iter(zones) # in case zones is not already an iterator doc, tag, text, line = Doc().ttl() with tag('table', klass="all-pr"): while True: first5 = take(5, zones_iterator) if len(first5) == 0: break else: with tag('tr'): with tag('td'): for zone in first5: line('div', zone['name'], klass = 'pr ' + zone['risk_alert']) line('div', '-', klass='link-pr') return doc.getvalue() # Example of use: if __name__ == '__main__': all_zones = ({'name': i, 'risk_alert': 'high'} for i in range(114, 129)) print(indent(zones_to_html(all_zones))) I used the line method of Yattag, which is a shortcut described here: http://www.yattag.org/#shortcut-for-nodes-that-contain-only-text
score: 3
downvote count: 0

http://stackoverflow.com/a/66845251
answers question: http://stackoverflow.com/q/50905636
score: 0
type: Answer
has body: You can just install pylint in your virtualenv using pip install pylint (inside your terminal) and restart your VS code.

http://stackoverflow.com/a/50915581
answers question: http://stackoverflow.com/q/50881103
accepted answer of: http://stackoverflow.com/q/50881103
type: Answer
score: 0
has body: Here is the answer, I figured out how to do it within my constraints. Make datasets for each file, define each mini batch size for each, and concatenate the get_next() outputs together. This fits on my machine and runs efficiently.
type: AcceptedAnswer

http://stackoverflow.com/a/50858067
upvote count: 6
has body: Environment variables set in a shell are not automatically exported to subprocesses. Just because your shell has a HOSTTYPE variable, doesn't mean this is variable is visible to subprocesses. Export the variable first: $ export HOSTTYPE You can combine setting and exporting a variable in one step with: $ export HOSTTYPE=x86_64 Demo: $ HOSTTYPE=x86_64 $ python -c 'import os; print os.path.expandvars("$HOSTTYPE")' $HOSTTYPE $ export HOSTTYPE $ python -c 'import os; print os.path.expandvars("$HOSTTYPE")' x86_64 See Difference between environment variables and exported environment variables in bash.
type: Answer
score: 6
downvote count: 0
answers question: http://stackoverflow.com/q/50857962

http://stackoverflow.com/comment/88925608
score: 0
has text: thanks, i saw that post and it is not what i am looking for. the approach in that example is exactly what i am trying to avoid. i don't want to have multiple string arrays and build a hashmap out from referencing them. That's the entire idea of a map. I want to have the map static in a resource file and pull it inside the code and that's it.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50964322

http://stackoverflow.com/comment/88891763
has text: [The PyPA recommended tool for **installing Python packages**.](https://pypi.org/project/pip/)
comment on: http://stackoverflow.com/q/50947238
type: Comment
type: QuestionComment
score: 3

http://stackoverflow.com/q/50868046
has comment: http://stackoverflow.com/comment/88738147
has comment: http://stackoverflow.com/comment/88738412
has comment: http://stackoverflow.com/comment/88738127
answer count: 1
downvote count: 0
score: 1
favorite count: 0
type: UnansweredQuestion
tagged with: pip
tagged with: python
has comment: http://stackoverflow.com/comment/88738425
has answer: http://stackoverflow.com/a/50868233
has body: I am trying to install flask with pip3 in a virtual environment and it fails when I run (VirtEnv) $ pip3 install flask With: Collecting flask Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('&lt;urllib3.connection.VerifiedHTTPSConnection object at 0x7f870ae3bc18&gt;: Failed to establish a new connection: [Errno -2] Name or service not known',)': /simple/flask/ Could not find a version that satisfies the requirement flask (from versions: ) No matching distribution found for flask However when I run with sudo, the command succeeds but I've read this will install the file outside the virtual environment when using sudo. Running outside the virtual environment also succeeds.
linked to: http://stackoverflow.com/q/28668180
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/88738418
has title: pip3 install without sudo in a venv virtual environment fails with "Failed to establish a new connection: [Errno -2] Name or service not known
has comment: http://stackoverflow.com/comment/88738261
tagged with: ubuntu

http://stackoverflow.com/comment/89009469
score: 0
has text: That's the ontology before data population - it does not match with any of the parse errors you're showing. What does the ontology look like after population? Are there multiple files involved?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50972464

http://stackoverflow.com/q/50952539
score: 0
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/88902964
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/339007
has comment: http://stackoverflow.com/comment/89010587
tagged with: oop
answer count: 0
has title: Change formatting of bin using OOP in python
tagged with: bin
type: Question
has comment: http://stackoverflow.com/comment/88902888
has body: I've encountered a question on a course in oop in python regarding bin(). The author wanted to modify it in such a way that it would return the binary representation of a number in a different format. For example, bin(30), instead of '0b11110' would output '00011110'. This can be done, for instance, by a workaround bin(30)[2:].zfill(8) According to the documentary and this stack question, this can be done also by f'{30:08b}' Is there a smart way to define a class to do just that? Note, a beginner here. Here's my attempt: class my_bin(object): def __init__(self,value): self.binary = format(value, '08b') def __repr__(self): return str(self.binary)
has comment: http://stackoverflow.com/comment/88902884

http://stackoverflow.com/q/50974590
type: Question
type: AnsweredQuestion
has body: Can anyone help with how i can scrap just the text below from this code using beautifulsoup. "Disappointed coach Bert van Marwijk said Australia have to find the last part of the puzzle if they are to stay in the World Cup after a 1-1 draw with Denmark on Thursday. Australia captain Mile Jedinak hit a VAR-assisted penalty to earn the Socceroos first point in Russia after Christian Eriksens opener, giving Australia" <a href="website" target="_blank" rel="nofollow" onmouseover="ddrivetip('Thu, 21 Jun 2018 Disappointed coach Bert van Marwijk said Australia have to find the last part of the puzzle if they are to stay in the World Cup after a 1-1 draw with Denmark on Thursday. Australia captain Mile Jedinak hit a VAR-assisted penalty to earn the Socceroos first point in Russia after Christian Eriksens opener, giving Australia []')" ;="" onmouseout="hideddrivetip()">Australias Van Marwijk says last part of puzzle missing at World Cup
accepted answer: http://stackoverflow.com/a/50974649
answer count: 2
upvote count: 0
score: -2
favorite count: 0
has title: Need to Scrape text with beautifulsoup
tagged with: http://stackoverflow.com/tag/html
tagged with: python
possible better answer: http://stackoverflow.com/a/50974684
has answer: http://stackoverflow.com/a/50974684
has answer: http://stackoverflow.com/a/50974649
downvote count: 2

http://stackoverflow.com/comment/88934022
score: 1
comment on: http://stackoverflow.com/a/50958025
type: AnswerComment
has text: tried both smj & jpp both answer my question, can't pandasice piRSquared, ran %%timeit on Jupyter NB on both - option smj 16.7 s ± 227 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) option jpp 1.24 s ± 2.6 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) -many thank, all 98k addresses sorted!
type: Comment

http://stackoverflow.com/comment/118373997
type: AnswerComment
comment on: http://stackoverflow.com/a/66963578
type: Comment
score: 0
has text: Hi @loveactualry. The challenge here is that dfply isn't recognising the ~ on the right side of the OR (|) in my original code. In your suggestion, when I change (X.b.isnull())) to ~(X.b.isnull())) I still get a result of: a b c 0 NaN 6.0 5 4 5.0 NaN 1 ...which is not what I expect. Rather, I expect: a b c 0 NaN 6.0 5 1 2.0 7.0 4 2 3.0 8.0 3 3 4.0 9.0 2

http://stackoverflow.com/q/50855424
has title: MATLAB to Python [sgolay()]
has answer: http://stackoverflow.com/a/50855728
has body: A MATLAB code contains the use of the function sgolay as: [b,g] = sgolay(k, f) Using this, I need to find the smoothness, first derivative, and second derivative. for finding the above, I need the value of g. These have to be performed in Python instead of MATLAB. Python's savgol_filter(arr, k, f) works the same as MATLAB's sgolay(arr, k, f), however, there is no alternative to sgolay(k, f) which designs the filter and returns g. What would be a Python equivalent to the sgolay() function?
type: UnansweredQuestion
upvote count: 1
downvote count: 1
tagged with: matlab
has comment: http://stackoverflow.com/comment/88718749
has comment: http://stackoverflow.com/comment/88713710
type: Question
answer count: 1
linked to: http://stackoverflow.com/q/50850399
favorite count: 0
score: 0
tagged with: python

http://stackoverflow.com/q/50871611
tagged with: translate
upvote count: 1
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/50922515
accepted answer: http://stackoverflow.com/a/50922515
has comment: http://stackoverflow.com/comment/88750965
tagged with: import
type: Question
tagged with: robotframework
has body: Obviously it is possible to import Python Robot Framework library in some Python script. However, is there a magic way to import Robot Framework resource file in Python script? Resource files are written in RF syntax so there would need to be some dedicated Python module for importing it (translating RF syntax to Python actually). Perhaps something like this exists already or even some RF builtin module could be used, as if I understand correctly, during script execution RF syntax is translated to Python calls. Update 2018-06-18: As suggested by A. Kootstra it is possible to import Robot keyword inside Python script using: from robot.libraries.BuiltIn import BuiltIn BuiltIn().import_resource('${EXECDIR}/resource.robot') However, how can I access any keyword from imported Robot resource inside Python script ? BuiltIn().import_resource does not return any handler to imported lib. I would call BuiltIn.call_method but it needs object instance as first parameter. Imported resource file is also not present in a dict returned by globals()
answer count: 1
downvote count: 0
favorite count: 0
has title: Is there a way to import Robot Framework resource fiile contents into Python script?
has comment: http://stackoverflow.com/comment/88826561
has comment: http://stackoverflow.com/comment/88826349
tagged with: python
linked to: http://stackoverflow.com/q/50790809

http://stackoverflow.com/comment/88855097
has text: Yes, it is safe because I have only one line with `[ word ]` in the input file.
score: 0
comment on: http://stackoverflow.com/q/50927581
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88958070
score: 0
type: Comment
type: QuestionComment
has text: These plots supposed to be straight lines. Not scattered plots. Also is there a way to calculate slopes on pairplot?
comment on: http://stackoverflow.com/q/50981193

http://stackoverflow.com/q/50973373
has body: I am facing a trouble when I use lightgbm to conduct grid search. lgb_classifer = lgb.LGBMRegressor(random_state=12) grid_lgb = { 'learning_rate': [0.01,0.05], 'num_iterations': [5,10,20]} gbm_lgb = GridSearchCV(estimator =lgb_classifer, param_grid =grid_lgb, scoring = 'recall', cv=3) ---&gt; gbm_lgb.fit(X_train, y_train) ValueError: Classification metrics can't handle a mix of binary and continuous targets Both X_train AND y_train is array.y_train is binary label.
tagged with: grid-search
has title: LightGBM- Classification metrics can't handle a mix of binary and continuous targets
has comment: http://stackoverflow.com/comment/88976560
upvote count: 4
answer count: 1
downvote count: 0
tagged with: scikit-learn
favorite count: 0
tagged with: lightgbm
linked to: http://stackoverflow.com/q/38015181
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88977504
tagged with: python
has comment: http://stackoverflow.com/comment/88977607
has answer: http://stackoverflow.com/a/51011731
score: 4
type: Question
has comment: http://stackoverflow.com/comment/88976314

http://stackoverflow.com/comment/91995562
comment on: http://stackoverflow.com/a/51010227
score: 1
type: AnswerComment
has text: Removing the font list cache essentially forces a rebuild of the font cache. I don't think the answer that I posted is any more "proper" since it uses the private `_rebuild` method, but there ya go.
type: Comment

http://stackoverflow.com/a/55725093
upvote count: 14
answers question: http://stackoverflow.com/q/50914729
has comment: http://stackoverflow.com/comment/112533488
type: AcceptedAnswer
downvote count: 0
has body: Thanks to this answer (I've changed the code a little bit to make it better). you can use this code for solving your problem. we have all our minor set of words in restricted_word_set(it can be either list or set) and w2v is our model, so here is the function: import numpy as np def restrict_w2v(w2v, restricted_word_set): new_vectors = [] new_vocab = {} new_index2entity = [] new_vectors_norm = [] for i in range(len(w2v.vocab)): word = w2v.index2entity[i] vec = w2v.vectors[i] vocab = w2v.vocab[word] vec_norm = w2v.vectors_norm[i] if word in restricted_word_set: vocab.index = len(new_index2entity) new_index2entity.append(word) new_vocab[word] = vocab new_vectors.append(vec) new_vectors_norm.append(vec_norm) w2v.vocab = new_vocab w2v.vectors = np.array(new_vectors) w2v.index2entity = np.array(new_index2entity) w2v.index2word = np.array(new_index2entity) w2v.vectors_norm = np.array(new_vectors_norm) WARNING: when you first create the model the vectors_norm == None so you will get an error if you use this function there. vectors_norm will get a value of the type numpy.ndarray after the first use. so before using the function try something like most_similar("cat") so that vectors_norm not be equal to None. It rewrites all of the variables which are related to the words based on the Word2VecKeyedVectors. Usage: w2v = KeyedVectors.load_word2vec_format("GoogleNews-vectors-negative300.bin.gz", binary=True) w2v.most_similar("beer") [('beers', 0.8409687876701355), ('lager', 0.7733745574951172), ('Beer', 0.71753990650177), ('drinks', 0.668931245803833), ('lagers', 0.6570086479187012), ('Yuengling_Lager', 0.655455470085144), ('microbrew', 0.6534324884414673), ('Brooklyn_Lager', 0.6501551866531372), ('suds', 0.6497018337249756), ('brewed_beer', 0.6490240097045898)] restricted_word_set = {"beer", "wine", "computer", "python", "bash", "lagers"} restrict_w2v(w2v, restricted_word_set) w2v.most_similar("beer") [('lagers', 0.6570085287094116), ('wine', 0.6217695474624634), ('bash', 0.20…
type: Answer
accepted answer of: http://stackoverflow.com/q/50914729
score: 14

http://stackoverflow.com/a/50870662
score: 0
answers question: http://stackoverflow.com/q/50870061
has body: The threads are working fine and they're completing correctly. It's your 'z' variable that's the problem. In general using a global variable as a container for your shared memory between two threads is a bad way to go about it. Check out this answer to see why. I made the following changes to your code. I made 'z' the shared variable and 'x' and 'y' are data for each thread alone. x=0 y=0 z=0 def increment1(s): global x,z s.wait() x+=1 z+=1 s.signal() def increment2(s): global y,z s.wait() y+=1 z+=1 s.signal() def task1(s): for somei in range(1000000): increment1(s) def task2(s): for somej in range(1000000): increment2(s) This is the output I got: X = 1000000 Y = 1000000 Z = 1961404 As you can see there's nothing wrong with the threads themselves, as they're completing their execution. But the shared data Z is a little wonky. Z will change randomly each time you run the script. Hence as you can see using global variables as shared memory is a bad idea. A much better option would be using some python supported sharing tool such as Queue provided by python's library itself. It's a multi-producer, multi-consumer message queue and helps when it comes to shared data such as the data you're using now. Let me show you how it can be done with Queue: import threading as th from Queue import Queue def task1(q): global x,z for somei in range(1000000): q.put(q.get() + 1) def task2(q): global y,z for somei in range(1000000): q.put(q.get() + 1) def main(): queue = Queue() queue.put(0) t1 = th.Thread(target=task1,name="t1",args=(queue, )) t2 = th.Thread(target=task2,name="t1",args=(queue, )) t1.start() t2.start() #Checking Synchronization t1.join() t2.join() return queue.get() if __name__=="__main__": print("Queue = %d"%main()) #Final Output You don't even need to create a semaphore here as the Queue will automatically take care of synchronization. The output of this final program is this: Queue = 2000000
type: Answer

http://stackoverflow.com/comment/88985977
has text: it could work but you're likely to run into problems... g++ 4.4 does have quite a bit of missing stuff: https://gcc.gnu.org/gcc-4.4/cxx0x_status.html alternativelly you could install a newer gcc, search so/google there is some help with this
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50995592
score: 1

http://stackoverflow.com/q/50991338
tagged with: tkinter
has comment: http://stackoverflow.com/comment/88984444
type: UnansweredQuestion
upvote count: 1
tagged with: python
has title: Tkinter: checkbox list not responsive
tagged with: checkbox
has answer: http://stackoverflow.com/a/50995609
score: 1
tagged with: checkboxlist
has comment: http://stackoverflow.com/comment/88983389
has body: I am trying to create a list of checkboxes with a loop. I have modified the implementation of someone else's code which uses the same concept and should have the same function as what I want. When I try to print the state of each checkbox, none of them are updated to 1. They all stay at 0 even if I click them. Here is my code, the test() function doesn't behave as I expect it to. import tkinter import tkinter.filedialog import os def browse(): filez = tkinter.filedialog.askdirectory(parent=window, title='Choose a file') ent1.insert(20, filez) dirs = os.listdir(filez) # remove previous IntVars intvar_dict.clear() # remove previous Checkboxes for cb in checkbutton_list: cb.destroy() checkbutton_list.clear() for filename in dirs: # create IntVar for filename and keep in dictionary var = tkinter.IntVar() # create Checkbutton for filename and keep on list c = tkinter.Checkbutton(window, text=filename, variable=var) c.pack() intvar_dict[filename] = var checkbutton_list.append(c) def test(): for key, value in intvar_dict.items(): if value.get() > 0: print("HIIIIII") print('selected:', key) #print (value.get()) # to keep all IntVars for all filenames intvar_dict = {} # to keep all Checkbuttons for all filenames checkbutton_list = [] window = tkinter.Tk() lbl = tkinter.Label(window, text="Path") lbl.pack() ent1 = tkinter.Entry(window) ent1.pack() btn1 = tkinter.Button(window, text="Select Path", command=browse) btn1.pack() btn1 = tkinter.Button(window, text="Test Checkboxes", command=test) btn1.pack() window.mainloop()
has comment: http://stackoverflow.com/comment/88977488
has comment: http://stackoverflow.com/comment/88979277
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/88979925
answer count: 1
has comment: http://stackoverflow.com/comment/88984591
has comment: http://stackoverflow.com/comment/88979306
favorite count: 0

http://stackoverflow.com/a/50883299
upvote count: 2
type: Answer
score: 2
has body: This doesn't appear to be a "grouping" operation, per se. Rather, it appears to be a graph closure or clustering task. I recommend that you change this to a while logic: as long as you can merge two clusters, you continue looping on the existing data set. You merge any two clusters whose intersection is non-empty. One way to approach the inner iteration control is to use a for loop to go through all of the dict entries; merge when you find a match. The outer loop repeats this until no matches are found. Another way is to focus on the first entry only; look for another entry that has a non-empty overlap, and merge. Once you can no longer merge the first entry with any other, you "retire" it: delete it from the "working" dict and append it to the "results" dict. repeat this until the "working" dict is empty. Does that get you moving? working = my_dict results = {} while len(working) &gt; 0: # Remove the first entry from the working directory; hold locally next_key = list(working.keys())[0] next_val = set(working.pop(next_key)) # Now, go through the remaining entries in "working" # Each time you find one with an element in common with "next_val", # pop that from "working" and merge into "next_val" and "next_key" # When there are no more such merges to make ... results[next_key] = next_val # ... and return to the top of the outer loop # to get the next independent entry.
downvote count: 0
answers question: http://stackoverflow.com/q/50883192
has comment: http://stackoverflow.com/comment/88768763
has comment: http://stackoverflow.com/comment/88769726

http://stackoverflow.com/q/50889452
has title: Flask app.py stopped working in pycharm
downvote count: 0
has answer: http://stackoverflow.com/a/50889539
score: 1
has answer: http://stackoverflow.com/a/50889481
tagged with: sqlalchemy
type: Question
has answer: http://stackoverflow.com/a/50889980
has body: I am new to flask and pycharm. Basically I wrote a rest webservice and initially PyCharm was running it as a python script. Everything was working fine. But then after I realuched pycharm it detects app.py as a flask application. Part that launches the app locally in app.py looks like so: if __name__ == '__main__': from db import db db.init_app(app) if app.config['DEBUG']: @app.before_first_request def create_tables(): db.create_all() app.run(port=5000) The problem is that it seems like this part is not executed when I try to run app.py. I also have run.py which I use to run the app through uwsgi on a web server. Here is the console output from pycharm when I launch app.py: FLASK_APP = app.py FLASK_ENV = development FLASK_DEBUG = 0 In folder /home/username/PycharmProjects/psychotest /home/aydar/PycharmProjects/psychotest/venv/bin/python -m flask run * Serving Flask app "app.py" * Environment: development * Debug mode: off * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) I've added print statements to the if __name__=='main' block, which are never printed. It also seems that pycharm launches flask with /home/username/PycharmProjects/psychotest/venv/bin/python -m flask run. Also as you can see DEBUG is false, even though I explicitly set debug to true in the body of app.py like so: app = Flask(__name__) app.config['DEBUG'] = True Everything is working through the terminal with just python app.py. How do I change this behaviour of Pycharm? It annoys me because I get sqlalchemy errors every time I try to get something from a database through flask. Error example: 'The sqlalchemy extension was not registered to the current ' \ AssertionError: The sqlalchemy extension was not registered to the current application. Please make sure to call init_app() first.
tagged with: flask
tagged with: flask-sqlalchemy
answer count: 3
upvote count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/30764073
tagged with: pycharm
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/50858231
has comment: http://stackoverflow.com/comment/88739145
has comment: http://stackoverflow.com/comment/88728659
downvote count: 0
tagged with: django-rest-framework-jwt
favorite count: 0
has body: this is django rest framework project . this time i want to resend account activation code to registered user(that is not active at the moment) i wrote view like this but i get server response that say: user account is disabled ... i know user is disabled right now but i want to send new activation code to him according his/her email and id.. note: im using jwt for authentication in my app this is my view: any suggestion for me to solve this issue? and about my view is it correct way? class ResendActivationCode(APIView): permission_classes = [AllowAny] activation_code = code_generator() def get(self, request): print(request.user) capname = str('re' + request.user.id) iscached = cache.get(capname) if not iscached: cache.set(capname, 1, 120) email = request.user.email Profile.objects.filter(user_id=request.user.id).update(**{'activation_key': self.activation_code}) subject = "complete you registration" message = "Thankyou. please enter this code to done your registration progress {}".format(self.activation_code) html_message = "http://localhost:4200/accounts/activation/{}".format(self.activation_code) froms = "mail@gmail.com" # html_template = render_to_string('mail/reg_mail.html', {}) send_mail( subject, message, froms, [email], html_message=html_message, # fail_silently=False, ) return Response("ok") else: return Response("time limit") and this is related model: (this is profile model that have relation to User table and have activation_code field to store code) class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='profile') activation_key = models.CharField(max_length=200) bio = models.CharField(max_length=250, null=True, blank=True) email = models.EmailField(null=True, blank=True) job = models.CharField(default="",max_length=250, null=True) server response: detail":"User account is disabled."
tagged with: python-3.x
type: UnansweredQuestion
tagged with: django
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/88742291
has comment: http://stackoverflow.com/comment/88726357
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/88816810
has comment: http://stackoverflow.com/comment/88728925
type: Question
has title: DRF send new activation code to registerd user that is not active
tagged with: django-rest-framework

http://stackoverflow.com/comment/89040381
type: Comment
type: QuestionComment
has text: Hi @Neil Davis could you explain what is your code actually doing?
comment on: http://stackoverflow.com/q/50971367
score: 0

http://stackoverflow.com/a/50965055
score: 0
type: Answer
has body: The code below does not read all in memory. Since you talk 10Gb files this might be of importance. I would do it like: #!/usr/bin/env python3 import json def convert2json(filename): with open(filename) as I: for line in I: d = {"data": line} print(json.dumps(d)) if __name__ == "__main__": import sys convert2json(sys.argv[1]) % python scriptname.py yourfile {"data": "9:username:someemail@gstuff:eafff17afbef485a894][;'.f6d39c56b79:\n"} {"data": "254:Starcius:someemail@gstuff:09160da290bcd1f83fssf0bd260e13d4f:\n"} {"data": "2:username:someemail@gstuff:104b77708bb7c19b9f913449c923a898:8\n"} {"data": "2:username:someemail@gstuff:efc38fca88d8e58089adccce3e05f93\n"} {"data": "254:username:someemail@gstuff:880896502dd68b546258\\][;.'54cca34\n"} {"data": "2:username:someemail@gstuff:647b61ba8f0965e762c579e5b3da9eca:hUr\n"} {"data": "2:username:someemail@gstuff::3e9478fcecb4e90266art87g8fiuba90c6ed5473c:\\^c\n"} {"data": "2:username:someemail@gstuff:9df5783228asdasddas796e18cb12e44da:,M|\n"}
answers question: http://stackoverflow.com/q/50964310
accepted answer of: http://stackoverflow.com/q/50964310
type: AcceptedAnswer

http://stackoverflow.com/comment/88752315
type: QuestionComment
comment on: http://stackoverflow.com/q/50875335
has text: so how to send json???
score: 0
type: Comment

http://stackoverflow.com/q/50907383
answer count: 1
tagged with: network-programming
accepted answer: http://stackoverflow.com/a/50966314
type: AnsweredQuestion
tagged with: linux
has body: Currently I have python script that utilize MSI to gather necessary credentials to obtain public IP address but I also want to get DNS name so it will be easier to connect (being the fact that IP is dynamic) This is my current script: from azure.mgmt.network import NetworkManagementClient from azure.mgmt.resource import ResourceManagementClient, SubscriptionClient from msrestazure.azure_active_directory import MSIAuthentication from azure.common.credentials import ServicePrincipalCredentials from azure.common.credentials import get_azure_cli_credentials from azure.common.credentials import get_cli_profile from azure.common.cloud import get_cli_active_cloud import sys # Create MSI Authentication credentials = MSIAuthentication() # Create a Subscription Client subscription_client = SubscriptionClient(credentials) subscription = next(subscription_client.subscriptions.list()) subscription_id = subscription.subscription_id # Create a Resource Management client resource_client = ResourceManagementClient(credentials, str(subscription_id)) resource_group_name = " " for resource_group in resource_client.resource_groups.list(): print(resource_group.name) resource_group_name = resource_group.name network_client = NetworkManagementClient(credentials, subscription_id) public_ip_name = [] for public_ip_names in network_client.public_ip_addresses.list(resource_group_name): public_ip_name.append(public_ip_names.name) print public_ip_name[0] result_get = network_client.public_ip_addresses.get(resource_group_name, public_ip_name[0], ) print result_get.ip_address Which class/methods should i use?
type: Question
tagged with: azure
has title: Microsoft Azure: obtaining DNS name on linux with Azure API for Python
tagged with: python
has answer: http://stackoverflow.com/a/50966314
score: 0

http://stackoverflow.com/comment/88802255
comment on: http://stackoverflow.com/a/50892623
has text: Worked! Thank you!
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/a/50856466
has body: Check if you can run msguniq manually: $ msguniq --help If that gives you a command not found error, ensure that your PATH environment variable is set correctly for brew.
answers question: http://stackoverflow.com/q/50855974
downvote count: 0
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/88716174
score: 1

http://stackoverflow.com/q/50993624
type: UnansweredQuestion
score: 1
tagged with: django
type: Question
tagged with: web-frontend
tagged with: matplotlib
upvote count: 1
downvote count: 0
favorite count: 0
has title: Django passing Matlpotlib image as variable
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has body: I am trying to display a Matplotlib graph image as a variable in the .html but am unsuccessful. I am new to Django, so any help would be greatly appreciated. I get the following image when I go to the HTML page: from django.shortcuts import render import sys import platform import datetime as dt from datetime import timedelta, date from django.shortcuts import render from django.http import HttpResponse from pylab import * import io inside views.py def submit(request): x = [1, 2, 3, 4, 5, 6] y = [5, 2, 6, 8, 2, 7] plot(x, y, linewidth=2) xlabel('x-axis') ylabel('yaxis') title('sample graph') grid(True) buf = io.BytesIO() plt.savefig(buf, format='png') plt.close() plt_bytes = buf.getvalue() buf.close() return render(request, 'jobs_app/index.html', {'path': plt_bytes}) Inside index.html: &lt; img src="{{ path }}"&gt; The Error code received in the terminal console is [22/Jun/2018 18:39:04] "POST /Home/submit HTTP/1.1" 200 95021 Not Found: /Home/b'/x89PNG/r/n/x1a/n/x00/x00/x00/rIHDR/x00/x00/x02/x80/x00/x00/x01/xe0/x08/x06/x00/x00/x005/xd1/xdc/xe4/x00/x00/x00/x04sBIT/x08/x08/x08/x08|/x08d/x88/x00/x00/x00/tpHYs/x00/x00/x0fa/x00/x00/x0fa/x01/xa8
answer count: 0

http://stackoverflow.com/q/50893563
answer count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/88787935
linked to: http://stackoverflow.com/q/13096604
has body: I have recently undertook converting all of my older batch files towards running on Python 3.6 to allow for them to run on multiple OS's. During this process I have hit a wall, my question is how to best convert these following batch commands to something capable of being run in Python. I have looked around extensively and it has all been for naught. I am open to suggestions. set number=1 set var%number%=[some value here] I have already tried things similar to this in Python: number = 1 ("var"+str(number)) = [some value here] As well as this to try to get the interpreter to process the variable I'm going to assign to done before I attempt assignment. number = 1 var = ("var"+str(number)) (var) = [some value here] The reason why I am trying to convert the first method is so that the program could initially set a changing value to 'var1' then 'var2' then 'var3' etc. Is this one of those things that is unique to batch files and not languages such as Python?
has title: Converting "set var%number%=[value]" where 'number' changes value to a Python script
has answer: http://stackoverflow.com/a/50893804
downvote count: 0
score: 1
accepted answer: http://stackoverflow.com/a/50893804
has answer: http://stackoverflow.com/a/50893887
type: Question
type: AnsweredQuestion
tagged with: python
possible better answer: http://stackoverflow.com/a/50893887
favorite count: 0

http://stackoverflow.com/q/50886444
has comment: http://stackoverflow.com/comment/88786644
has comment: http://stackoverflow.com/comment/88778656
has title: CSRF token changing when trying to log in with python
has comment: http://stackoverflow.com/comment/88774482
downvote count: 0
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
tagged with: python-requests
score: 2
answer count: 0
tagged with: authentication
type: Question
has body: I'm trying to log into a website using python requests with sessions. Part of the login payload is a CSRF token that can be scraped from the login page. So in order to log in, I first GET the login page to scrape the CSRF token and then POST the login credentials with the token. The problem is that somehow the site is changing the "expected" CSRF token on me between requests. I'm not very familiar with how cookies really work, but I guess there may be something wrong with the session management. Here's an example (anonymized a bit) where I GET the CSRF token sequentially 4 times from the same session object. Note that the token changes on the second request, but then changes back on the third and stays the same on the forth. Surprisingly the login doesn't work if I only request the page once. It does work after 3-4 requests, but as you can see that uses the same CSRF token as just requesting once! Any help would be greatly appreciated. SESSION COOKIES: &lt;RequestsCookieJar[]&gt; [GET-ing site login page] CSRF: LK_6-aEvE_Zb_Zb_Zboo3y47yZnhEEQLS-vH0IYjAsg RESPONSE COOKIES: &lt;RequestsCookieJar[&lt;Cookie incap_ses_767_1707636=sU5qZB5t8idbH0/R2u6kCnbPJFsAAAAAp8RfLoNe8mgtYX7xEvpogA== for .[domain].com/&gt;, &lt;Cookie nlbi_1707636_1553025=Oip3RSHTj1lZ8hPpAAAAAAAAAAC5n1FN4OAJXYHbM4x6npWy for .[domain].com/&gt;, &lt;Cookie visid_incap_1707636=W8ZnFEvcTM2CUn3lHxfi53bPJFsAAAAAQUIPAAAAAABeXCa4LfpmJg7LJH6MDpjE for .[domain].com/&gt;, &lt;Cookie AWSALB=zbarZNgpUkIrbM2FAlyUBfjV2ISjZWUxDh9gGfypqHeeB5soBr0bVGex4YKvljag1oKBwcuJRDg3u0FDXwBV3+RgLQEp8TXwf3g6ex1TNRg2y7iDvzdA+ofVhO4R for www.[domain].com/&gt;, &lt;Cookie SERVERID=web01 for www.[domain].com/&gt;, &lt;Cookie ___utmvaLzuKsciB=bgjCCaL for www.[domain].com/&gt;, &lt;Cookie ___utmvbLzuKsciB=kZo XDLOFalE: vtn for www.[domain].com/&gt;, &lt;Cookie ___utmvmLzuKsciB=JWWkKWKUiuL for www.[domain].com/&gt;, &lt;Cookie PHPSESSID=a8165be7052eef205e0a3fdf6d558ef7 for www.[domain].com/nl/&gt;, &lt;Cookie visitorId=5b24cf7723efe8.1415…
tagged with: session

http://stackoverflow.com/q/50923461
answer count: 1
favorite count: 0
has title: python fabric: set environment variable
tagged with: fabric
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/50923548
accepted answer: http://stackoverflow.com/a/50923548
linked to: http://stackoverflow.com/q/7128542
type: Question
has body: I have a question that is somehow covered by documentation but I simply do not understand it. I want to start a flask app and set two shell environment variables first: export FLASK_APP=startup.py export DEBUG=1 pipenv run flask db upgrade In fabric I run the second command: run("pipenv run flask db upgrade") But It eludes me on how to set the environment variables. I read all the examples but I dont understand them.
upvote count: 1

http://stackoverflow.com/a/50999066
has body: i think you are using bs4 from bs4 import BeautifulSoup html_doc = """ 102, 99 """ soup = BeautifulSoup(html_doc, 'html.parser') price_div = soup.find("div", {"class": 'price-block__highlight'}) texts = [x.strip() for x in price_div.text.split(',')] print('.'.join(texts)) Output 102.99
upvote count: 1
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50998990
type: Answer
answers question: http://stackoverflow.com/q/50998990